text:
Q: ASP.NET Data binding not working properly OnSelectedItemChanged event Hi :) I'm making a simple form. The user is prompted to fill in street addresses. Every user is allowed to add up to 5 street addresses. Therefore, I have 5 one and the same controls. I am using a database to provide lists of all countries and cities. I am listening to the OnSelectedItemChanged event on every Country list. When this event is triggered, I am connecting to the database and binding the corresponding City list to the appropriate Country ID.
So, it is fairly simple. I could do 5 different event handlers, but I wanted to create just one event handler and listen to it for every single Country list item.
My Country lists are called lstContactCountry1, lstContactCountry2, ... up to number 5, and the City lists are called lstContactCity1, lstContactCity2 respectively.
I am using DropDownLists.
So, my problem is that when I change the selected item of whichever Country dropdown, except for number 1, the City list has not databinded at all. Databinding works only after I have changed the selected item of the first country list once. Furthermore, even if I have changed the selected item of the first country list once and then, change, for example, the selected item of the second country list the City lists of both of them have binded to the same country, even if they shouldn't.
ASP.NET code-behind:
protected void lstContactCountry1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // lstContactCountry is the sender of the event
        DropDownList lstContactCountry = sender as DropDownList;

        // Get the number of DropDownList
        char lstNumber = lstContactCountry.ID[lstContactCountry.ID.Length - 1];
        lblTemp.Text = "Sender: " + lstContactCountry.ID;

        // Get the IdCountry property from the selected value of the DropDownList
        string idCountry = lstContactCountry1.SelectedValue;

        // Some ADO.NET code :)
        DataSet dataSet = new DataSet();
        SqlConnection connection = new SqlConnection(connectionString);
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT IdCity, CityName FROM City WHERE IdCountry = '" + idCountry + "' ORDER BY CityName", connection);

        adapter.Fill(dataSet, "City");

        // lstContactCity is the City DropDownList below the selected Country DropDownList
        DropDownList lstContactCity = this.Master.FindControl("phSecuredPageMainContent").FindControl("lstContactCity" + lstNumber.ToString()) as DropDownList;
        lblTemp.Text += "<br />Receiver: ";

        lstContactCity.DataSource = dataSet.Tables["City"];
        lstContactCity.DataTextField = "CityName";
        lstContactCity.DataValueField = "IdCity";

        this.DataBind();

        // Adding a default value to the list
        lstContactCity.Items.Insert(0, new ListItem("City", "0"));
        lstContactCity.SelectedIndex = 0;
    }

EDIT:
I found the mistake. It is on this line of code:
        string idCountry = lstContactCountry1.SelectedValue;

I've unintentionally added a "1" at the end of the control's name. That's all. :)

A: You're calling this.DataBind();, which databinds everything on the page that has been bound (datasource set in code behind or a <%# used in aspx code).
You should start fixing this by calling databind on the actual controls that you are binding.
lstContactCity.DataBind();


text:
Q: double (or triple) curly braces in netbeans (e.g Blade Templates) This is strange. I have set my background to black and now when I type double braces in netBeans they both becomes black (and thus invisible as the background is also black)
Hers is an example:
 <title>{{}}</title>

The title in-between becomes all black. Where in NetBean is responsible for this?

A: *

*Go to Tools -> Options

*Select Font & Color

*For Language, select HTML

*Select Text from Category

*Change the color of the text to a more visible color

Another option is, in the same Options dialog, just change the profile. It will give you predefined settings, so you don't have to mess with each category individually, which sometimes is hard to keep track of and maintain.
EDIT
Change the foreground of Expression Delimiter category. I tested it, and it works and maybe Expression Content, depending on your current settings. You my also need to change Text

A:

*

*Go to Tools -> Options

*Select Font & Color

*For Language, select HTML

*Select "Expression Delimiters" from Category

*Set Foreground color to white(if your IDE's background if white). In short, it should be easily visible color when comparing with IDE's
  background color.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux exec program not getting outputted values Not sure why this isn't working...the following cmake script works well on windows:
exec_program(hg ${${PROJECT_NAME}_HGREMOTEDIR}
ARGS "log" "-r" ${${PROJECT_NAME}_HG_HASH_CODE} "--template" "{latesttag}"
OUTPUT_VARIABLE ${PROJECT_NAME}_HG_LAST_TAG)

which gets the latest tag. However, in Fedora 17, when I try to run the ${PROJECT_NAME}_HG_LAST_TAG ends up empty.
My first thought was that the repository location was somehow wrong. So I tried to run:
exec_program(hg ${${PROJECT_NAME}_HGREMOTEDIR}
ARGS "log" "-r" ${${PROJECT_NAME}_HG_HASH_CODE}
OUTPUT_VARIABLE ${PROJECT_NAME}_HG_LAST_TAG)

This fills in ${PROJECT_NAME}_HG_LAST_TAG with:
changeset:   368:a7ab3c8aca83
branch:      Integration
tag:         tip
user:        ******
date:        Wed Dec 11 10:59:33 2013 -0500
summary:     ******

so then I thought maybe "latesttag" wasn't supported..But latest tag "works" in a terminal.
>hg log -r a7ab3c8aca83 --template "{latesttag}"
2.0>

So my last though was that for some reason, the --template command makes it bad. So I made a template with no outside data

hg log -r a7ab3c8aca83 --template foo

and then in the CMake file
exec_program(hg ${${PROJECT_NAME}_HGREMOTEDIR}
ARGS "log" "-r" ${${PROJECT_NAME}_HG_HASH_CODE} "--template" "foo"
OUTPUT_VARIABLE ${PROJECT_NAME}_HG_LAST_TAG)

and ${PROJECT_NAME}_HG_LAST_TAG is still empty. What would cause this? Is there a work around?

A: Looks like a bug in CMake: the output variable will not add parts of a stream that do not end in a new-line.
exec_program(cat ARGS test OUTPUT_VARIABLE TEST_VAR)
if test doesn't end in a new line, the TEST_VAR isn't filled in, despite a valid output in a shell terminal.
If test ends in a new line, then the output is filled in.
The fix, in my case, is to change the template to include a newline:
exec_program(hg ${${PROJECT_NAME}_HGREMOTEDIR}
ARGS "log" "-r" ${${PROJECT_NAME}_HG_HASH_CODE} "--template" "\"{latesttag}\\n\""
OUTPUT_VARIABLE ${PROJECT_NAME}_HG_LAST_TAG)

And then the code works (in both windows and linux).


text:
Q: Wrong format of Year in Chart I am calculating the Annual mean NDVI from S2 data and trying to plot it. However, in the chart, the format of all years is not correctly presented. The 'year' values are presented as double. How I may force it to have the correct date format?
code link: https://code.earthengine.google.co.in/c5c9a6518584e41a2cf1b5793242b315
var Level2 = ee.FeatureCollection("FAO/GAUL_SIMPLIFIED_500m/2015/level2");
var Sindh =Level2.filterMetadata('ADM1_NAME', 'equals', 'Sindh');
print (Sindh.size());
//Load Sentinel 2 image collection and calculate NDVI over the selected time-period
var S2 = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
                  .filterDate('2017-01-01', '2022-01-01')
                  // Pre-filter to get less cloudy granules.
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
                  .select(['B4','B8'])
                  .filterBounds(Sindh);
print (S2.size());

// function to calculate NDVI in S2

var addNDVI = function(image) {
  var NDVI = image.normalizedDifference(['B8', 'B4'])
  .multiply(10000)
  .rename('NDVI')
  .copyProperties(image,['system:time_start']);
  return image.addBands(NDVI);
};

// Add NDVI to the image collection
var withNDVI = S2.map(addNDVI);
//print("NDVI collection", withNDVI.first());

var startyear = 2018;
var endyear = 2021;

// list years over which to obtain time series
var years = ee.List.sequence(startyear, endyear,1);

var byYear = ee.ImageCollection.fromImages(
    years.map(function(y) {
      return withNDVI
        .filter(ee.Filter.calendarRange(y, y, 'year'))
        .reduce(ee.Reducer.mean())
        .set('year', y);
    })
  );

print (byYear);

Map.centerObject(Sindh,6);

var chart = ui.Chart.image.seriesByRegion({
  imageCollection:  byYear,
  band: 'NDVI_mean',
  regions: Sindh,
  reducer: ee.Reducer.mean(),
  scale: 5000,
  seriesProperty: 'ADM2_NAME',
  xProperty: 'year'
});

print(chart);

A: The Earth Engine ui.Chart module uses Google Charts. Google Charts allow you to format axis labels with the hAxis.format and yAxis.format properties. See examples of formatting strings in the Configuration Options section of the line chart docs.
In Earth Engine, you set style properties using the ui.Chart.setOptions method. In your case, you can set the hAxis.format property to '####' to remove the decimal and comma.
For other chart styling tips, see the Earth Engine chart styling page.
chart.setOptions({
  hAxis: {
    format: '####'
  }
});


text:
Q: Logstash Grok regex parsing I am trying to do a parsing on a plaintext message using Grok; my goal is to explode the plaintext to a JSON log.
The message has a quite rigid format, as follows:
<timestamp> <loglevel> <greedydata> field1=value1, field2=value2, .... fieldN=valueN

Where the number of fields is not fixed.
It's possible to capture every field=value pair using a named capturing group, being able to use the same "field" name as the key in the output message?
Thanks

A: TL;DR - use dissect instead of grok

You want something like:
{
  "timestamp": <timestamp>,
  "loglevel": <loglevel>,
  "field1": value1,
  "field2": value2,
  ....
  "fieldN": valueN
}

Where the keys (field1, fieldN etc) are dynamic.
You cannot use grok to do this. Even using a pattern like this (then using array position indices) won't work:
( field[0-9]+=%{DATA:value})+$

You need to handle this a different way. Your options are:

*

*handle this before it hits logstash

*use a ruby filter

*use the dissect filter


text:
Q: AWS CDK - How to invoke function Fn.cidr? I am trying to invoke function Fn.cidr('10.0.0.0/16', 256, '8'); using AWS CDK (typescript https://docs.aws.amazon.com/cdk/api/latest/typescript/api/core/fn.html#core_Fn_cidr), but so far this function keeps returning an array of 1 with a cidr value of 0. It seems like this function doesn't work, does anyone knows how to use this function and have a working example?
I was expecting this function to work as described in https://blog.james.rcpt.to/2018/03/16/aws-vpcs-calculating-subnets-in-cloudformation/
Example:
const subnetCidrs = Fn.cidr('10.0.0.0/16', 256, '8');
console.log('length'+subnetCidrs.length);
for(let cidr in subnetCidrs){
    console.log('cidr: '+cidr);
}

A: The issue is that instead of
for(let cidr in subnetCidrs){
        console.log('cidr: '+cidr);
}

it should be
for(let cidr of subnetCidrs){
        console.log('cidr: '+cidr);
}

it should be let ... of instead of let ... in


text:
Q: Rails: Match a route prefixing all my other routes I'm migrating a Rails application to JRuby running on TorqueBox.
As a result I am now running locally as http://localhost:8080/myapp/ instead of the previous http://localhost:3000/.
As a result none of my routes match.
Is there a quick way to take into account this change without having to rewrite all my routes considering I will be running this from / eventually.
Thanks!

A: You can put config.action_controller.relative_url_root = "/myapp" in the appropriate environment file. In this case, it sounds like it would be config/environments/development.rb. Once you deploy somewhere else and want to use / as your root URL again, just make sure the app is running in the production environment, and it'll work as expected.


text:
Q: How to test for correlation with data that violates assumption of linearity and is not monotonic? I have sampled 8 individuals (birds) from two regions. For each of these 16 individuals I have sampled 9 feathers that have each grown in sequential order (from 1 to 9). Next I have measure both carbon and nitrogen isotopes in each of the feather samples. I have plotted (Fig. 1) my data and in some individuals the relationship between the isotope value and feather position is linear, in some cases monotonic, and in a few cases neither.

I am looking for a non-parametric (?) method to test these three alternative hypotheses for each individual in my dataset.
H1: If the 9 sequentially grown feathers on each individual are grown in the same place under the same diet, the isotope values will be highly correlated with feather position and the regression line essentially flat.
H2: If an individual moves or changes their diet in a systematic way, the isotope values and feather position will correlated but the regression line will be either positive or negative.
H3: If the individual abruptly moves or changes their diet, the isotope values will be uncorrelated and the relationship will not be linear.
Finally, I would like to test the hypothesis that their are differences between the relationship of feather isotopes and feather position is different in individuals between the two regions.
This would more intuitive if all the data (for each individual) was linear or monotonic, but they are not. From my nascent understanding for using either a Pearson's correlation or GLM, these tests assume the data is linear, while the Spearman's assumes the data is monotonic.
Sample Data:
WW_Wing_SI <- structure(list(Individual_ID = c("WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03",
"WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03",
"WW_08A_04", "WW_08A_04", "WW_08A_04", "WW_08A_04", "WW_08A_04",
"WW_08A_04", "WW_08A_04", "WW_08A_04", "WW_08A_04", "WW_08A_05",
"WW_08A_05", "WW_08A_05", "WW_08A_05", "WW_08A_05", "WW_08A_05",
"WW_08A_05", "WW_08A_05", "WW_08A_05", "WW_08A_06", "WW_08A_06",
"WW_08A_06", "WW_08A_06", "WW_08A_06", "WW_08A_06", "WW_08A_06",
"WW_08A_06", "WW_08A_06", "WW_08A_08", "WW_08A_08", "WW_08A_08",
"WW_08A_08", "WW_08A_08", "WW_08A_08", "WW_08A_08", "WW_08A_08",
"WW_08A_08", "WW_08A_09", "WW_08A_09", "WW_08A_09", "WW_08A_09",
"WW_08A_09", "WW_08A_09", "WW_08A_09", "WW_08A_09", "WW_08A_09",
"WW_08A_13", "WW_08A_13", "WW_08A_13", "WW_08A_13", "WW_08A_13",
"WW_08A_13", "WW_08A_13", "WW_08A_13", "WW_08A_13", "WW_08B_02",
"WW_08B_02", "WW_08B_02", "WW_08B_02", "WW_08B_02", "WW_08B_02",
"WW_08B_02", "WW_08B_02", "WW_08B_02", "WW_08G_01", "WW_08G_01",
"WW_08G_01", "WW_08G_01", "WW_08G_01", "WW_08G_01", "WW_08G_01",
"WW_08G_01", "WW_08G_01", "WW_08G_02", "WW_08G_02", "WW_08G_02",
"WW_08G_02", "WW_08G_02", "WW_08G_02", "WW_08G_02", "WW_08G_02",
"WW_08G_02", "WW_08G_05", "WW_08G_05", "WW_08G_05", "WW_08G_05",
"WW_08G_05", "WW_08G_05", "WW_08G_05", "WW_08G_05", "WW_08G_05",
"WW_08G_07", "WW_08G_07", "WW_08G_07", "WW_08G_07", "WW_08G_07",
"WW_08G_07", "WW_08G_07", "WW_08G_07", "WW_08G_07", "WW_08I_01",
"WW_08I_01", "WW_08I_01", "WW_08I_01", "WW_08I_01", "WW_08I_01",
"WW_08I_01", "WW_08I_01", "WW_08I_01", "WW_08I_03", "WW_08I_03",
"WW_08I_03", "WW_08I_03", "WW_08I_03", "WW_08I_03", "WW_08I_03",
"WW_08I_03", "WW_08I_03", "WW_08I_07", "WW_08I_07", "WW_08I_07",
"WW_08I_07", "WW_08I_07", "WW_08I_07", "WW_08I_07", "WW_08I_07",
"WW_08I_07", "WW_08I_12", "WW_08I_12", "WW_08I_12", "WW_08I_12",
"WW_08I_12", "WW_08I_12", "WW_08I_12", "WW_08I_12", "WW_08I_12"
), Feather = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "1", "2", "3", "4", "5", "6", "7", "8", "9", "1", "2", "3",
"4", "5", "6", "7", "8", "9", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "1", "2", "3", "4", "5", "6", "7", "8", "9", "1", "2",
"3", "4", "5", "6", "7", "8", "9", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "1", "2", "3", "4", "5", "6", "7", "8", "9", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "1", "2", "3", "4", "5", "6", "7", "8", "9"
), Delta13C = c(-18.67, -19.16, -20.38, -20.96, -21.61, -21.65,
-21.31, -20.8, -21.28, -20.06, -20.3, -21.21, -22.9, -22.87,
-21.13, -20.68, -20.58, -20.69, -16.54, -15.6, -16.61, -19.65,
-20.98, -21.18, -21.7, -21.18, -21.33, -20.33, -20.28, -20.58,
-20.8, -21.24, -20.94, -20.54, -21.04, -20.42, -21.28, -21.24,
-21.22, -21.2, -21.47, -21.23, -21.89, -21.89, -21.6, -23.86,
-23.95, -24, -24.16, -24.93, -24.93, -24.48, -24.17, -23.1, -21.3,
-21.44, -21.49, -21.49, -21.1, -20.84, -20.78, -21.58, -20.76,
-21.34, -24.13, -23.03, -21.77, -21.4, -21.57, -21.45, -21.32,
-21.59, -20.87, -20.95, -20.76, -20.9, -21.02, -20.84, -21.11,
-20.64, -20.11, -20.32, -20.02, -19.92, -20.05, -20.23, -20.73,
-20.91, -19.87, -19.58, -19.35, -19.38, -19.7, -19.94, -20.43,
-20.08, -20.81, -20.9, -19.24, -21.2, -21.29, -21.85, -22.22,
-22.34, -22.42, -22.69, -22.75, -22.73, -21.61, -21.42, -21.84,
-21.68, -21.79, -21.49, -21.88, -21.62, -21.54, -18.3, -18.53,
-19.55, -20.18, -20.96, -21.08, -21.5, -17.42, -13.18, -22.3,
-22.2, -22.18, -22.14, -21.55, -20.85, -23.1, -20.75, -20.9,
-21.6, -21.77, -22.17, -22.21, -22.24, -22.47, -22.19, -21.89,
-21.89, -24.12, -24.08, -24, -24.2, -24.16, -22.87, -22.51, -22.12,
-22.3), Delta15N = c(7.35, 7.27, 7.23, 7.07, 7.13, 7.38, 6.98,
6.88, 6.72, 5.72, 5.76, 5.51, 6.12, 5.8, 5.34, 5.47, 5.78, 6.2,
7.33, 7.45, 7.3, 7.19, 7.56, 7.54, 8.12, 7.71, 7.44, 9.45, 9.81,
9.7, 9.08, 8.6, 9.34, 10.38, 9.67, 10.48, 7.71, 7.76, 7.95, 7.73,
7.69, 7.24, 6.64, 6.42, 7.31, 8.26, 8.1, 8.07, 8.7, 8.98, 9.44,
7.84, 7.26, 6.05, 8.04, 7.73, 7.55, 6.77, 6.99, 6.84, 7.09, 6.78,
7.07, 6.96, 6, 5.91, 6.48, 7.06, 7.27, 8.32, 7.85, 7.45, 6.9,
6.73, 6.97, 6.67, 6.76, 6.59, 6.58, 6.42, 6.3, 11.64, 11.83,
11.66, 11.3, 11.32, 11.29, 10.91, 10.77, 11.4, 9.5, 9.55, 9.22,
8.84, 8.89, 9.14, 9.8, 9.13, 8.51, 7.7, 7.8, 8.29, 9.65, 10.25,
13.67, 14.66, 13.48, 13.76, 8.7, 8.7, 8.36, 8.11, 8.47, 8.13,
6.88, 7.21, 7.16, 14.07, 13.91, 14.07, 14.26, 13.99, 13.51, 13.77,
14.83, 15.13, 10.93, 10.85, 11.31, 11.28, 11.96, 13.41, 8.12,
12.96, 12.03, 8.16, 8.29, 8.43, 8.53, 8.1, 7.65, 7.6, 7.51, 7.38,
6.44, 6.18, 6.33, 6.49, 6.34, 8.65, 7.73, 7.13, 7.07), Region = c("South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "South", "South", "South", "South",
"South", "South", "South", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North", "North", "North",
"North", "North", "North", "North", "North")), .Names = c("Individual_ID",
"Feather", "Delta13C", "Delta15N", "Region"), row.names = c(NA,
153L), class = "data.frame")

A: Test for a quadratic relationship.
WW_Wing_SI$Feather <- as.numeric(WW_Wing_SI$Feather)
library(ggplot2)
theme_set(theme_bw())
ggplot(WW_Wing_SI,aes(Feather,Delta15N,fill=Individual,colour=Individual))+
    geom_line()+geom_smooth(method="lm",formula=y~poly(x,2),linetype=2)
library(nlme)
m1 <- lmList(Delta15N~poly(Feather,2)|Individual,data=WW_Wing_SI)
summary(m1)

Looking at some of the coefficients in abbreviated form:
, , poly(Feather, 2)1

          Estimate Std. Error t value Pr(>|t|)
WW_08A_08    -1.43       0.67   -2.14  4.3e-02
WW_08B_02    -0.54       0.67   -0.81  4.3e-01
WW_08G_01    -0.73       0.67   -1.09  2.9e-01
WW_08G_05     7.49       0.67   11.21  5.0e-11

At alpha=0.05, feathers A_08 and G_05 have significant linear trends.
(Not really worth worrying about interpreting a linear trend in the
presence of a quadratic term -- see below.)
, , poly(Feather, 2)2

          Estimate Std. Error t value Pr(>|t|)
WW_08A_08    -2.03       0.67   -3.04   0.0056
WW_08B_02    -0.14       0.67   -0.21   0.8358
WW_08G_01     0.23       0.67    0.35   0.7291
WW_08G_05    -0.67       0.67   -1.00   0.3271

At alpha=0.05, feather A_08 has a significant quadratic trend.


text:
Q: TypeError: 'method' object is not subscriptable for pandas dataframe This program shows error in order to get rollingmean output.
    dff = pd.Series([ 0.001215,0.001571,0.002944, 0.005101, 0.007357, 0.009988, 0.013653, 0.017936, 0.021971, 0.025590 ])
    dff = pd.DataFrame(dff, columns=['A'])
    avg = dff['A'].rolling(3).mean()
    avg = [x*5 for x in avg]
    dff['mean'] = avg

    listpos = 0 #We use a counter to move over the different data columns

    for datapoint in dff.A:
        rollingmean = dff.mean[listpos]

After simulation it gives the error message given below:
TypeError                                 Traceback (most recent call last)
<ipython-input-114-61e9145fea85> in <module>()
     13 for datapoint in dff.A:
---> 14     rollingmean = dff.mean[listpos] #Get local mean

TypeError: 'method' object is not subscriptable

What's wrong in this code?

A: Change dff.mean to dff["mean"]. The error is caused by a name conflict that dff.mean is recognized as a library built-in method pd.DataFrame.mean().


text:
Q: Image blur with CSS/Javascript: is it possible? Is it possible to add a blur effect to an image using CSS and Javascript?

A: This is also good to consider:
http://tympanus.net/codrops/2011/12/14/item-blur-effect-with-css3-and-jquery/
http://tympanus.net/codrops/2011/11/18/fullscreen-image-blur-effect-with-html5/

A: Using CSS
.cbp-rfgrid li:hover img {
-webkit-filter: blur(2px);
-moz-filter: blur(2px);
filter: blur(2px);
}

A: Yep, this works a treat:

Pixastic is an experimental library which allows you to perform a variety of operations on images using just a bit of JavaScript. The effects supported out of the box include desaturation/greyscale, invert, flipping, brightness/contrast adjustment, hue/saturation, emboss, blur, and many more...
Pixastic works by utilizing the HTML5 Canvas element which provides access to raw pixel data, thereby opening up for more advanced image effects. This is where the "experimental" part comes into play. Canvas is only supported by some browsers and unfortunately Internet Explorer is not one of them. It is however well supported in both Firefox and Opera and support for Safari only just arrived with the recent Safari 4 (beta) release. Chrome currently works in the dev channel. A few of the effects have been simulated in IE using the age old proprietary filters. While these filters are much faster than their Canvas friends, they are few and limited. Hopefully we will one day have real Canvas on IE as well...

A: StackBlur works: Here's how I'm using it:
also, works on all browsers and ipad!! unlike webkit!!
download StackBlur v5.0 from here: StackBlurv5.0
HTML
<CANVAS ID="top"></CANVAS>

CSS
#top {
  border-radius:         28%;
  -o-border-radius:      28%;
  -webkit-border-radius: 28%;
  -moz-border-radius:    28%;
  position: absolute;
  top: -2px;
  left: -2px;
  z-index: 40;
  width: 208px;
  height: 208px;
}

JS
var topCan = document.getElementById("top");
var toptx  = topCan.getContext("2d");
toptx.drawImage(_specimenImage, 0, 0);
var blur   = 0;

blur       = Math.abs(_sliderF.getPosition(8, -8)); //this returns multiple values
                                                    //based on a new slider position

stackBlurCanvasRGB("top", 0, 0, topCan.width, topCan.height, blur);

NOTES:
Radius values for the stackBlurCanvasRGB function can range from I think 100 to -100.. just play with values, you'll get it working.
..CanvasRGB works faster than CanvasRGBA on iPad.. least that's what I'm noticing on iPad 4th gen.

A: Alternatively you could use StackBlur or Superfast Blur

A: With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image. For Chrome
See live demo and complete source code here
http://purpledesign.in/blog/adjust-an-image-using-css3-html5/
See the following code for more details.
To make an image gray:
img {
 -webkit-filter: grayscale(100%);
}

To give a sepia look:
img {
 -webkit-filter: sepia(100%);
}

To adjust brightness:
img {
 -webkit-filter: brightness(50%);
}

To adjust contrast:
img {
 -webkit-filter: contrast(200%);
}

To Blur an image:
img {
 -webkit-filter: blur(10px);
}

A: Try this:

let blur = document.querySelector("#blur");
let girlImg = document.querySelector("#girlImg");

blur.addEventListener('input', blurring);
function blurring(){
    girlImg.style.filter = `blur(${blur.value}px)`
}

  Blur:
  <input type="range" id="blur" min="0" max="50" value="0">


text:
Q: Error using com.google.gms: google-services: 4.3.4 I am trying to connect Firebase project to my app. But when I add "classpath" com.google.gms: google-services: 4.3.4" AS is giving this error:
Cause: unable to find valid certification path to requested target
What should I do?
build.gradle:
  apply plugin: 'com.android.application'
  apply plugin: 'com.google.gms.google-services'

 buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath "com.android.tools.build:gradle:4.0.1"
    classpath 'com.google.gms:google-services:4.3.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
    repositories {
        google()
        jcenter()
}
}

 task clean(type: Delete) {
 delete rootProject.buildDir
 }

build.gradle(app):
 android {
compileSdkVersion 30
buildToolsVersion "29.0.3"

defaultConfig {
    applicationId "com.vogella.findpeople"
    minSdkVersion 14
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

 dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

implementation 'com.google.firebase:firebase-auth:19.4.0'
implementation 'com.google.firebase:firebase-database:19.5.0'
}

A: The link I flagged should work for you. Try this
classpath 'com.google.gms:google-services:4.3.3'

Replace your classpath with this and resync.

A: Try to move your apply plugin: lines to the app build.gradle file instead of the project one

A: I had a similar problem with regard to adding this classpath 'com.google.gms:google-services:4.3.4' but it seems like I had a bad internet connection, and when I had a strong internet connection, this error occurred,
it also occurred to me that that error was also due to a poor internet connection, after I fixed that then this error occurred,
this was because I included this implementation platform('com.google.firebase:firebase-bom:26.0.0') in build.gradle file within the app directory. So I commented it out and now I was able to run the flutter app in my android device. Like this,


text:
Q: Is this a proper async/await implementation when the nested promises are literally thousands? Regarding: https://github.com/gvasquez95/binance-trader/issues/8
I'm concerned that the actual "inner" await (in every single invocation of getPriceChange) isn't blocking asynchronous invocation of the about 1.5k calls this method has on the outer loop (getPriceChanges). As if it was blocking, then the loop would be serial processing.
From the performance view and timing, I'd say it is working as expected, as it takes just some seconds to complete the whole process but, I'd like a programming ACK of the assumptions, if possible, please.
Block codes for those that don't want to get into GitHub and, prefer the code more visible here:
Outer loop:

async function getPriceChanges (since, breakpoint) {
  const changes = []
  for (const [i, ticker] of tickers.entries()) {
    if (!ticker.includes('BIDR') && !ticker.includes('BIFI')) {
      changes.push(getPriceChange(ticker, since, breakpoint))
    }
  }
  const res = await Promise.all(changes)
  let symbol
  let maxChange = 0
  let slope = 0
  for (const ticker of res) {
    if (ticker.percentChange > maxChange && ticker.slope > Math.pow(10, -1 * NUM_DECIMALS)) {
      maxChange = ticker.percentChange
      symbol = ticker.symbol
      slope = ticker.slope
    }
  }
  return { symbol, maxChange: Math.round(100 * maxChange) / 100, slope: round(slope, NUM_DECIMALS) }
}

Inner getPriceChange function:

async function getPriceChange (symbol, since, breakpoint) {
  const params = {
    TableName: DYNAMODB_TABLE,
    ProjectionExpression: '#timestamp, price',
    KeyConditionExpression: 'symbol = :symbol and #timestamp > :timestamp',
    ExpressionAttributeNames: {
      '#timestamp': 'timestamp'
    },
    ExpressionAttributeValues: {
      ':symbol': symbol,
      ':timestamp': since
    }
  }
  const res = await documentClient.query(params).promise()
  const prev = []
  const recent = []
  const trendData = []
  for (const data of res.Items) {
    if (data.timestamp < breakpoint) {
      prev.push(data.price)
    } else {
      trendData.push({ x: trendData.length, y: data.price })
      recent.push(data.price)
    }
  }
  let sumPrev = 0
  let sumRecent = 0
  for (const price of prev) { sumPrev += price }
  for (const price of recent) { sumRecent += price }
  const avgPrev = sumPrev / prev.length
  const avgRecent = sumRecent / recent.length
  const trend = createTrend(trendData, 'x', 'y')
  return { symbol, percentChange: (100 * (avgRecent - avgPrev)) / avgRecent, slope: trend.slope }
}

Update:
Function execution takes about 30 seconds in a Node.js 14.x AWS Lambda environment, configured with 624 MB RAM and, from a cost perspective the both the DynamoDB query (ReadRequests) costs and Lambda executions are 1/50th of the actual DynamoDB Batch Put operations (WriteRequest), so optimizing the query should be a needed goal.

A: Your loop is correctly asynchronous.  And it seems you're concerned about how many queries will be in flight at the same time.  In your case, you intended for many concurrent queries, and you have done as such.
Explanation
In the simple example of ordering 10 pizzas, consider these arrays:
concurrently
This is an array of pizza orders. We can await all 10 orders to get an array of 10 pizzas.  Assuming there are at least 10 delivery people working that night, there's a good chance you'll get all your pizzas within 30 minutes.
for (let i = 0; i < 10; ++i) {
   orders.push(orderPizza());
}
pizzas = await Promise.all(orders);

sequentially
This is an array of pizzas.  Each order is awaited as it is issued.  If each pizza is delivered in 30 minutes or it's free this is likely to result in about 5 hours (10 * ~30 minutes) of waiting for that last pizza because the next pizza isn't ordered until the previous one arrives.  (No need for a final Promise.all in this case as each promise is already resolved before continuing with the loop.)
for (let i = 0; i < 10; ++i) {
   pizzas.push(await orderPizza());
}

A: Not sure I understand what your question is here exactly. Your assumptions about your code seem to be correct – I (and many others I assume) would be highly surprised if 1500 promises changed anything in their execution model.
As a general note, if you need more control over promise execution, I can recommend checking out Sindre Sorhus' collection of promise helpers. You'll find tools for limiting concurrency, allowing for promise failures, async mapping … and much more.


text:
Q: How to forward a request to other endpoint in node.js In my scenario I need forward get request to another end point. In my machine there are two servers php and node.js server. Node.js is like a "man in the middle", PHP server must work in the same way.
Node.js server code
var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var app = express();

var HTTP_PORT = 3000;

// Create an HTTP service
http.createServer(app).listen(HTTP_PORT,function() {
  console.log('Listening HTTP on port ' + HTTP_PORT);
});

//endpoint for tracking
app.get('/track', function(req, res) {

  sendRequestToOtherEndPoint(req);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

function processRequest(req){
    console.log("request processed");
}

function sendRequestToOtherEndPoint(req){
    //magic here :)
}

When this server receive a get request in port 3000, it process request information and it must forward the same requesto to another end point.
For example:

*

*Get localhost:3000/track?param1=1&param2=2

*Server process get request

*Server forward get request to localhost/final-endpoint?param1=1&param2=2

A: There are a couple of useful libraries that one could use:
http-proxy-middleware:
const proxy = require('http-proxy-middleware')
var apiProxy = proxy('/track', {target: 'http://end-point'});
app.use(apiProxy)

axios-express-proxy
import express from 'express';
import { Proxy } from 'axios-express-proxy';
const app = express();
const port = 3000;

app.get('/track', (req, res) => Proxy('http://end-point', req, res));

A: In you case res.redirect might help.
app.get('/track', function(req, res) {
   // process the request

   // then redirect
   res.redirect('/final-endpoint');
});

Then catch the redirected request in final endpont.
app.get('/final-endpoint', function(req, res) {
       // proceess redirected request here.
});

See the Express docs

A: Depending on what you're trying to do, you can create a new request to the end-point:
//endpoint for tracking
app.get('/track', function(req, res) {

  req.get({url: 'http://end-point', headers: req.headers});

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

More info: https://github.com/request/request

A: If your second endpoint is on a different server, (e.g. PHP) then you're going to need to either redirect the client (as in sohel's answer), or spoof a request from Node to the PHP server and then send the response back to the client. This latter option is definitely non-trivial so I would question whether it's crucial not to use a client redirect.
If you're talking about two express endpoints, then I think the simplest answer might be not to actually forward at all, but just use the endpoint callback directly instead:
app.get('/track', trackCallback);
app.get('/otherendpoint', otherendpointCallback);

function otherendpointCallback(req, res) {
  // do your thing
}

function trackCallback(req, res) {

  otherendpointCallback(req, res);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
};

Depending on exactly what you want to do at the other end point, you might need to spoof some of req's fields (e.g. req.url)


text:
Q: php glob() alternatives I have a wordpress theme that uses glob() function. THe problem is my hosting company has disabled glob(). how to modify the code so that it works using other php functions (opendir() maybe ?)
here is the code:
function yiw_get_tabs_path_files() {
$theme_files_path = YIW_THEME_FUNC_DIR . 'theme-options/';
$core_files_path  = YIW_FRAMEWORK_PATH . 'theme-options/options/';

$tabs = array();

foreach ( glob( $theme_files_path . '*.php' ) as $filename ) {
    preg_match( '/(.*)-options\.(.*)/', basename( $filename ), $filename_parts );
    $tab = $filename_parts[1];

    $tabs[$tab] = $filename;
}

foreach ( glob( $core_files_path . '*.php' ) as $filename ) {
    preg_match( '/(.*)-options\.(.*)/', basename( $filename ), $filename_parts );
    $tab = $filename_parts[1];

    $tabs[$tab] = $filename;
}

return $tabs;

}

A: You can use the combination of opendir, readdir and closedir as you
suggested.
// open the directory
if ($handle = opendir($file_path)) {

  // iterate over the directory entries
  while (false !== ($entry = readdir($handle))) {

    // match on .php extension
    if (preg_match('/\.php$/', $entry) {
      ...
    }
  }

  // close the directory
  closedir($handle);
}

If these too are disabled, you can try the object-oriented Directory class.


text:
Q: java.lang.VerifyError during ejb method call When I try to call a method from a local ejb I have this error :
java.lang.VerifyError: com/pwc/lu/ejb/hcfollowup/staff/HCFStaffManagerLocal.getPersonById(Ljava/lang/Integer;)Lcom/pwc/lu/mapping/hcfollowup/hibernate/global/Person;

HCFStaffManagerLocal is my local interface and getPersonById an ejb method. Person, the result type.
I can get my ejb but error occurs when trying to call getPersonById method.
I don't understand why it get an exception for Person class...
Any ideas ?

A: This question on VerifyError has a lot of good answers - hope one leads to a solution!
There's a chance that the compiled Person class is corrupt and it's worth a try to recompile it with a different java SDK.


text:
Q: Emacs can't find package to install I got this error when trying install Emacs package automatically.
Warning (initialization): An error occurred while loading `/Users/username/.emacs.d/init.el':

File error: http://melpa.org/packages/projectile-20150619.800.el, Not found

To ensure normal operation, you should investigate and remove the
cause of the error in your initialization file.  Start Emacs with
the `--debug-init' option to view a complete error backtrace.

A: You need to first refresh ELPA package archives by M-x package-refresh-contents, because yours are out-of-date so the package manager can't download package for you.
You can also install packages from Package Menu (entering via M-x list-packages), refreshing will be done automatically.

A: And here's my solution:

*

*Open your browser, and enter: http://melpa.org/

*Search package name: 'projectile'

*Then download and extract the package into ~/.emacs.d/elpa

A: If you use ubuntu you can also just use apt-get install elpa-projectile as described in documentation.

A: One reason this may be happening is that you may be trying to set up the package in your emacs.el file before setting up the melpa connection, so your package list is much smaller. Try disabling it there and refreshing the package list to see if that helps.


text:
Q: Wordpress http post 404 I have an error in WP that every time I http post I get a 404
I have ready about the error with field names and it is not that, if the fields are named random names, or their are no fields, I still get the 404 error.
It happens with any http post I get a 404, if it is on the same server or not.
This only happens when permalink is set to "Post name"
Any help fixing this error would be gratefully appreciated

A: Cleared the cache and restarted the router (dynamic IP) and it worked, host must have confused me with a hacker


text:
Q: Fatal error: Uncaught InvalidArgumentException when trying to upload file to AWS I have a problem with php 8, the code that I show works perfectly in php5 but in php 8 it shows me an error and I don't know how to solve it.
    $s3 = S3Client::factory(
                        array(
                            'credentials'   => array(
                                'key'       => IAM_KEY,
                                'secret'    => IAM_SECRET
                            ),
                            'version' => 'latest',
                            'region'  => 'eu-west-1'
                        )
                    );
$s3->putObject(
                    array(
                        'Bucket'        => RUTA_REPOSITORIO,
                        'Key'           => $_FILES['Archivo_'.$i]['name'],
                        'SourceFile'    => $_FILES['Archivo_'.$i]['tmp_name']
                        //'Body'            => $_FILES['Archivo_'.$i]['tmp_name']
                    )
                );

An uncaught Exception was encountered
Type: Guzzle\Common\Exception\InvalidArgumentException
Message: Invalid handle provided


text:
Q: Converting XML to Python object - multiple IF statements I'm trying to write my own logic to parse an XML string and convert it into a Python object. It's requiring me to do a bunch of
attribute1 = xml_element.find('ATTRIBUTE1')
attribute2 = xml_element.find('ATTRIBUTE2')

And then several:
if attribute1 is not None:
    obj.attribute1 = attribute1.text
if attribute2 is not None:
    obj.attribute2 = attribute2.text

These multiple if statements (there's almost 50), is causing 4D to show low test coverage (I'm not testing each if statement, obviously) and also say my function has high cognitive complexity. Wondering if there's a way to do this without having multiple if statements? (Third party packages are not an option)

A: You could use a method to check if the object is None
@staticmethod
def assign_attribute(attribute):
    if attribute is not None:
        return attribute.text
    return None

And then simply call it and assign the text or None if the attribute is null:
obj.attribute1 = assign_attribute(attribute1)
obj.attribute2 = assign_attribute(attribute2)

Now you only have one "if" statement.
Edit
This code assumes you are creating and initializing the object from your XML for the first time, if obj.attribute1 already contains a value and then you use the assign_attribute method and the attribute is None, the original value will be cleared.
If you want to keep existing values, then the method could be something like this:
@staticmethod
def assign_attribute(xml, attribute_name, current_value):
    attribute = xml.find(attribute_name)
    if attribute is not None:
        return attribute.text
    elif current_value is not None:
        return current_value
    else
        return None

obj.attribute1 = assign_attribute(xml_element, 'ATTRIBUTE1', obj.attribute1)
obj.attribute2 = assign_attribute(xml_element, 'ATTRIBUTE2', obj.attribute2)


text:
Q: Printing webpage to console via CURL.h In the wake of a previous thread Building curl 7.46.0, I've tested the below sample code which does compile without errors, but does not print anything on my console.
#include <iostream>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.cnn.com/");
        system("pause");
        res = curl_easy_perform(curl);
        /* always cleanup */     curl_easy_cleanup(curl);
    }
    //system("pause");
    return 0;
}

Is this result due to the setup adopted while installing libcurl? As a matter of fact, to get libcurl.dll and libcurl.lib I've used:
1 - (release mode) : nmake /f Makefile.vc mode=dll VC=12
2 - (debug mode)   : nmake /f Makefile.vc mode=dll VC=12 DEBUG=yes
Best,
Expectation: Something like

[EDIT] : Valid Code
#include<string>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
CURL *curl = curl_easy_init();
if (curl) {
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "http://edition.cnn.com/");
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    system("pause");
}
}

A: As the documentation at
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
suggests, you need to specify a callback function that will write the
html to some buffer. Then, you can use that buffer to print the
contents. Here is how you do it:
#include <iostream>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>
#include <string>

static size_t getHtmlCallback(void *contents, size_t size, size_t nmemb, void *ptr)
{
    // Cast ptr to std::string pointer and append contents to that string
    ((std::string*)ptr)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    std::string htmlBuffer;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.cnn.com/");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getHtmlCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &htmlBuffer);
        res = curl_easy_perform(curl);
        if(CURLE_OK == res)
        {
            std::cout << htmlBuffer << std::endl;
        }
        curl_easy_cleanup(curl);
    }

    return 0;
}

A: It appears that libcurl is failing (i.e. curl_easy_init is returning NULL).  Sadly, according to http://curl.haxx.se/mail/lib-2009-11/0243.html you have to use a debugger to find out why.


text:
Q: Method to instantiate objects Would like to create a method that instantiate  objects.
- (NSArray *) make3Of : (Class) type
{
    ...
    type * temp = [[type alloc] ...
    ...
}

But I get a warning from Xcode ...
Actual warning:
"Class method +alloc not found (return type defaults to 'id')"
Is there a better/correct way to do this?
Actual code:
- (NSArray *) getBoxesOfType: (Class <ConcreteBox>) type StartingFrom: (uint64_t) offset
{
    NSMutableArray *valueArray = [[NSMutableArray alloc]initWithObjects: nil];

    for (uint64_t i = offset; i< boxStartFileOffset + self.size; i += [self read_U32_AtBoxOffset:i])
    {
        if ([[self read_String_OfLen:4 AtBoxOffset:offset + 4] isEqual:[type typecode]]) {

            [[type alloc]initWithFile:file withStartOffset:i]; //warning here;

            //yes I plan to assign it to a variable
            //(originally of "type" but that won't work as AliSoftware pointed out, will be using "id" instead.

            ...

        }
    }
}

Same as example, I'm trying to instantiate a couple of objects.
Code for protocol:
#import <Foundation/Foundation.h>

@protocol ConcreteBox

+ (NSString *) typecode;

- (id) initWithFile: (NSFileHandle *) aFile withStartOffset: (uint64_t) theOffset;

@end

A: You can't use a variable (in your case type)... as a type for another variable!
In your code, both type and temp are variables, that's a syntax error.
As you don't know the type of the variable as compile time, use the dynamic type id instead. This type is specifically designed to handle cases when the type is not defined at compile time.
So your code will look like this:
-(NSArray*)make3Of:(Class)type {
  id obj1 = [[[type alloc] init] autorelease];
  id obj2 = [[[type alloc] init] autorelease];
  id obj3 = [[[type alloc] init] autorelease];
  return [NSArray arrayWithObjects:obj1, obj2, obj3, nil];
}


text:
Q: Python Dictionary Print First occurence In Python, I currently have a dictionary (it has a composite key from a list within a list) that looks similar to the following when I print it:
the first value is a number, the second value (A or B) refers to a text value and the numbers are a count of the times they appear in the original list of list that this dictionary was derived from.
What I need is a way of printing out the data in the following format. For the unique occurrences of the numeric value in the dictionary (ie. in this case the first and third values), print out the associated text value along with its count. So it would look like
Type: 111 Text Count
       A     4
       B    10

      Total: 14

Type: 112 Text Count
       A      3

     Total:   3

I know I need to use some sort of while loop when combined with If statements. From what I have researched so far (pertinent to what I have been taught so far for Python), I need to write loops with if statements to print only what I want to print. So I need to print new Numeric Values the first time they occur, but not the second (or third or fourth, etc) time they occur. I assume to partially do this I put them in a variable, then compare them to the current value. If they are the same, I don't print them, but if they are different, I print the "total" of the old numeric values, add it to the overall total, then print the new one.

A: Instead of one flat dictionary, I would use a hierarchy of objects, such as dicts inside a dict, tuples inside a dict, etc.
Considering an example with dicts inside a dict:
data = {
    '111': {
        'A': 4,
        'B': 10,
    },
    '112': {
        'A': 3
    },
}

Now you can more easily access the contents. For instance display properties inside '111':
for key in data['111']:
    print "%s\t%s" % (key, data['111'][key])

The desired output can be created somewhat trivially by combining two for-loops:
for datatype in data:
    print("Type: %s Text Count" % datatype)
    items = data[datatype]
    total = 0
    for key in items:
        print "%s\t%s" % (key, items[key])
        total += items[key]
    print("Total:\t%s\n" % total)

Running the above with the given data would result in the following output:
Type: 111 Text Count
A       4
B       10
Total:  14

Type: 112 Text Count
A       3
Total:  3

A: It seems to me that a better data structure would be:
{111:[('A', 4),('B',10)], 112:[('A': 3)]}

Then you can print the dict easily:
for k,v in d.items():
   print "Type: {0}\t Text Count".format(k)
   for item in v:
       print "\t\t{0}  {1}".format(*v)

To convert your dict to this form, I'd use a defaultdict:
from collections import defaultdict
d = defaultdict(list)
for k,v in yourdict.items():
    new_key,value0 = (x.strip() for x in k.split(','))
    d[int(new_key)].append((value0,v))

A: Since this is homework, I will give you code that is almost the answer:
myDict = {'111, A': 4, '112, A': 3, '111, B': 10} # input

# keep track of the first half of the composite keys that you've already handled
# This is used to avoid redundant printing
done = set()

for key in myDict:
    # first half of your composite key (eg. '111')
    # I'll be using '111' to explain the rest of the code
    prefix = key.split(',')[0]

    if prefix not in done: # if you haven't already printed out the stuff for '111'
        print prefix # print '111'
        done.add(prefix) # add '111' to done, so that you don't print it out again

        # for all keys in myDict that are of the form "111,X" where X can be anything (e.g. A)
        for k in [k for k in myDict if k.split(',')[0]==prefix]:

            # print a <tab> and the suffix (in our example, "A") and the count value (in myDict, this value is 4)
            print '\t', k.split(',')[1], myDict[k]

Outputs:
111
     B 10
     A 4
112
     A 3

This requires very small modifications to get you to where you need to be.
EDIT: "explain how the for k in [k for k in myDict if k.split(',')[0]==prefix]: works"
There are two parts to that statement. The first is a simple for-loop (for k in …), which works as usual. The second is the list comprehension [k for k in myDict if k.split(',')[0]==prefix]. This list comprehension can be rewritten as:
myList = []
for k in myDict:
    if k.split(',')[0]==prefix:
        myList.append(k)

and then you would do
for k in myList:

There is something to be said about for k in myDict. When you iterate over a dict like that, you iterate only over the keys. This is the same as saying for k in myDict.keys(). The difference is that myDict.keys() returns a new list (of the keys in myDict) which you then iterate over, whereas for k in myDict iterates directly over all the keys in myDict

A: You can use tuples as your keys. Instead of '111, A' try ('111', 'A')
It allows you to easily loop through the dictionary looking for matches to either the first or second key value. Just like what you have, except change the key:
for row in lists:
    key = (row[0], row[1])
    if key in dictionary:
        dictionary[key] += 1
    else:
        dictionary[key] = 1

#gives
dictionary = {('111', 'A'): 4, ('111', 'B'):10, ('112', 'A'):4}

Now, you're exactly right: you need a variable to store the total, you need to loop through the dictionary, and you need to use conditional statements inside the loop. What exactly are you asking about?
You can loop through the dictionary like this:
for k in d:
    print k, d[k]

If you keep your string keys, you will need to extract the two values from each key, which you can do with split. (No need to do this step if you use tuples):
#with string keys
key_1, key_2 = k.split(',')

You need to test if the first key value matches the desired number, and then you want to print the letter and the value d[k], and update the total variable:
if key_1 == desired:
    print key_2, d[k]
    total += d[k]

So you can put it together, inside a function like this:
def f(d, desired):
    total = 0
    for k in d:
        key_1, key_2 = k.split(',')
        if key_1 == desired:
            print key_2, d[k]
            total += d[k]
    print 'total', total

If you use tuples instead of keys, you can remove the split step, and just use k[0] and k[1] to get the two values:
def f(d, desired):
    total = 0
    for k in d:
        if k[1] == desired:
            print k[0], d[k]
            total += d[k]

    print 'total', total

A: I wrote a straightforward function that prints what you want. It needs the dictionary as the first argument and the type as a int as second (e.g. fancy_print({'111, A': 4, '112, A': 3,'111, B': 10}, 111)):
def fancy_print(d, typ):
    res=[]
    for k in d:
        kp=[q.strip() for q in k.split(',')]
        if int(kp[0])==typ:
            res.append((kp[1],d[k]))
    res.sort()
    print('\tType: %d Text Count' % typ)
    for t,n in res:
        print('\t%s\t%2d' % (t, n))
    print()
    print('\tTotal:\t%2d' % sum([n[1] for n in res]))


text:
Q: Qt forbid declaration of QListView with no type I have a very strange error in my Qt project. Here is the code, the main_window.h:
#include <QtGui>
#include <QtSql>

class main_window : public QTabWidget
{
    Q_OBJECT

    /// @name List Widgets
private:
    QListWidget*    m_documents_list;
....

and here is main_window.cpp:
...
void main_window::create_documents_widget()
{
    m_documents = new QWidget(this);
    m_documents_list = new QListWidget(m_documents);
}
...

The problem that I can't understand is in QListView, I'm not using it in my project. There is only QListWidget, but when I'm trying to build the project the following errors occur:
qlistview.h:194: error: ISO C++ forbids declaration of 'QListView' with no type
qlistview.h:194: error: expected ',' or '...' before '&' token
Also the following strange errors:
qlistwidget.h:308: error: no 'void QListWidget::removeItemWidget(QListWidgetItem)' member function declared in class 'QListWidget'*
qlistwidget.h:311: error: no 'void QListWidget::addItem(QListWidgetItem)' member function declared in class 'QListWidget'*
qlistwidget.h:314: error: no 'QListWidgetItem QListWidget::itemAt(int, int) const' member function declared in class 'QListWidget'*
etc.
Thanks in advance.
UPD: I'm using QtCreator 2.2.1 on Windows 7.
UPD2: Qt version is 4.7.1.
UPD3: The complete output
In file included from c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/QtGui:68,
                 from ..\my_project\/main_window.h:4,
                 from ..\my_project\main.cpp:2:
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:194: error: ISO C++ forbids declaration of 'QListView' with no type
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:194: error: expected ',' or '...' before '&' token
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:194: error: ISO C++ forbids declaration of 'QListView' with no type
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:194: error: ISO C++ forbids declaration of 'QListView' with no type
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:194: error: expected ';' before '&' token
In file included from c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/QtGui:69,
                 from ..\my_project\/main_window.h:4,
                 from ..\my_project\main.cpp:2:
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:202: error: redefinition of 'class QListWidget'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistview.h:58: error: previous definition of 'class QListWidget'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:308: error: no 'void QListWidget::removeItemWidget(QListWidgetItem*)' member function declared in class 'QListWidget'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:311: error: no 'void QListWidget::addItem(QListWidgetItem*)' member function declared in class 'QListWidget'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:314: error: no 'QListWidgetItem* QListWidget::itemAt(int, int) const' member function declared in class 'QListWidget'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h: In member function 'void QListWidgetItem::setSelected(bool)':
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:318: error: 'class QListWidget' has no member named 'setItemSelected'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h: In member function 'bool QListWidgetItem::isSelected() const':
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:321: error: 'class QListWidget' has no member named 'isItemSelected'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h: In member function 'void QListWidgetItem::setHidden(bool)':
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:324: error: 'class QListWidget' has no member named 'setItemHidden'
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h: In member function 'bool QListWidgetItem::isHidden() const':
c:\QtSDK\Desktop\Qt\4.7.3\mingw\include\QtGui/qlistwidget.h:327: error: 'class QListWidget' has no member named 'isItemHidden'

A: It should be noted that QListWidget inherits from QListView, so you are indirectly using it.
The error your getting looks like you're simply missing a #include <QListWidget> line in your header file.
Also, it could be that that you're missing #include guards in your header file
#ifndef MYCLASS
#define MYCLASS

class MyClass { ... };

#endif

If your header file is #included by more than one project then that would explain the errors you're seeing.

A: Firstly - you should also mention qt version, as in this case that's most important.
This seems like some weird quirk of compiler or qt - my recomendation would be first to create simplest program where problem occurs. If it shows also in program like
#include <QtGui/QListWidget>
int main(int argc, char* argv[]){
    QListWidget* w = 0;
}

then it is some problem with qt headers of compiler - then answer cannot be provided from data provided. If it works, then try to slowly add other elements of your code to this simple file - most likely at some point you will get the same error again - then you will know that last added piece of code is guilty. Some additional thinking might be required to figure out how to remove problem once located.


text:
Q: Grunt / npm error on production server (Ubuntu 14.04.3 LTS) I'm getting this error on the production server (local is fine both Windows and OSX)
/home/myuser/my-app/node_modules/grunt/node_modules/findup-sync/lib/findup-sync.js:33
}).flatten().uniq().value();
   ^
TypeError: undefined is not a function
    at Object.module.exports [as findup] (/home/myuser/my-app/node_modules/grunt/node_modules/findup-sync/lib/findup-sync.js:33:8)
    at Task.task.init (/home/myuser/my-app/node_modules/grunt/lib/grunt/task.js:427:16)
    at Object.grunt.tasks (/home/myuser/my-app/node_modules/grunt/lib/grunt.js:120:8)
    at Object.module.exports [as cli] (/home/myuser/my-app/node_modules/grunt/lib/grunt/cli.js:38:9)
    at Object.<anonymous> (/usr/local/lib/node_modules/grunt-cli/bin/grunt:45:20)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)

So far I tried removing the node modules, clearing the cache and reinstalling but no success.
rm -rf node_modules && npm cache clean && npm install

I've also tried installing the module it's complains about:
 npm install findup-sync -g && npm link findup-sync

Also I've checked that my .gitignore file contains the dist folder
I'm going to paste my package.json and bower.json files any help would be much appreciated.
Thanks!

package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "dependencies": {
    "bower": "^1.4.1",
    "grunt": "^0.4.5",
    "grunt-cli": "^0.1.13",
    "connect-modrewrite": "^0.8.2",
    "grunt-autoprefixer": "^3.0.3",
    "grunt-concurrent": "^2.0.2 ",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-compass": "^1.0.3",
    "grunt-contrib-concat": "^0.5.1",
    "grunt-contrib-connect": "^0.8.0",
    "grunt-contrib-copy": "^0.8.1",
    "grunt-contrib-cssmin": "^0.13.0",
    "grunt-contrib-htmlmin": "^0.4.0",
    "grunt-contrib-imagemin": "^0.9.4",
    "grunt-contrib-jshint": "^0.11.2",
    "grunt-contrib-uglify": "^0.9.1",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-filerev": "^2.3.1",
    "grunt-google-cdn": "^0.4.3",
    "grunt-newer": "^1.1.1",
    "grunt-ng-annotate": "^1.0.1",
    "grunt-svgmin": "^2.0.1",
    "grunt-usemin": "^3.1.0",
    "grunt-wiredep": "^2.0.0",
    "load-grunt-tasks": "^3.2.0",
    "time-grunt": "^1.2.1",
    "grunt-ng-constant": "^1.1.0",
    "jasmine-core": "^2.3.4",
    "grunt-karma": "^0.12.0",
    "connect-livereload": "^0.5.3",
    "jshint-stylish": "^2.0.1",
    "karma": "^0.13.9",
    "karma-jasmine": "^0.3.5",
    "karma-phantomjs-launcher": "^0.2.1",
    "phantomjs": "^1.9.18"
  }
}

bower.json

{
  "name": "myapp",
  "version": "0.0.1",
  "dependencies": {
    "angular": "^1.3.0",
    "json3": "^3.3.0",
    "es5-shim": "^4.0.0",
    "bootstrap-sass-official": "^3.3.5",
    "angular-animate": "^1.3.0",
    "angular-cookies": "~1.4.0",
    "angular-messages": "^1.3.0",
    "angular-resource": "^1.3.0",
    "angular-route": "^1.3.0",
    "angular-sanitize": "^1.3.0",
    "angular-touch": "^1.3.0",
    "angular-bootstrap": "~0.12.0",
    "font-awesome": "~4.2.0",
    "angular-progress-arc": "~1.0.0",
    "angular-xeditable": "~0.1.9",
    "angular-moment": "~0.10.1",
    "angular-native-picker": "~1.0.4",
    "angular-sweetalert": "~1.1.0",
    "angular-base64": "~2.0.5",
    "angular-timer": "~1.3.3",
    "angular-bootstrap-colorpicker": "~3.0.18"
  },
  "devDependencies": {
  },
  "appPath": "app",
  "resolutions": {
    "angular": "1.4.4"
  }
}

A: I've managed to get to the bottom of it. A bit of background, I was experiencing this problem on a DigitalOcean droplet which was a 512M RAM/1 CPU.
Because of limited amount of RAM npm install used to fail / be killed silently so it wouldn't get the chances to finish installing and I wouldn't get an error / warning message either.
So in the end the solution was simple: increase the RAM and then run -rf node_modules && npm cache clean && npm install and it worked without any issues afterwards.
Hopefully some of you will find this helpful.
TL;DR; Try increasing your RAM size and then run -rf node_modules && npm cache clean && npm install


text:
Q: Ubuntu 13.10 AdobeAIR application: Failed to load module "unity-gtk-module" I have installed AdobeAIR on 13.10, but am getting the following error messages when using:
Gtk-Message: Failed to load module "overlay-scrollbar"
Gtk-Message: Failed to load module "unity-gtk-module"

Has someone faced this issue. I looked at comment giving a possible resolution here , but that didn't help, as I already have those packages installed.
Basically to install AdobeAIR, being a 32-bit, I had to install various i386 packages:
libgtk2.0-0:i386 libnss3-1d:i386 libnspr4-0d:i386 lib32nss-mdns libxml2:i386 libxslt1.1:i386

When I run the program as root, it opens up properly without errors. But that is not an option.
Could it be a problem that necessary modules are not getting loaded on non-root user's environment.


text:
Q: Gson deserialization of List into realmList I'm using retrofit with gson to deserialize my json into realm objects. This works very well for the most part. Trouble arises when dealing with

RealmList(String(or any other basic data type))

Since Realm doesnt support RealmList where E doesnt extend Realm object, I wrapped String in a RealmObject.
public class RealmString extends RealmObject {
  private String val;

  public String getValue() {
    return val;
  }

  public void setValue(String value) {
    this.val = value;
  }
}

My realm Object is as below
    public class RealmPerson extends RealmObject {
    @PrimaryKey
    private String userId;
    ...
    private RealmList<RealmString> stringStuff;
    private RealmList<SimpleRealmObj> otherStuff;

    <setters and getters>
   }

SimpleRealmObj works fine as it only has String elements
    public class SimpleRealmObj extends RealmObject {
    private String foo;
    private String bar;
       ...
    }

How can I deserialize stringStuff? I tried using a gson TypeAdapter
public class RealmPersonAdapter extends TypeAdapter<RealmPerson> {
    @Override
    public void write(JsonWriter out, RealmPerson value) throws IOException {
        out.beginObject();
        Log.e("DBG " + value.getLastName(), "");
        out.endObject();
    }

    @Override
    public RealmPerson read(JsonReader in) throws IOException {
        QLRealmPerson rList = new RealmPerson();
        in.beginObject();
        while (in.hasNext()) {
            Log.e("DBG " + in.nextString(), "");
        }
        in.endObject();

        return rList;
    }

However I still hit the IllegalStateException

2334-2334/com.qualcomm.qlearn.app E//PersonService.java:71﹕ main com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was NAME at line 1 column 3 path $.

I tried RealmList, RealmString adapter earlier to no avail.
The only workaround I managed to find so far is https://github.com/realm/realm-java/issues/620#issuecomment-66640786
Any better options?

A: The error message "Expected a string but was NAME" can be solved by retrieving the name of the json object in the JsonReader before the actual json object (which is a String in your case).
You can take a look at the Android documentation for JsonReader. It has detailed explanation and code snippet. You can also take a look at the readMessage method in the sample code snippet in the documentation.
I have modified your read method to what I think it should be. NOTE: I didn't test the code, so there may be some minor errors in it.
@Override
public RealmPerson read(JsonReader in) throws IOException {
    RealmPerson rList = new RealmPerson();
    in.beginObject();
    String name = "";
    while (in.hasNext()) {
        name = in.nextName();

        if (name.equals("userId")) {
            String userId = in.nextString();
            // update rList here
        } else if (name.equals("otherStuff")) {
            // since otherStuff is a RealmList of RealmStrings,
            // your json data would be an array
            // You would need to loop through the array to retrieve
            // the json objects
            in.beginArray();
            while (in.hasNext()) {
                // begin each object in the array
                in.beginObject();
                name = in.nextName();
                // the RealmString object has just one property called "value"
                // (according to the code snippet in your question)
                if (name.equals("val")) {
                    String val = in.nextString();
                     // update rList here
                } else {
                    in.skipValue();
                }
                in.endObject();
            }
            in.endArray();
        } else {
            in.skipValue();
        }
    }
    in.endObject();

    return rList;
}

Let me know if this helps.

A: My gson typeAdapter was the culprit.
The above error was seen as I wasnt deserializing the json into RealmPerson correctly, the first field is not a String, hence

in.nextString()

was borking.
I looked at some example code and it hit me, I didnt have to use

in.beginObject() and in.endObject()

to deserialize a String. The below code works.
public class QLRealmStringAdapter extends TypeAdapter<QLRealmString> {
@Override
public void write(JsonWriter out, QLRealmString value) throws IOException {
    Log.e("DBG " + value.getValue(), "");
    out.value(value.getValue());
}

@Override
public RealmString read(JsonReader in) throws IOException {
    RealmString rString = new RealmString();
    if (in.hasNext()) {
        String nextStr = in.nextString();
        System.out.println("DBG " + nextStr);
        rString.setValue(nextStr);
    }

    return rString;
}

}
Hope this helps someone.

A: It is better to use JsonSerializer and JsonDeserializer rather than TypeAdapter for your RealmObject, because of 2 reasons:

*

*They allow you to delegate (de)serialization for your RealmObject to the default Gson (de)serializer, which means you don't need to write the boilerplate yourself.

*There's a weird bug in Gson 2.3.1 that might cause a StackOverflowError during deserialization (I tried the TypeAdapter approach myself and encountered this bug).
Here's how (replace Tag with your RealmObject class):
(NOTE that context.serialize and context.deserialize below are equivalent to gson.toJson and gson.fromJson, which means we don't need to parse the Tag class ourselves.)
Parser + serializer for RealmList<Tag>:

public class TagRealmListConverter implements JsonSerializer<RealmList<Tag>>,
        JsonDeserializer<RealmList<Tag>> {

    @Override
    public JsonElement serialize(RealmList<Tag> src, Type typeOfSrc,
                                 JsonSerializationContext context) {
        JsonArray ja = new JsonArray();
        for (Tag tag : src) {
            ja.add(context.serialize(tag));
        }
        return ja;
    }

    @Override
    public RealmList<Tag> deserialize(JsonElement json, Type typeOfT,
                                      JsonDeserializationContext context)
            throws JsonParseException {
        RealmList<Tag> tags = new RealmList<>();
        JsonArray ja = json.getAsJsonArray();
        for (JsonElement je : ja) {
            tags.add((Tag) context.deserialize(je, Tag.class));
        }
        return tags;
    }

}

Tag class:

@RealmClass
public class Tag extends RealmObject {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

Then register your converter class with Gson:
Gson gson = new GsonBuilder()
        .registerTypeAdapter(new TypeToken<RealmList<Tag>>() {}.getType(),
                new TagRealmListConverter())
        .create();

A: i need a jackson serializer and deserializer for the Converting Arraylist to RealmList


text:
Q: How to access recordID from lightning datatable in LWC I wish to navigate to a record by clicking on a button present on lightning datatable. For this, I need to access the recordId of row. I tried using event.detail.row.id but it does not work. I get this error: [Cannot read property 'Id' of undefined]. Am I doing something wrong here?

javascript

navigateToRecordViewPage(event) {

        // View a custom object record.
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: event.detail.row.Id,
                objectApiName: 'Lead', // objectApiName is optional
                actionName: 'view'
            }
        });
    }

HTML

<lightning-datatable
                    key-field="Id"
                    data={wrappers.data}
                    columns={columns}
                    onrowaction={navigateToRecordViewPage}
            </lightning-datatable>

A: I made the following change in javascript function and it worked!
navigateToRecordViewPage(event) {
        this.record = event.detail.row;
        // View a custom object record.
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.record.id,
                //objectApiName: 'Lead', // objectApiName is optional
                actionName: 'view'
            }
        });

A: You can use the native getSelectedRows method of the lightning-datatable and with checkboxes enabled, you can get the ids of the rows that is clicked.
handleClickAdd() {

        var el = this.template.querySelector('lightning-datatable');
        var selected = el.getSelectedRows();
        let selectedIdsArray = [];

        for (const element of selected) {
            //console.log('elementid', element.Id);
            selectedIdsArray.push(element.Id);
        }


text:
Q: ¿Comó incluir de manera inteligen un archivo CSS en PHP? tengo el siguiente inconveniente para aplicar mis estilos CSS en PHP. Bueno la verdad tengo en mi archivo index.php, la estructura y funciones que necesito, por ende he estado reciclado codigó con PHP POO y importandolo con include al resto de archivos al cual le voy a aplicar lo mismo, pero hasta aquí todo perfecto. El problema surge cuado realizo la importación del código con mis estilos CSS.
El código que importo es el siguinete:
<?php
echo "<link rel=stylesheet href=css.css>";
class MenuPagina{
public $folder;
public $pages;

public function __construct($folder,$pages){
$this->folder=$folder;
$this->pages=$pages;
}

public function paginacion(){
$general = 0;
$t_file = glob($this->folder);
$cont=count($t_file);
for ($j=1; $j<=$this->pages; $j++) {
for($i=0; $i<=($txpages-1);$i++){
$fileExtension=explode(".", $t_file[$general]);
$fileExtension=end($fileExtension);
if($fileExtension =="jpg" or $fileExtension=="png" or $fileExtension=="gif"){
echo "".($general+1)."";
} else{
echo "".($general+1)."";
}
  }
}

public function changeFolder($folder){
$this->folder=$folder;
 }

}
$menu = new MenuPagina("*.*",4);
$menu->paginacion();
?>

Al momento de importarlo lo hago de la siguiente forma:
<link rel="stylesheet" href="../css.css">
<?php
include '../index.php';
?>

Pero el resultado que me da al momento de revisar el código generado en html, desde el navegador, se visualiza de la siguiente forma:
<link rel="stylesheet" href="../css.css">
<link rel=stylesheet href=css.css>

Bueno se me ocurrio esta solucón pero no funciona como se espera:
$includeFile = get_included_files();
if($includeFile){
echo "<link rel=stylesheet href=../css.css>";
}else{
echo "<link rel=stylesheet href=css.css>";
}

Este ultimo, lo que hace es dectectar si el archivo se le esta importado o no, en caso de que no se este exportando simplemente no saldra al directorio de raiz.
Agradezco su ayuda.

A: Es importante que recuerdes que una clase, en el contexto de POO, es un modelo que define atributos y métodos; y sirven para crear objetos.
Con este concepto en mente, te diré que no es válido que agregues la línea:
echo "< link rel=stylesheet href=css.css>";

ya que dicha línea no es ni un atributo ni un método de la clase MenuPagina.
Continuando con el concepto de clase, tampoco es válido que agregues dentro de la clase las líneas:
$menu = new MenuPagina("*.*",4) ;

$menu->paginacion();

Lo correcto es eliminar esas tres líneas de las clase, posteriormente crear un archivo de nombre menu.php, por ejemplo, y entonces, ahora sí, incluir la hoja de estilos y crear el objeto.
Por ejemplo, la página "menu.php", quedará así:
< !-- Invocas tu hoja de estilos -->
< link rel=stylesheet href=css.css>

<?php

     //invocas a la clase
     include_once 'MenuPagina.php';

    //Creas el objeto menu
    $menu = new MenuPagina(" * . * ",4);

    //ejecutas el metodo paginacion
    $menu->paginacion();

?>

Doy por hecho que los archivos css.css, MenuPagina.php y menu.php estan al mismo nivel, es decir todos directamente dentro de la carpeta raíz de tu proyecto.


text:
Q: how to make JDialog with checkboxes I am writing a Java program and I ran into a problem. I have an ArrayList<JCheckBox> and I want to show some dialog window with these checkboxes, so I can choose some of them and I want another ArrayList<> of the selected objects as an outcome after closing that dialog. I think I can get results by adding ActionListener to those checkboxes, but I don´t know how to pass that ArrayList<JCheckBox> to the dialog window..
So far I tried something like this:
ArrayList<JCheckBox> al = new ArrayList<JCheckBox>();
for (MyClass mc : sr.getFields().values())
{
    JCheckBox box = new JCheckBox(mc.getType());
    al.add(box);
}
JOptionPane.showConfirmDialog(null, al);

If I try to print the text in the checkbox, it is ok, but the dialog shows only a long line of some text that does not make any sense..
So, is there a way how to do that?
Thanks in advance..

A: The showConfirmDialog method has to interpret the message object in order to render it correctly and it doesn't know how to interpret an ArrayList, you have to add all your elements to an JPanel eg:
JPanel al = new JPanel();
for (MyClass mc : sr.getFields().values()){
    JCheckBox box = new JCheckBox(mc.getType());
    al.add(box);
}
JOptionPane.showConfirmDialog(null, al);

or an Object[] eg:
ArrayList<JCheckBox> al = new ArrayList<JCheckBox>();
for (MyClass mc : sr.getFields().values()){
    JCheckBox box = new JCheckBox(mc.getType());
    al.add(box);
}
Object[] obj = (Object[]) al.toArray(new Object[al.size()]);
JOptionPane.showConfirmDialog(ui, obj);


text:
Q: use iText to read pdf(C#), But I can't find the dynamic link library I already use iText to generate pdf, but now I need to read pdfs(no pictures, only some string)
I have found the example code. Here is the website: http://www.ujihara.jp/iTextdotNET/examples/Chap0112.cs
using com.lowagie.text;
using com.lowagie.text.pdf

But i can't find com.lowagie.text dll through the Internet. I can only find the Java library. I have browsed http://itextpdf.com/, but I didn't find it.

A: I think this is an error in the example - try using iText.text and iText.text.pdf instead.


text:
Q: Bittorent connection is going up and down, how to prevent slowing down of link My Bittorrent, in working time, all  time have a amplitudes, the cable connection from 600 -800 Kb, than in his pick, starting to slow down to zero, wait fo a long time, than start to download with 0,3 or 0,5 Kb. What's is wrong?
Thanks.

A: bittorent and utorent use p2p file sharing protocol. Meaning it gets the file from other users that have downloaded the file. From a ratio of 10, if 10 people has downloaded the file and only one out of ten is sharing it don't expect that your download speed it fast. That's why if you read comments on torrent site the most repeated comment is "PLEASE SEED" meaning "PLEASE SHARE THE FILE" in torrent software like you utorrent and bittorent and keyword is "UPLOAD". Some users after successfully downloading the file they stop it, not noticing that the ''UPLOAD" is still running. That's why your download speed is slow because other users don't upload it AKA ''SEEDING". It's not the fault of your ISP. But it's the fault of the users that have successfully downloaded the file and doesn't seed it.
Long story short, it depends on the external people seeding the same file at the same time.
This is not 100% effective and I agree with William Hilsum sometimes the ports can be deceiving, what you can do is port forwarding the router correctly. You can also test if the ports are forwarded correctly. Change the settings by going to Options>Preferences Change the port to something else and also make sure you "Enable UPnP port mapping", and "Enable NAT-PMP port mapping" Add exceptions to your firewall and make sure your firewall isn't blocking the ports which causes the internet and the downloading speed to go slow.

A: Your question isn't totally clear. If you are saying the speed drops and then remains low? If so, then it could be the ISP throttling the line (as an example). You need to perform some tests to find out.
If this is on a laptop (or if you have access to multiple networks), then try on a different network.
I also suggest you perform a speed test (Google speed test), make a note of the download and upload speed and then start a torrent download. When the torrent slows, try doing the speed test again to see if the issue is with the torrent download only (or not). If the speed test remains fast, the issue is then with the torrent or the program. If the internet is also slow, then it's the ISP (who you'll need to contact direct).

A: What you are seeing is normal with torrents.
If I was you, I would double check that the port forwarding rules are there (or UPnP is working).
I have a gigabit internet connection and if a torrent is not very well seeded (not a load of other people with the file), the connection is usually VERY slow, where as I can download a well seeded file at many MegaBytes a second.
Torrents rely on other people having fast upload speed.


text:
Q: Can Design-by-Contract be applied to dynamic languages as easily/well as to statically-typed ones? The title pretty much sums up the gist.
I'm interested in whether it is possible to enable/disable contract enforcement(s) when using a dynamic language without running a serious risk of poorly/un-diagnosed failure?
If not, the crux seems (to me) to be that any enforcements are a required part of the component's logic, rather than optional/removable as per the spirit of removability of DbC's enforcements.

A: Not only is it possible, there are real-world implementations of this and they've been around for years. Here's a DbC implementation for Python that's twelve years old, for example.

A: I believe lisp has a good design by contract framework.
http://www.cl-user.net/asp/OkD82/sdataQkIGW7mlSHARDQ3r-H8X8yBX8yBXnMq=/sdataQu3F$sSHnB==


text:
Q: left invariant and right invariant imply inversely invariant This is an exercise on page 158 of Conway's text A course in  functional  analysis:
Let $G$ be a locally compact group. If $m$ is a regular Borel measure on $G$, show
that any two of the following properties imply the third:

*

*$m (\Delta g)= m(\Delta)$ for
every Borel set $\Delta$ and every $g$ in $G$;

*$m(g\Delta) = m(\Delta)$ for every Borel set $\Delta$
and every $g$ in $G$;

*$m(\Delta) = m(\Delta^{-1})$ for every Borel set $\Delta$.

The proof for 1&3 $\Rightarrow$2  is  quite simple $m(g\Delta)=m(\Delta^{-1}g^{-1})=m(\Delta^{-1})=m(\Delta)$. Similarly, we can prove  2&3 $\Rightarrow$ 1. But how to prove  1&2 $\Rightarrow$ 3?  How to  obtain $\Delta^{-1}$ from  $\Delta$?

A: I assume that you know that a (left-invariant) Haar measure is unique up to constants.
If 1) and 2) hold, define $m'(B) := m(B^{-1})$. It is not hard to check that $m'$ is a regular Borel measure. Furthermore, $m'(gB) = m((gB)^{-1}) = m(B^{-1} g^{-1}) = m(B^{-1}) = m'(B)$, so that $m$ and $m'$ are both left-invariant regular Borel measures on $G$, and hence $m' = c \, m$ for some $c \in [0,\infty]$ (note that $m \equiv 0$ if and only if $m' \equiv 0$).
The claim is clear if $m = 0$. Otherwise, by regularity, there is a compact set $K \subset G$ of positive measure. Set $K' := K \cup K^{-1}$ and note $m(K') = m'(K')$, so that necessarily $c=1$; that is, $m = m'$.


text:
Q: calling awk on output of another script I am trying to use awk to search the output of a script for a specific line. Can someone explain why this doesnt return the output: 16.72?
my bash script:
speed=$(./speedtest-cli)
awk '/Download:/ {print $2}' $speed

speedtest-cli
pi@raspberrypi ~/Desktop/PiControl $ ./speedtest-cli
Retrieving speedtest.net configuration...
Retrieving speedtest.net server list...
Testing from Charter Communications (xxxxxx)...
Selecting best server based on latency...
Hosted by Charter Communications (yyyy, zz) [67.01 km]: 44.035 ms
Testing download speed........................................
Download: 16.72 Mbit/s
Testing upload speed..................................................
Upload: 3.45 Mbit/s

Note (included in the comments below) I am trying to avoid one-liners because I plan to print multiple lines from the output.
EDIT:
To clarify my end goal. I am trying to run ./speedtest-cli (I am trying not to change this file). I am trying to take its output (the download speed, the upload speed, and the latency) and pass them as individual parameters to another script that will write them to a database. (This project is purely for personal use.... im not trying to use it in an enterprise environment)
From the speedtest-cli output above I want to do this:
MY GOAL:
./another_script 16.72 3.45 44.035

A: Your requirements are very vague (big picture - you're telling us HOW you want to do something but not WHAT you want to do) but MAYBE this is what you want:
./speedtest-cli | awk -F': *' '/Download|Hosted by Charter Communications/{print $2}'
44.035 ms
16.72 Mbit/s

A: First, in answer to your question:
speed=$(./speedtest-cli)
awk '/Download:/ {print $2}' <<< "$speed"

Second, this is almost certainly not what you really need.  You could, for example, construct the call you want within bash, and then either use awk's system function, or perhaps echo the entire call.
Another approach would be to assign the values of interest to a bash array, along the lines of:
 a=( $(./speedtest-cli | awk -F ....) )

A: You've stated that this is your bash script:
#!/bin/bash

speed=$(./speedtest-cli)
awk '/Download:/ {print $2}' $speed

This fails because you are not giving anything to awk to parse. You're setting a variable to contain output from a command, but then treating that variable as if it were a filename.
Awk's command line format looks like this, roughly:
awk [options] awkscript [file ...]

Is $speed a file?  No, it is not.
Based on the edit to your question, it looks as if what you're trying to do is simply strip out the numbers that are output from the speedtest-cli command.  If the script that can take those numbers can be edited, and does not need options in the order you've specified, the quickest solution is probably something like this:
/path/to/speedtest-cli | egrep -o '[0-9]+\.[0-9]+' | xargs /path/to/anotherscript

This takes the output of speedtest-cli, strips out everything that is not a decimal number, then makes those numbers the options to anotherscript. For the sample input you provided, this is equivalent to running
anotherscript 67.01 44.035 16.72 3.45


text:
Q: Umbraco 7 URL rewriting I am trying to add url rewrites
My current URL http://some_domain.co.uk/category/page_name/
I am trying to keep existing site urls functioning with below URL
http://some_domain.co.uk/category/page_name.htm
Any help appreciated.
Thanks!

A: i would highly recommend keeping the current URL structure, it's cleaner, and maintainability will be easier.
If your worried about the SEO or the dead links after the new site goes live then how about doing 301 redirect instead?
Umbraco has a plugin that helps you do 301 redirect and keep track of all the 404 pages, and you can view the report and 301 redirect those 404 pages.
http://our.umbraco.org/projects/developer-tools/301-url-tracker
In the example above,
http://some_domain.co.uk/category/page_name.htm
will get redirected to
http://some_domain.co.uk/category/page_name/


text:
Q: Run time error 1004 excel cannot find the text file to refresh this external range I'm trying to convert tsv files in a folder to xlsx format by importing them as text file using Data=>From Text option via VBA.
During that encountered this error

Code:

Sub convert()

Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook

CSVfolder = ActiveSheet.Range("B2").Value & "\"

fname = Dir(CSVfolder & "*.tsv")

Do While fname <> ""
    Workbooks.Add

    Set wBook = ActiveWorkbook

       With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
        .Name = fname
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    wBook.Close False
    fname = Dir

 Loop
End Sub

End Sub

Why i'm getting the error in .Refresh BackgroundQuery:=False ?

A: The error is happening there as it's at the Refresh stage that it looks for the file.
The issue is that Fname won't contain the path.
Change your connection to:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....


text:
Q: Firebase authentication, firebase is not defined Im trying to make a login page to my firebase project, but always when i send the params to the functions its returns "Firebase is not defined . Here's my code:
<button id="login" onclick="signIn()"><Login</button>

The function signIn() only change the href to http://localhost:5000/signin/:email/:password
then i have this
const functions = require('firebase-functions');
const adm = require('firebase-admin');
const express = require('express');
const signin = require('./modules/signin');
const firebase = require("firebase");

// // Create and Deploy Your First Cloud Functions
adm.initializeApp(
    functions.config().adm
);

const app = express();

app.get('/signin/:email/:password', (request, response) => {
    exports.signin = signin(request.params.email, request.params.password);
});

exports.app = functions.https.onRequest(app);

and my function is only
function signin (email, password) {
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
    // user signed in
    console.log ("Usuário logado com sucesso!");
    return True;
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
            // alert('Wrong password.');
            return false;
        } else {
            alert(errorCode+": "+errorMessage);
            return false;
        }
    });

}

module.exports = signin;

im trying to use the index.js on functions folder as a type of "controller" to call functions on backend, but im having trouble to solve this simple problem.

A: You can't use the Firebase client SDK in Cloud Functions.  Cloud Functions is considered backend code, and doesn't run on the browser.  If you want to sign in the user, you have to use the SDK in your browser code, not backend code.


text:
Q: RoR as_json call missing data that's in the database using rails 4.1.8, ruby 2.2, mysql, elasticsearch-rails 5.0.4, elasticsearch 5.2. the selectors field on the Selector model is stored as json in a varchar column and for some reason when I load a location and its associated selector using as_json, the selectors field comes back nil when I know there is data in the column?
the Selector table:
create table Selectors do
   t.text selectors
   t.text selectors_other
   t.references location
   t.timestamps
end

I recently added Elastic Search so the model has:
settings index: {
   analysis: {
      analyzer: {
         selector_analyzer: {
            type: :standard,
            stopwords: ["some","words","here"]
         }
      }
   }
}

mapping do
   indexes :selectors, {analyzer: :selector_analyzer}
   indexes :selectors_other, {analyzer: :selector_analyzer}
end

def as_indexed_json(options={})
   {
      'id' => id,
      'selectors' => selectors,
      'selectors_other' => selectors_other
   }
end

and the call I make to get the data for the view is
Location.find(<id>).as_json(:include => [:selector, :response])

every field I expect is in the json and all the data is there except the selectors field which is nil. I know there is data because if I do:
loc = Location.find(<id>)
loc.selector

the selectors field is not nil. I tried adding an as_json method to the Selector model but it didn't have any effect. The only changes I've made recently were to add the Selector model to the Elasticsearch index. I used an IndexManager in order to create one index with multiple types and created a rake task for deployments and re-indexing. The only distinction is that this field is stored as json, but it was working fine before.
Any ideas, suggestions, etc would be appreciated since I can't think of anything that would cause it to be nil.

A: figured out what was causing the field to be nil, tho not why it is causing a problem
I had added a method to manipulate the json when updating the selectors field, in that method I had a line like
sel_hash = JSON.parse(self.selectors)

the IDE was unable to resolve self.selectors so I added
attr_accessor :selectors

and that line for some reason caused the selectors field to be nil, go figure


text:
Q: Why does Qt generate a .cpp file out of .qrc? Qt generates a .cpp file when compiling the resource, e.g. images, which are defined in the .qrc file. The compile output is as follows:
/usr/local/Qt-5.5.1/bin/rcc -name images ../myApplication/images.qrc -o qrc_images.cpp
g++ -c -pipe -g -std=c++0x -Wall -W -D_REENTRANT -fPIC -DQT_QML_DEBUG -DQT_DECLARATIVE_DEBUG -DQT_QUICK_LIB -DQT_MULTIMEDIA_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_SQL_LIB -DQT_CORE_LIB -I../myApplication -I. -I../shared_base/Debug -I../shared_base -I/usr/local/Qt-5.5.1/include -I/usr/local/Qt-5.5.1/include/QtQuick -I/usr/local/Qt-5.5.1/include/QtMultimedia -I/usr/local/Qt-5.5.1/include/QtGui -I/usr/local/Qt-5.5.1/include/QtQml -I/usr/local/Qt-5.5.1/include/QtNetwork -I/usr/local/Qt-5.5.1/include/QtSql -I/usr/local/Qt-5.5.1/include/QtCore -I. -I/usr/local/Qt-5.5.1/mkspecs/linux-g++ -o qrc_images.o qrc_images.cpp

So as seen in the output, to compile the image resources, two different commands are executed, the rcc and the g++.
However, one can simply compile the images with the rcc and register this binary file in the application during run time. I can't understand what this g++ command does and why it is necessary.
Also why does qt include libs such as Multimedia, Gui, etc. into this file and make it larger than just the images?
Note: The images folder is sized 27MB. The generated images.cpp file is sized 66MB and if I compile the images with the rcc-utility myself it is also 27MB and it works just like the 66MB did.

A:
...one can simply compile the "images" with the rcc and register this
  binary file in the application during run time.

As @vahancho pointed out, Qt resources can be loaded dynamically too if you generate a binary resource data with -binary option of rcc. That file can be loaded with QResource::registerResource() function.

I can't understand what this g++ command does and why it is necessary.

It builds the object file, which is then linked into the binary at a later stage.

Also why does qt include libs such as Multimedia, Gui etc into this
  file and make it larger than just the images?

Including the libs doesn't necessary mean the binary will be larger. Linker will produce a binary only with those objects that are used in your code.

A: The cpp file generated by rcc is bigger, because every byte in images will become 0x00 code in cpp.
If your file is 100KB, the cpp file may be 500KB, it's ok.
The final executable file will not so big, binary is binary, cpp is cpp.


text:
Q: How to over-ride meta data in Wordpress, using Squirrly SEO I currently have a Wordpress website using Squirrly for SEO.  However, on archive pages, it is using descriptions/titles from the first content page that belongs to the archive page.
So for example, on my accommodation archive page, that lists all the hotels, the title is "Hotel 1", and the description is "Hotel 1 is a beautiful...".  They should instead be referencing the title "List of Accommodation", and description "These are all the hotels...".
I am trying to write an over-ride for this - I did find one for Yoast SEO listed here - https://wordpress.stackexchange.com/questions/61472/using-php-to-overwrite-or-replace-title-tag-while-using-yoast/61523#61523?newreg=a3496de25de941a7bb16089b1912653b but this is not working, assumedly because wpseo_title is a filter specific to Yoast.
My current code is:
<?php get_header();
    if ( is_archive() ) {
        add_filter('wpseo_metadesc', 'filter_product_wpseo_metadesc');
            function filter_product_wpseo_metadesc($wpseo_metadesc) {
                if(  is_singular( 'product') ) {
                    $wpseo_metadesc = "This is a big test of stuff";
                }
                return $wpseo_metadesc;
            }
} ?>

Does anyone know a filter, or similar, that would over-ride the SEO for my archive pages, either specific to Squirrly SEO, or one which would work in general?
Kind regards
James

A: Make sure you add the hook before "wp_head" (get_header();)
You can use this:
if (is_archive()){

add_filter('sq_title', 'filter_product_wpseo_metadesc');

function filter_product_wpseo_metadesc($wpseo_metadesc){

    if (is_singular('product')){
        $wpseo_metadesc = "This is a big test of stuff";
        }

    return $wpseo_metadesc;
    }
}  get_header();

You can change the title and description in Squirrly by calling the filters: sq_title and sq_description
Hope this helps you.