text:
Q: TFS 2017 Page loading issues for static icons and images I've been working on a project whereby we are working to split the web tier onto a separate server from the app tier per our security requirements. It's actually worked really well with the exception of one piece. When accessing the TFS site everything loads except the static page bits (some fonts, banner images and icons). I've confirmed through logs on the app server that the service account appears to be granted access to the files but they are not actually rendered on the page. Furthermore, for each of these items that is attempting to load a login prompt appears and user credentials do not appear to work when entered. The problem mostly only occurs when HTTPS only is enforced. If I leave 8080/HTTP as the primary URL and don't enforce SSL it seems to work better because there are no longer continuous login prompts but some icons are still missing. Looking at the page inspection when loading the SSL enforced page the content failing to load shows HTTP/1.0 with a 401 error but it's URL referenced has HTTPS listed. When using the direct HTTPS URL for the icon or image file it will download fine. Then since the file is cached I can refresh the TFS page and that icon/image will load properly without logon prompt, until I clear browser cache.
 I feel like this is something misbehaving within TFS.  I have group policies configured correctly for the service account with impersonating of logons and logon as a service set on both web and app tier servers so I don't believe that is the issue.  I've tried this on a few different builds of 2017 all with similar results.  Currently on 2017 Update 3.1 patch 6 and TFS is configured to use Negotiate since we have NTLM restrictions in the environment.
UPDATE:
Wanted to get back on here and explain in further detail but I've been busy. We follow NIST 800-53 requirements and adhere to CIS Level 2.  As such the recommended configuration for a web application is to be three-tier (web, app, and data).  TFS by default will technically allow up to 2 tiers where the app and web are on the same box.  I need to move the web to a different box for true three-tier architecture.  So I think I've managed to figure out a way to sort of 'trick' TFS into thinking there's a third server for the web that isn't actually using the app services like the app tier does and essentially separating the two tiers as result.
This is how I achieved where I am currently.  These are all Server 2016 boxes.

*

*Deploy SQL 2016 box and added the service account to SQL with
sysadmin ahead of the TFS install

*Stand up the web server and app server.  Added the service account to both "Impersonate a client after authentication" and
"logon as a service" policies on both systems.

*Install TFS on the app server, pointing to the SQL box during configuration letting the install create the databases.  Setup with
self-signed TFS issued cert initially to get it going and set HTTPS
redirect as well so the web.config files are already preset for
this.

*Install TFS on the web server but do NOT configure any features.

*On the TFS app export IIS app pools and sites using Command Prompt and copy to the web server.  Disable IIS services.  On the
TFS install folder and TFSCache folder setup network shares and
grant the tfsservice account read/write access and NETWORK SERVICE
along with the TFS_Users group read access. (this part I'm still not
100% sure on and have played with numerous variations with little
change in results other than the TFS_Users group seems to be what
allows me to pull down most of the static site bits)

*On the web server, edit the exported 'sites' file to adjust the bindings to point to itself instead of the app server and update the
physical paths for all three entries to their respective UNC path on
the app server.  Import the app pools and sites.  In IIS update the
bindings with an internal CA issued cert and Edit the Application
Settings > dataDirectory to point to the UNC path of the tfs_cache.
Restart IIS.

*Back on the app server open TFS admin console and update the public URL to point to the web  box.  Hit Test so it validates and
accepts the cert.  (I also installed the cert on the app server just
for good measure since I read something about a multi-server
deployment with multiple app servers needs to have them all issued
the correct cert when using SSL certs from a CA. Not sure if this
was actually necessary or not for my configuration.)

*Once updated, test access to TFS.

TFS will add the web box to the Application Servers list in the admin console but none of the features on the web box are configured.  TFS sees it almost as a TFS Proxy as it enables the TFS_Proxy local security group on the web box but does not actually create the TFS_Application_Tier security group like it does on the app server.  The web server also doesn't function as your typical 'TFS Proxy' since it's not caching data locally for use like it would if you setup the Proxy feature.
I think that's the quick dirty run down but I'll go back through my write-up I did while going through all this to keep track of what I was doing and make sure I didn't miss anything pertinent.


text:
Q: iphoto: deleting photos from iPhone doesn't work Even if iPhoto tells me all the files are deleted, I can still find them on my iPhone under All Photos. There has to be a way to delete all pictures without separately selecting them on the small screen?
Image Capture does not allow me to delete anything either:

A: On your phone, open the Photos app and select Albums from the bottom.  One of the albums is Recently Deleted.  Once you delete the photos from there, and sync your phone, they should all be off the phone.  The Recently Deleted album appears to work sort of like a trash can for deleted photos and videos, but with a 30 day expiration.  If a photo or video isn't recovered from Recently Deleted within 30 days, then it is removed from the phone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Terraform count error when condition with variables used Running Terraform 0.12.24 code that was upgraded from 0.11.15 and getting an error related to count on a resource. The count statement has a conditional in it and the line of code and error are:
75:   count                  = var.vpc_count == 0 || var.tgw_count == 0 ? 0 : var.vpc_count

The "count" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.
To work around this, use the -target argument to first apply only the
resources that the count depends on.

Both of the variables are simple numbers, either 0 or 1 and are in the tfvars file and passed into the module.
I have searched but couldn't find anything related to this error when the count has simple variables and a conditional in it.
How can I get this to work?
Here is the code inside the module
resource "aws_route" "private-1-tgw" {
  provider               = aws.acct
  count                  = "${var.vpc_count}" == 0 || "${var.tgw_count}" == 0 ? 0 : "${var.vpc_count}"
  route_table_id         = aws_route_table.private-1[0].id
  destination_cidr_block = "10.0.0.0/8"
  transit_gateway_id     = var.tgw_id
}

Here is what is in tfvars file
hmi_vpc_count = 1
tgw_count = 0

And here is the module call
module "hmi-vpc" {
  source = "../../modules/hmi-vpc"

  providers = {
    aws.acct = aws.acct
  }

  aws_account                   = var.aws_account
  aws_region                    = var.aws_region
  management_sg_rules           = var.management_sg_rules
  tgw_count                     = module.transit-gateway.tgw_id == "" ? 0 : var.tgw_count
  tgw_id                        = module.transit-gateway.tgw_id
  tags                          = var.tags
  vpc_cidr                      = var.hmi_vpc_cidr
  vpc_count                     = var.hmi_vpc_count
  vpc_dhcp_count                = var.hmi_vpc_dhcp_count
  vpc_dhcp_domain_name          = var.hmi_vpc_dhcp_domain_name
  vpc_dhcp_dns_servers          = var.hmi_vpc_dhcp_dns_servers
  vpc_dhcp_netbios_name_servers = var.hmi_vpc_dhcp_netbios_name_servers
  vpc_dhcp_ntp_servers          = var.hmi_vpc_dhcp_ntp_servers
  vpc_sn_private_1a_cidr        = var.hmi_vpc_sn_private_1a_cidr
  vpc_sn_private_1b_cidr        = var.hmi_vpc_sn_private_1b_cidr
  vpc_sn_private_1c_cidr        = var.hmi_vpc_sn_private_1c_cidr
  vpc_sn_public_1a_cidr         = var.hmi_vpc_sn_public_1a_cidr
  vpc_sn_public_1b_cidr         = var.hmi_vpc_sn_public_1b_cidr
}

A: The problem lies in the line (in module "hmi-vpc" { ... })
  tgw_count = module.transit-gateway.tgw_id == "" ? 0 : var.tgw_count

which depends on the execution of the module.transit-gateway. To resolve this you should think about a condition that does not depend on an output of the module but maybe on an input variable of it. e.g.:
  tgw_count = var.tgw_disabled ? 0 : var.tgw_count

or based on the information provided even
  tgw_count = var.tgw_count

might work for you.


text:
Q: Integer promotions in C programming In the code below which statements have integer promotions?
unchar a;
unchar b;
short c;
a = 0xFE;
b = 0xFE;
c = a+b;
int d = a==b

I got the question like this in a question series. How to answer it.
Moreover,Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and enum.

A:
which statements have integer promotions.

unchar a;
unchar b;
short c;

These appear to be declarations, and possibly unchar is an alias for unsigned char. There are no expressions in them, so there are no integer promotions.

a = 0xFE;

0xFE is an unsuffixed hexadecimal constant whose value, 254, must fit in an int. Per C 2018 6.4.4.1 5, its type is int. a is an lvalue. As the left operand of an assignment, it is left as an lvalue and not converted to a value.
Per C 2018 6.5.16 2, the right operand is converted to the type the left operand would have after lvalue conversion, hence unsigned char. The integer promotions are not performed.

b = 0xFE;

This is the same as above.

c = a+b;

For the binary + operator on arithmetic operands, the usual arithmetic conversions are performed, per c 2018 6.5.6 5. For integer operations, the usual arithmetic conversions include the integer promotions. Thus the integer promotions are performed on a and on b.
Except in esoteric C implementations, int can represent all the values of unsigned char. In this case, the integer promotions convert unsigned char to int. So they convert each of a and b to int.
Then + produces an int result, and, since it is the right operand of assignment, it is converted to the type c would have after lvalue conversion, short. There are no further integer promotions.

int d = a==b

This is similar to above. For arithmetic operands of ==, the usual arithmetic conversions are performed, per C 2018 6.5.9 4. These include the integer promotions on a and on b. There are no other integer promotions in this.


text:
Q: React Router go back to current page after redirect I have a problem with redirection after login. It works when I hardcode the result but when I call the api to check authentication it will redirect to "/main" and go back to the current page "LoginForm".
import React, { Component } from 'react';
import LoginForm from './components/login/LoginFormContainer';
import Main from './components/main/MainContainer';
import {
  BrowserRouter as Router,
  Switch,
  Route
} from 'react-router-dom';
import './App.css';

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact name="login" path="/" component={LoginForm} />
          <Route exact name="main" path="/main" component={Main} />
        </Switch>
      </Router>
    );
  }
}

export default App;

and in my loginPage redirect to "/main" after check authentication
import React, { Component } from 'react';
import { Button, Form, Col, Row } from 'react-bootstrap';
import FieldGroup from '../common/FormGroup';
import { Redirect, Link } from 'react-router-dom';
import Logo from '../../img/zonLogo.svg';

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.state = {
      isLoggedIn: false,
      username: "",
      password: ""
    };
  }

  handleLoginClick(e) {
    var form = new FormData()
    form.append("username", "xxxxx");
    form.append("password", "xxxxx");
    let self = this;

    fetch('/login', {
      method: 'POST',
      body: form
    }).then(function (response) {
    if (response.status === 200) {
      return response.json()
    }
    }).then(function (data) {
  i    f (data.user !== undefined && !data.user.isSuspended &&     !data.user.banned) {
        self.setState({ isLoggedIn: true });
      }
    }).catch(function (error) {
      console.log("Call report API error");
    });
  }

render() {

if (this.state.isLoggedIn) {
  return <Redirect to="main" />;
}
return (
  <div >
    <Row>
      <Col>
        <Form onSubmit={this.handleLoginClick}>
          <FieldGroup
            id="username"
            type="text"
            placeholder="Username"/>
          <FieldGroup
            id="password"
            type="password"
            placeholder="Password"
            />
          <Button type="submit" block> Log in</Button>
        </Form>
      </Col>
    </Row>
  </div >
);
  }
}

export default LoginForm;

when login successfully it will redirect to main but it redirect back to login page but if I hardcode it will work
handleLoginClick(e) {
    self.setState({ isLoggedIn: true });
}


text:
Q: py4j.protocol.Py4JJavaError: An error occurred while calling o59.save. : java.lang.NoClassDefFoundError: scala/runtime/LazyBoolean I'm new in spark and wanted to write something in a mongodb using pyspark. I tried to do the same as in this tutorials: https://docs.mongodb.com/spark-connector/master/python-api/ and https://docs.mongodb.com/spark-connector/master/python/write-to-mongodb/. Somehow an error occurred.
Scala version: 2.13.1
Spark version: 2.4.4
Python version: 2.7.5
Java version: 1.8.0_242
[root@node2 vagrant]# pyspark --conf "spark.mongodb.input.uri=mongodb://IP/db.collection?readPreference=primaryPreferred" --conf "spark.mongodb.output.uri=mongodb://IP/db.collection" --packages org.mongodb.spark:mongo-spark-connector_2.12:2.4.1 --conf spark.ui.port=63000
Python 2.7.5 (default, Aug  7 2019, 00:51:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/home/vagrant/spark-2.4.4-bin-hadoop2.7/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
org.mongodb.spark#mongo-spark-connector_2.12 added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent-08af433d-99aa-4bba-8d25-7983617c99e5;1.0
        confs: [default]
        found org.mongodb.spark#mongo-spark-connector_2.12;2.4.1 in central
        found org.mongodb#mongo-java-driver;3.10.2 in central
        [3.10.2] org.mongodb#mongo-java-driver;[3.10,3.11)
:: resolution report :: resolve 1456ms :: artifacts dl 6ms
        :: modules in use:
        org.mongodb#mongo-java-driver;3.10.2 from central in [default]
        org.mongodb.spark#mongo-spark-connector_2.12;2.4.1 from central in [default]
        ---------------------------------------------------------------------
        |                  |            modules            ||   artifacts   |
        |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
        ---------------------------------------------------------------------
        |      default     |   2   |   1   |   0   |   0   ||   2   |   0   |
        ---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent-08af433d-99aa-4bba-8d25-7983617c99e5
        confs: [default]
        0 artifacts copied, 2 already retrieved (0kB/19ms)
20/02/07 20:30:55 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.4.4
      /_/

Using Python version 2.7.5 (default, Aug  7 2019 00:51:29)
SparkSession available as 'spark'.
>>> my_spark = SparkSession.builder.appName("myApp").getOrCreate();
>>> people = spark.createDataFrame([("Bilbo Baggins",  50), ("Gandalf", 1000), ("Thorin", 195), ("Balin", 178), ("Kili", 77), ("Dwalin", 169), ("Oin", 167), ("Gloin", 158), ("Fili", 82), ("Bombur", None)], ["name", "age"]);
>>> people.write.format("mongo").mode("append").save();
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/spark-2.4.4-bin-hadoop2.7/python/pyspark/sql/readwriter.py", line 736, in save
    self._jwrite.save()
  File "/home/vagrant/spark-2.4.4-bin-hadoop2.7/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__
  File "/home/vagrant/spark-2.4.4-bin-hadoop2.7/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/home/vagrant/spark-2.4.4-bin-hadoop2.7/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o59.save.
: java.lang.NoClassDefFoundError: scala/runtime/LazyBoolean
        at com.mongodb.spark.sql.DefaultSource.createRelation(DefaultSource.scala:66)
        at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
        at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
        at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
        at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:676)
        at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:676)
        at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
        at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
        at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
        at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:285)
        at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: scala.runtime.LazyBoolean
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
        ... 32 more


text:
Q: Glob through a long list of files with curl and writing each to a unique, new file with a matching filename I am downloading several large sets of files from an ftp site using curl and writing them to new files with the same name. I want to use a command like this:
curl ftp/site/filename > filename

Here are some example files from the ftp site:
File:Compara.6_primates_EPO.chr10_1.emf.gz 30909 KB     8/3/10  12:00:00 AM
File:Compara.6_primates_EPO.chr10_2.emf.gz 13110 KB     8/3/10  12:00:00 AM
File:Compara.6_primates_EPO.chr10_3.emf.gz 24948 KB     8/3/10  12:00:00 AM
File:Compara.6_primates_EPO.chr10_4.emf.gz 45155 KB     8/3/10  12:00:00 AM
File:Compara.6_primates_EPO.chr10_5.emf.gz 17236 KB     8/3/10  12:00:00 AM
File:Compara.6_primates_EPO.chr11_1.emf.gz 37593 KB     8/3/10  12:00:00 AM
...
500 files later
....
File:Compara.6_primates_EPO.other_9.emf.gz 8980 KB  8/3/10  12:00:00 AM

There are a lot of these files, and I will be going through many long lists of them. There are some numerical patterns for which I could use
for x in {1..N}; do curl ftp/site/file${x} > file${x}
But there are also unpredictable patterns, like for example the secondary numeric index varies for different files. It is {1..5} here:
Compara.6_primates_EPO.chr10_{1..5}
and with the next file I might have something like
Compara.6_primates_EPO.chr11_{1..7}
and then there some oddballs like the last one:
Compara.6_primates_EPO.other_{1..?}
I know that I can't use simple globbing as in:
curl ftp/site/file* > file*

-- that just gives me ambiguous redirect.  I was wondering if anyone knew of a clever solution where I could glob the filename, save it as a string and then write the output to the filename, without getting too fancy... I know I could probably go and write a python script to do this more systematically, but it seems like there might be a quick bash solution that I am failing to think of...

A: The answer to this question was simple after all:
curl -O ftp/path/to/site/*glob_pattern*
The -O option will save the files with the same name they are given in the directory :-)


text:
Q: QGroupBox find selected Radio Button I have created a simple UI consisting of a QGroupBox with a bunch of QRadioButtons (32 to be exact) and I want to be able to find the selected one.
I've looked at forums and things, but the answers I've found don't work, and one referenced documentation on a nonexistant method of QGroupBox.
Given the below snippet, how would I find the selected QRadioButton, if any?
QGroupBox* thingGroup = ui->thingGroupBox;

A: If you want to get it when you select one of them you could use the toogled signal, connect it to some slot and use the sender () function and convert it to QRadioButton.
*.h
public slots:
    void onToggled(bool checked);

*.cpp
QGroupBox *thingGroup = ui->groupBox;

QVBoxLayout *lay = new QVBoxLayout;

thingGroup->setLayout(lay);

for(int i = 0; i < 32; i++){
    QRadioButton *radioButton = new QRadioButton(QString::number(i));
    lay->addWidget(radioButton);
    connect(radioButton, &QRadioButton::toggled, this, &{your Class}::onToggled);
}

slot:
void {your Class}::onToggled(bool checked)
{
    if(checked){
        //btn is Checked
        QRadioButton *btn = static_cast<QRadioButton *>(sender());
    }

}

A: I guess it is easier to identify which button is checked using a QButtonGroup, just remember to select buttons in "Design mode" then right-click and select assign to button group :

To identify the checked button, you can use QButtonGroup's checkedButton method:
QAbstractButton *button = ui->buttonGroup->checkedButton();


text:
Q: Postgres How to keep counties with no data in the query results I have a query that counts the number of brokerages, agent, and unaffiliated agents in a county. Not every county has brokerages and agents and those counties are currently excluded from the results. I want to all the counties to be in the results regardless of the number of agents/brokerages there.
My current query is:
with locations_cte as
(
    select
        lpad(cbsa.zip,5,'0') as zip,
        cbsa.st,
        cbsa.county
    from cbsa_locations cbsa
)
,
brokerage_count_cte as
(
    select
        distinct cb.county,
        cb.st,
        count(distinct bcz.brokerage_code) as brokerageCount
    from brokerage_coverage_zips bcz
    left join locations_cte cb on cb.zip = bcz.zip
    group by cb.st,cb.county

)
,
agent_count_cte as
(
    select
        distinct cb.county,
        cb.st,
        --COALESCE(pup.brokerage_code,'NO-BROKERAGE-CODE') AS brokerage_code,
        count(distinct puz.profile_id) as agentCount,
        count(distinct case when pup.brokerage_code is not null then puz.profile_id end) as BAagentCount
    from profile_coverage_zips puz
    left join locations_cte cb on cb.zip = puz.zip
    join partner_user_profiles pup on pup.id = puz.profile_id
    where pup.verification_status = 'Verified-Verified'
    group by cb.county, cb.st--, pup.brokerage_code

)
select
    distinct cb.county,
    cb.st,
    bcc.brokerageCount,
    acc.agentCount,
    acc.BAagentCount,
    acc.agentCount - acc.BAagentCount as UnaffiliatedAgentCount
from locations_cte cb
join brokerage_count_cte bcc on bcc.st = cb.st and bcc.county = cb.county
join agent_count_cte acc on acc.st = cb.st and acc.county = cb.county
-- order by bcc.brokerageCount ASC

and when I include the last line of the query the lowest county brokerageCount is 1 whereas I want the counties with 0 to show up as well.
Tables are as follows:
cbsa_locations:

*

*contains, zip,county,state

brokerage_coverage_zips

*

*brokerage_code, row for each zip, only contains location data for areas a brokerage covers

profile_coverage_zips

*

*same as brokerage_coverage_zips but for an agent instead of brokerage

A: Use LEFT OUTER JOINs instead of INNER JOINS.


text:
Q: Can't See Windows Phone Template in Visual Studio 2012 for windows Phone 8 Previously I used Visual Studio 2012 for Windows Phone 8. and developed some projects.
But, suddenly there is no options for creating windows phone App.
If i try to create a new project will show error popup like this.

A: Right-click on the Visual Studio Command Prompt shortcut and then  select Run as Administrator
Run below command
devenv /installvstemplates
devenv /resetsettings

http://www.tanchunsiong.com/visual-studio-2012-no-template-information-found/
UPDATE:

This switch is supported only for Visual Studio partner development, and is not available in Express editions. You must run devenv as an
  administrator in order to use the /Setup (devenv.exe) and
  /InstallVSTemplates (devenv.exe) switches. For more information, see
  User Permissions and Visual Studio.

http://msdn.microsoft.com/en-us/library/vstudio/ms241279.aspx

A: This may not work on the express version. If you have a Professional or Ultimate version of VS, try running the installer again. Then choose "Modify" option, and select "Windows Phone 8.0 SDK" from the list.
For more information see here


text:
Q: Espresso + Junit4 How to test on other screens that require login I started learning Espresso couple days ago,and found it very nice library for testing but i stuck on a problem.
I want to test "Home screen" but before moving to home screen User should be logged-in as i get many details from server and stored in my shared preferences.
So i found "@Before" Annotation that can be used.
But drawback of @Before annotation is that it will execute before every test method. in case if i have four test cases are written then it will be execute four times. That should not be done.
Then i googled again and found "@BeforeClass" annotation can be used that is called once while class is started as per given link (Espresso + Junit4 - login once before running all test)
But it didn't solve my problem as login activity is not started in "below" method with "@BeforeClass" annotation
@BeforeClass
public static void setUpBeforeClass() {
    // do login stuff here
}

So what should i do as i require login information before executing test cases for home screen.
Below is the code i am testing
Any help will he appreciated...
Thanks in advance
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(LoginActivity.class);

@Before
public void setUp() {
    onView(withId(R.id.et_username_login))
            .perform(typeText(Credentials.USERNAME), ViewActions.closeSoftKeyboard());
    onView(withId(R.id.et_password_login))
            .perform(typeText(Credentials.PASSWORD), ViewActions.closeSoftKeyboard());
    onView(withId(R.id.btn_login)).perform(click());
}
@Test
public void onAllEventTabTest() {
    onView(withId(R.id.ll_tab_1)).perform(click());
}

@Test
public void formPacketTabTest() {
    onView(withId(R.id.ll_tab_2)).perform(click());
}

A: You can choose which activity you want to launch through the ActivityTestRule
If you're already logged in use the rule for your other activity to test like
@Rule
public final android.support.test.rule.ActivityTestRule<MainActivity> main = new ActivityTestRule<>(MainActivity.class);

It should go directly to it without the need to login.


text:
Q: Famous type of transistor in IC I am begginer in electronics and I would like to ask if there is a specific type of a transistor which is used more than the others in today integrated circuits and why?

A: Most transistors are CMOS, by quantity. ICs like the Intel i7 use billions per chip. Ditto SRAM memories.


text:
Q: How to handle in memory data with multiple threads and persistence in Java I have a Java webapp (running on Tomcat or Jetty) which is only used by a few concurrent users (3-5). The data is managed by Hibernate on an HSQLDB, in memory. The DB is flushed to disk automatically.
The amount of data is not that big, and the performed SQL queries are not so special (mostly direct retrieval by primary key).
I have the feeling Hibernate and SQL are a massive overhead for what I am actually doing.
All I need is a datamodel to be available for all threads, making sure that changes in the model can be transactional. If needed, I don't even mind locking the full data model per transaction! Also, the model should be serialized to disk on a regular basis to avoid data loss in case of a crash.
Is there anything out there which can do this?
Thanks!

A: Stick with the database.  You're going to drive yourself up the wall if you try to re-invent a DB on your own.
At best, you might want to look into NoSQL databases.  These can be simpler than SQL databases.

A: If you feel that Hibernate is a massive overhead, consider using straight JDBC. Although, if SQL is the percieved problem and your data model is very simple, you might be better off with Hibernate instead of the JDBC.

A: Just use Sqlite... You get all from HSQL and plus you have persistence.
No Database manager needed. Nothing is required to be installed.


text:
Q: Can I use an array in ajax javascript? I'm new with ajax and I want to use an array in ajax.
What I want is:

*

*get data from ajax

*add data to new Array. It's all.

$(document).ready(function () { var main_img = new Array()});
So, first, I made one new Array and It works very well.
Than I made settings variable for my ajax:
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost:52273/movie",
    "method": "GET",
    "headers": {
      "cache-control": "no-cache",
      "postman-token": "b39e3106-5289-f828-261f-132e1aba7bf7"
    }
  }

localhost runs in node server.js and I will get data from html.
  $.ajax(settings).done(function (response) {
    $('#content > div.article > div > div.lst_wrap > ul > li > div > a > img', response).each(function(index)
    {
      var k = $(this).attr('src');
      var k2 = k.slice(0, k.indexOf('?'));
      var alt = $(this).attr('alt');

      main_img[index] = k; // this is not working!!!
    });
  });

setting and ajax run on document.ready,
and I test insert value in out of ajax, it works very well..
So I thought something is wrong when I use an array in ajax.
Please Help me...
Is there anything I am missing???

A: since it is possible to have this bug hidden out of sight, what I would do will be:

*

*Create a var to store the type of what I think is an image: let test = typeof(k);

*Use main_img.push(test) as MysterX just said.

*Then console.log(main_img).

I hope it helps!
Then probably it is about scope, let's try this:
$.ajax(settings).done(function (response) {
    $('#content > div.article > div > div.lst_wrap > ul > li > div > a > img', response).each(function(index, main_img)
    {
      var k = $(this).attr('src');
      var k2 = k.slice(0, k.indexOf('?'));
      var alt = $(this).attr('alt');
      main_img[index] = k; // this is not working!!!
    });
  });


text:
Q: Varnish in front of multiple servers with versioning I've got Varnish in front of multiple webservers, I can run them as native to varnish or through upstream checks via nginx, but only static content is cached (no surprise), also respecting query strings i.e.
/main.css?v=1 and /main.css?=v2 are cached separately
I update servers one by one, in fact, all this cannot be done at exactly the same time without downtime, general deployment thing.
If main.css gets updated on one backend and I send request according to the new webpage version to the varnish and request /main.css?=v2, it may still look for file on the machine which has old version and where main.css hasn't been updated yet, so, now I am getting v1 in the cache as v2 and there is nothing I can do, unless TTL expires (which is too late).
I can manually invalidate cache via requests, that's ok.
Is there any automated solution without manual interfering on rewriting software for feedback to varnish? like:

*

*Is it possible, to expire cache when backend comes up, after probe is good?

*anything else?

Thanks

A: If you load this code, or adapted for your varnish version, you can then send requests of type PURGE, with the request URL matching the thing you want to purge, to wipe the item from varnish cache. You can use this to basically automate selectively purging at the end of the deployment process against your Varnish servers, via cURL commands or similar.
https://github.com/dreamhost/varnish-vcl-collection/blob/master/lib/purge.vcl


text:
Q: Order taxonomy terms by the frequency of use in the last 30 days I would like to know how to order the terms in some taxonomy according to their frequency of use in posts in the last 30 days. What I am looking for is the most optimal method how to add "orderby" parameter or apply the array compare on the list of the terms or maybe some smart SQL select. I know this would include some extra columns in table to store a count and a last changed (added) time data. Any suggestions?

A: First thing's first -- You'll have to add that table.
The way you do that if you were writing this in a plugin is as follows:
function customtaxorder_init() {
    global $wpdb;
    $init_query = $wpdb->query("SHOW COLUMNS FROM $wpdb->terms LIKE 'term_order'");
    if ($init_query == 0) {
        $wpdb->query("ALTER TABLE $wpdb->terms ADD `term_order` INT( 4 ) NULL DEFAULT '0'");
    }
}
register_activation_hook(__FILE__, 'customtaxorder_init');

register_activation_hook allows this to run only when the plugin is activated, and the condition in the function keeps it from ever happening if it doesn't have to. Now, you have a place to keep that term order stored.
If you're doing this in your functions.php file of your theme, you could just attach it via add_action to 'init', run it once, then comment it out. There's many other ways to do it too, but this is just a quick handy-dandy way of getting that field into that table.
Next, we need a way to apply that order.
function customtaxorder_applyorderfilter($orderby, $args) {
    if($args['orderby'] == 'term_order')
        return 't.term_order';
    else
        return $orderby;
}
add_filter('get_terms_orderby', 'customtaxorder_applyorderfilter', 10, 2);

That gives us ability to use 'term_order' in the 'orderby' clause of any taxonomy query.
The final step of this is applying that number to the term in order for things to actually sort.
I figure we should look to update this every time we update a post, so how about the 'save_post' action hook.
function customtaxorder_update( $id ) {
    global $wpdb;
    $post_count = 0;
    $post_type = get_post_type( $id );
    $taxonomies = wp_get_object_taxonomies( $post_type );
    $args = array('fields' => 'ids');
    $terms = wp_get_object_terms( $id, $taxonomies, $args );
    $thirtydaysago = date_i18n('U', strtotime('-30 days') );
    foreach( $terms as $term ) :
        $querystr = "SELECT count FROM $wpdb->term_taxonomy, $wpdb->posts, $wpdb->term_relationships WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id AND $wpdb->term_taxonomy.term_id = $term AND $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_date > $thirtydaysago";
        $result = $wpdb->get_var($querystr);
        $post_count = $result;
        $wpdb->query("UPDATE $wpdb->terms SET term_order = '$post_count' WHERE term_id ='$term'");
    endforeach;
}
add_action('save_post', 'customtaxorder_update');

The action 'save_post' runs the post ID through it, so all we have to do is leverage that in our function to first get it's post type, then all taxonomies associated with it, then all terms which apply to the post for all associated taxonomies. Set wp_get_object_terms to give us an array of ID's and loop throught them, get the post count from the category, and assign it to the term_order field which we created.
This should do it for you. Make sure to 'orderby' => 'term_order' and 'order' => 'DESC' since you'll want high numbers to come first!
Enjoy!
Note: I've added the necessary code to make this get the post counts from the last 30 days.


text:
Q: Image of a finite dimensional complex representations of $GL_n(\mathcal{O})$ EDIT Let $\mathcal{O}$ be the ring of integers in a non-Archimedean local field. Let $GL_n(\mathcal{O})$ be the (compact) group of $n\times n$ matrices with entries in $\mathcal{O}$ such that its inverse also has entries in $\mathcal{O}$.

Consider a continuous finite dimensional representation of $GL_n(\mathcal{O})$ in a complex vector space $V$. Is it true that the image of $GL_n(\mathcal{O})$ in $GL(V)$ is a finite subgroup?

A reference would be most helpful.

A: Call the representation $\pi$.  Let $U$ be a neighbourhood of the identity in $\operatorname{GL}(V)$ that contains no non-trivial subgroup.  Then the pre-image of $U$ under $\pi$ is a neighbourhood of the identity there, hence contains some open subgroup.  That is, $\ker(\pi)$ contains an open subgroup, hence is open, hence has finite index.  The representation thus factors through the finite quotient $\operatorname{GL}_n(\mathcal O)/\ker(\pi)$.


text:
Q: Confusing licensing for a user "Office 365 E3 + Power apps plan 2 trial ?" I have this license for a user

so it is confusing me, as having Office 365 E3 should cover Power Apps without the need to start a trial period.. so why the users have E3 + Power apps plan 2 trial


text:
Q: Webpack LESS-loader Unexpected character error i can't compile less files. I don't know where i'm doing mistake.
Can u help me?
Error is:
Failed to compile.
**./src/less/main.less 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.

@fontSize: font-size:20px;
  |
  | p {**

here is my webpack.config.js
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const config = {
    entry: './src/js/index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'main.js',
        publicPath: 'dist/'
    },
    devServer: {
        overlay:true
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
            },
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader!less-loader"
                })
            }
    },
    plugins: [
        new ExtractTextPlugin("styles.css"),
    ]
};

module.exports = config;

and here is my index.js
import '../less/main.less';
and here is my less file
@fontSize: font-size:20px;

p {
    font-size: @fontSize;
}

A: Replace @fontSize: font-size:20px; with @fontSize: 20px; and use: "css-loader!less-loader" with use: ['css-loader', 'less-loader']


text:
Q: Help me solve this simultaneous linear congruence question. I am trying to find solutions to: $ x \equiv 4 \mod 7$ and $x \equiv 8 \mod 13$ Here is what I have done so far.
Let $x \in \mathbb{Z}$ be a solution then $x \equiv 4 \mod 7 \iff x=4+7k, k\in \mathbb{Z}$.
Also $x \equiv 8 \mod 13$ but $x=4+7k, k\in \mathbb{Z}$ so $4+7k \equiv 8 \mod 13 \iff 7k \equiv 4 \mod 13$.
I am unsure how to proceed and very stuck. Any help?

A: $7k+4=13n+8\iff7~(k-2n)=4-n.~$ But $7=4+3$, so $k-2n=1$ and $n=-3$ form an initial solution, yielding $k=-5$. So $N=n+7a$ and $K=k+13a$ with $a\in$ Z form all integer solutions.


text:
Q: How do I monitor display :1 while I'm using display :0? I am running X on two displays. :0 is my primary display but I also have some programs running on :1. Is there any GUI application that will let me monitor display :1 in a window that sits on display :0?
(Using gnome, FWIW)

A: I know of 2 ways to do this when the system is remote, so given the 2nd X server is locally running on your system (:1) should really make no difference.
Method #1 - VNC
You could setup VNC on the 2nd X server and then run vncviewer :1 from the 1st X desktop.
Method #2 - XDMCP
If you want to remote display an entire desktop from one system to another system you'd typically use XDMCP. You can then use a tool such as Xephyr to connect to your 2nd X server on display :1 from the 1st X server.
Example
$ Xephyr -ac -br -noreset -screen 800x600 :1

Here are several resources for setting up XDMCP and going further.

*

*Configuring XDMCP and GDM on Red Hat Linux

*xdmcp - Ubuntu wiki reference page

*Xdmcp - ArchLinux Wiki

*GDM and XDMCP configuration for remote graphical Linux desktop access
References

*

*X display manager (program type)


text:
Q: Couldn't use JSON Data in an viewController extension? could anybody please let me know what I did wrong here?
I couldn't pass the JSON data from URLSession.shared.dataTask to outer extension
Nor could bring the
func numberOfSections .. etc to be used in the URLSession.shared.dataTask
Any help appreciated, thank you for your time.
Swift
struct getSubData: Decodable {
    let id: Int
    let name: String
}
struct Section: Decodable {
    let id: Int
    let name: String
    let subData: [getSubData]
}
class indexViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    let url = "https://nabulsi.com/nabulsi_app/main_sections_v4.json"
                         let urlObj = URL(string: url)
                         URLSession.shared.dataTask(with: urlObj!){(data, response, error) in
                             do {
                                 let sections = try JSONDecoder().decode([Section].self, from: data!)
                                for section in sections {
                                    print(section.name)
                                    let sectionName = section.name
                                    for data in section.subData {
                                        print(data.name)
                                        let subSectionName = data.name
                                    }
                                }
                             } catch {
                                 print("We got an error")
                             }
                         }.resume()
}

}
extension indexViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
    return sectionName.count

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sectionName[section].subSectionName?.count ?? 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = sectionName[indexPath.section].subSectionName?[indexPath.row]

    return cell
}

}

A: JsonDecoder class has no chance to parse your data just because of the received JSON text from the server is not a valid format.
Here is your endpoint, open it in the web browser: https://nabulsi.com/nabulsi_app/main_sections_v4.json
And here is the JSON validator tool: https://jsonlint.com
Copy and paste to validate your server response to the JSON validator tool called jsonlint, and you will see where is your wrong.
Probably it's not your fault. It's about your backend developer if you didn't write by yourself. Contact him to fix the JSON format. After fixing the issue please notify me. I am gonna fix your parse codes if it's still not working as you expected.

*

*EDIT: After fixing problem, the related codes here:

[0] - Parsed json values assigned to local variable.
class indexViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var sections: [Section] = []

override func viewDidLoad() {
    super.viewDidLoad()
    let url = "https://nabulsi.com/nabulsi_app/main_sections_v4.json"
    let urlObj = URL(string: url)
    URLSession.shared.dataTask(with: urlObj!){(data, response, error) in
        do {
            let sections = try JSONDecoder().decode([Section].self, from: data!)
            self.sections = sections // [0]

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        } catch {
            print("We got an error")
        }
    }.resume()
  }
}

*

*Look at the code and follow these brief explanation:

[1] - Return every rows in section, from local array
[2] - Assigned the name variable to label for current row
[3] - Assigned the name variable to header for current section
extension indexViewController: UITableViewDataSource, UITableViewDelegate {

func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let subDatas = sections[section].subData // [1]
    return subDatas.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // [2]
    let currentSection = sections[indexPath.section]
    let currentSubdata = currentSection.subData[indexPath.row]
    cell.textLabel?.text = currentSubdata.name

    return cell
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40))
    view.backgroundColor = #colorLiteral(red: 1, green: 0.3653766513, blue: 0.1507387459, alpha: 1)

    let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 15, height: 40))
    lbl.font = UIFont.systemFont(ofSize: 20)
    lbl.text = sections[section].name // [3]
    lbl.textAlignment = .right
    view.addSubview(lbl)

    return view
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 40
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 40
  }
}

Happy Coding! =]

A: Just take you section Array outside your function. Keep it as property of your controller.
class indexViewController: UIViewController {

  @IBOutlet weak var tableView: UITableView!
  var sections: [Section] = []

  override func viewDidLoad() {
    super.viewDidLoad()

    let url = "https://nabulsi.com/nabulsi_app/main_sections_v4.json"
    let urlObj = URL(string: url)
    URLSession.shared.dataTask(with: urlObj!) {
     [weak self](data, response, error) in
     do {
          self?.sections = try JSONDecoder().decode([Section].self, from: data!)
          for section in sections {
            //your code goes here
          }
    }
    catch {
      print("We got an error")
    }
  }.resume()
}


text:
Q: Ionic 4 - How can I programmatically clear ion-searchbar? I work with ion-searchbar on Ionic 4.
I would like to know how I can clear the content, if the user clicks on any other button (not the cancel button).
<ion-searchbar id="name_of_searchbar" animated placeholder='search' (ionChange)="buscar($event)">
</ion-searchbar>

In the function (any another button), I try with: document.getElementById ("name_of_searchbar"). innerHTML = "";
but although it modifies the content, it also removes the ion-searchBar
Thank you!

A: Add in search bar [(ngModel)]="searchValue"
<ion-searchbar [(ngModel)]="searchValue"  animated placeholder='search' (ionChange)="buscar($event)">
</ion-searchbar>

And in ts file:
export class PageName {
searchValue:string;
constructor(){}

clearSearch(){
    this.searchValue = "";
}
}

In the button you want the user to clear text with , put inside the button click example :
<ion-button color="primary" (click)="clearSearch()">empty search</ion-button>


text:
Q: Finite state machine to detect if a number is divisible by 5 if LSB comes first If MSB comes in first, we can keep track of the remainder for each new bit since the additional bit will either cause the number to be 2x or 2x+1.
But if LSB comes in first, how can we come up with the fsm? I found some fsm but I wasn't able to understand how they came up with it. Can someone please explain how to go about doing this?

I was just wondering how one can come up with this fsm? I didn't really understand the description in the other post.


text:
Q: Why does std::copy (from istream to ostream) raises an ios::failure exception? The following code should copy data from an wifstream to wcout.
After the content is copied, the program throws a ios::failure exception.
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <locale>
#include <iterator>
#include <algorithm>

int main(void)
{
    std::locale::global(std::locale(""));

    std::wifstream is;
    is.exceptions( std::ios::failbit | std::ios::badbit );
    is.open("test.ts", std::ios::binary);

    is >> std::noskipws;

    std::istream_iterator<wchar_t, wchar_t> in(is);
    std::istream_iterator<wchar_t, wchar_t> end;

    std::copy(in, end,
              std::ostream_iterator<wchar_t, wchar_t>(std::wcout));

    return 0;
}

The stream should only throw an exception (see exception mask) if anything goes bad, but not on EOF.

A: To avoid skipping white space use the std::istreambuf_iterator
std::copy(std::istreambuf_iterator<wchar_t, wchar_t>(is),
          std::istreambuf_iterator<wchar_t, wchar_t>(),
          std::ostream_iterator<wchar_t, wchar_t>(std::wcout));

The exception:
The local may be using codecvt facet that is failing.
Try commenting out the locale line see what happens.
Have you tried to print what the exceptions is?
try
{
    // do work
}
catch(std::exception const& e)
{
    std::cout << e.what() << "\n";
}

A: Because you're using std::istream_iterator, the attempt to read a character past the end of the stream sets both eofbit and failbit (and only after some error bits are set, does the iterator become equal to the end iterator)
Stripping to bare essentials and reverting to char to make it even simpler, program is equivalent to:
#include <iostream>
#include <fstream>
int main()
{
    std::ifstream is("test.txt", std::ios::binary);
    is.exceptions(std::ios::failbit); // failbit only because that's what you get
    is >> std::noskipws;
    if(is)
        for(char c; is >> c;) // will throw!
            std::cout << c;
}

A: According to §27.6.1.2.3/10:

After a sentry object is constructed a character is extracted from in, if one is available, and stored in c. Otherwise, the function calls in.setstate(failbit).

So, when it reaches the end of the file and can no longer extract a character, it will set the fail bit, which you've set to produce an exception. Using std::copy doesn't change the behavior -- an istream_iterator reads via operator>>.
You can copy the file a bit more easily:
std::wifstream is("test.ts", std::ios::binary);
std::wcout << is.rdbuf();


text:
Q: Django | How to reference the User's username when using OneToOneField in UserProfile? Here's my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Userprofile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    username = user.__unicode__()
    path = './data/'+username+'/'
    file = models.FileField(upload_to=path)
    labelfile = models.FileField(upload_to=path, blank=True)
    def __unicode__(self):
        return u"%s" % self.user.username

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Userprofile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

the problem is:
AttributeError: 'OneToOneField' object has no attribute 'model'

I want a file upload function that it can save in a index related to the User's name, but I can't find a good way to do it. And I hope someone can help me. Thanks.


text:
Q: timedelta with pandas_market_calendars Can someone help me with the following:
I want to make some time calculations using market hours calendar. For example if the market closes SEpt 26 at 20:00 (open 13:30) and I add two hours to 19:00 I want to return the time of the next market day one hour after the open:
so "2022-09-26 19:00"+timedelta(hours=2) results in "2022-09-27 14:30" using the calendar below.
There's this pandas library that can be useful. It lists when the market is open.
import pandas_market_calendars as mcal
timeschedule = nyse.schedule(start_date='2022-09-25', end_date='2022-09-30')
timeschedule

    index,market_open,market_close
    2022-09-26 00:00:00,2022-09-26 13:30:00+00:00,2022-09-26 20:00:00+00:00
    2022-09-27 00:00:00,2022-09-27 13:30:00+00:00,2022-09-27 20:00:00+00:00
    2022-09-28 00:00:00,2022-09-28 13:30:00+00:00,2022-09-28 20:00:00+00:00
    2022-09-29 00:00:00,2022-09-29 13:30:00+00:00,2022-09-29 20:00:00+00:00
    2022-09-30 00:00:00,2022-09-30 13:30:00+00:00,2022-09-30 20:00:00+00:00

Any help would be appreciated!
Ivo


text:
Q: Cleaning a .csv (not create a new) I have an .csv when I try to convert to a DataFrame I have this error:
'utf-8' codec can't decode byte 0x92 in position 208: invalid start byte

I know is because the csv file contain simbols like ' and " " and I want to clean it before convert to dataframe. I look how to achieve it but I only find something like this
Removing in-field quotes in csv file
The solution they say is to create a new csv document, but I think is no so efficient...
It's possible to clean a .csv file from this strange characters without creating a new file?
Thanks


text:
Q: Django respond to a search result in a database from navbar I'm working on a django app that has a database with various posts. These posts have names and ids. The ids are in sub urls like sitename.com/1. On every page of the django app, I have a navbar which was extended from base.html. The navbar has a search bar which is really a form submission.
When I want to execute a search, I can take in the search data and use filters on it with the given database. However, the views.py has a function for each sub url. With each sub url that has a form on it, the function on views.py is handling the post request for the form.
How am I going to handle the requests from the search bar form? Do I have to make a function that handles it and then copy paste a call for that function at the beginning of the functions for every other page I want to make? Is there an easier way to do this? I've heard of using @ but I don't know if that is the right use for this sort of problem.


text:
Q: I am able to hit a SOAP web service from eclipse, but not from a jar file I have a webservice wsdl, i need to hit it and parse the response.
I am able to hit it from my IDE Eclipse, but when i make a runnable jar file it shows following error.
java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:209)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
        at sun.security.ssl.InputRecord.read(InputRecord.java:503)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)

We have already performed whitelisting related work at server end but still the problem remains the same.
Can anyone suggest anything ..
Thanks

A: After so many searching and implementations, I've found one line which solved it. Server environment was not supporting my protocol.
I added  below line it solved the problem
System.setProperty("https.protocols", "TLSv1");

A: This problem was because the protocol at client side was not same as protocol used at server side. So to bypass it we can set property according to server side ans our request will be successful.


text:
Q: How to load initial data with playframework2.1 and ebean for single table inheritance? I get this error:
" NullPointerException: null
No source available, here is the exception stack trace:
->java.lang.NullPointerException:
 com.avaje.ebean.Ebean.save(Ebean.java:585)"

after clicking on "Apply this script now" on the initial page that states "Database 'default' needs evolution!".
I have single table inheritance (the only one supported by ebean), where Usuario is the parent table and Operador is child.
I have the next models:
@Entity
@Table(name="usuario")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DTYPE", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("usuario")
public class Usuario {
    @Id
    public Long id;

    @Constraints.Required
    public String username;

    @Constraints.Required
    public String password;

    @Constraints.Required
    public String nombre;

    @Constraints.Required
    public String apellido;

    @Constraints.Required
    @Constraints.Email
    public String email;
}

@Entity
@DiscriminatorValue("operador")
public class Operador extends Usuario {
    @Formats.DateTime(pattern = "dd/mm/yyyy hh:mm:ss")
    public Date ultimaSesion;
}

This is the table definitions for Usuario (defined in /conf/evolutions/defaults/1.sql):
# --- !Ups
create table usuario (
  id serial,
  DTYPE varchar(10) not null,
  nombre varchar(30) not null,
  apellido varchar(35) not null,
  username varchar(30) not null,
  password varchar(255) not null,
  email varchar(255) not null,
  ultima_sesion timestamp,
  constraint pk_usuario primary key (id)
);

As you can see, table Usuario has DTYPE and ultima_sesion (which will be inherited by Operador class)
And this is initial-data.yml:
usuario:
    - !!models.Usuario
        username: usuario1
        password: usuario1pass
        nombre: NombreUsuario1
        apellido: ApellidoUsuario1
        email: email@usuario1.com

    - !!models.Operador
        username: usuario2
        password: usuario2pass
        nombre: NombreUsuario2
        apellido: ApellidoUsuario2
        email: email@usuario2.com
        ultimaSesion: 2013-06-15T17:18:23.18-06:00

    - !!models.Usuario
        username: usuario2
        password: usuario2pass
        nombre: NombreUsuario3
        apellido: ApellidoUsuario2
        email: email@usuario3.com

I load the initial-data using the Global class stored in /app as follows:
public class Global extends GlobalSettings {
    public void onStart(Application app) {
        InitialData.insert(app);
    }

    static class InitialData {
        public static void insert(Application app) {
            if(Ebean.find(Usuario.class).findRowCount() == 0) {
                Map<String, List<Object>> usuario = (Map<String, List<Object>>) Yaml.load("initial-data.yml");
                Ebean.save(usuario.get("usuario"));
            }
        }

    }
}

I can't see where the mistake could be. Maybe it is the way I'm trying to instantiate Operador on initial-data.yml? I suppose it is ok to do !!models.Operador since it is a subclass of Usuario.
Thanks for any help you can provide.


text:
Q: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV So I was working with JSTL in OSGi, under Gemini runtime. And I'm getting following exception, when I try to access the url to my servlet: -
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /WEB-INF/login.jsp (line: 3, column: 66) Unable to read TLD "META-INF/c.tld" from JAR file "file:/D:/OSGi%20Runtime/Gemini/gemini-web/dep/com.springsource.javax.servlet.jsp.jstl-1.2.0.v20110728.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV

However, I have checked, that I already have all the necessary bundles in my runtime. The relevant bundle that I have is: -
71  ACTIVE      javax.servlet_3.0.0.v201103241009
73  ACTIVE      javax.el_2.2.0.v201105051105
74  ACTIVE      javax.servlet.jsp_2.2.0.v201103241009
75  ACTIVE      com.springsource.javax.servlet.jsp.jstl_1.2.0.v20110728
121 ACTIVE      com.springsource.org.apache.taglibs.standard_1.1.2.v20110517

There are more bundles, but those are the ones that are relevant. So, I can't understand what went wrong.
From the Spring Source Repository, from where I downloaded the bundle, it's clear that, org.apache.taglibs.standard bundle - Bundle 121, contains that JstlCoreTLV class.
So, not sure, what's going on here.
Here's my JSP header I'm using (Just in case, it is relevant): -
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

I'm using: -

*

*Servlet 3.0

*JSP 2.2

*Gemini Runtime 2.1

*JSTL 1.2.0

Update: -
The problem described below seems to be solved, and now I'm not getting any warning as shown below. That was because, I was having the taglibs.standard_1.1.2 - (Bundle 121), which was incompatible to others. So, I removed it, and the warnings went away.
So, you can ignore whatever is there from here on. But, The problem above is still there. I'm still getting that JasperException. May be this will help further, as the problem domain is reduced now a little bit thanks to the valuable input from @BalusC.

Part after this is solved. So, you can ignore it: -
Also, I'm not sure that the version of the OSGi JSTL bundle that I have - Bundle 75, is compatible with the other bundles - javax.el, taglibs, servlets, etc, or not. Because I was using JSTL 1.2.1, but I couldn't get the bundle for JSTL 1.2.1. What I got was the bundle I used (JSTL 1.2.0). Why this is bothering me is because of these kinds of messages coming up, when I start my application: -
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jstl/core is already defined
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jsp/jstl/core is already defined
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jstl/fmt_rt is already defined
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jstl/fmt is already defined
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jsp/jstl/fmt is already defined
Jan 22, 2013 7:14:05 PM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: http://java.sun.com/jsp/jstl/functions is already defined

As you can see that there two different URLs shown above: -

*

*URI: http://java.sun.com/jstl/core

*URI: http://java.sun.com/jsp/jstl/core
Now, AFAIK both those URLs, do not belong to same JSTL versions.
So, could that raise some problems? And what can be the reason for them to come? I have just used one JSTL bundle.

A: com.springsource.javax.servlet.jsp.jstl_1.2.0.v20110728
com.springsource.org.apache.taglibs.standard_1.1.2.v20110517

You're mixing JSTL 1.2.0 API+impl with JSTL 1.1.2 impl.
The both impls are conflicting with each other which explains all the trouble you're seeing.
Get rid of the 1.1.2 impl.
See also:

*

*Our JSTL wiki page

A: This is just a shot in the dark. Not sure if you came upon below links.
The error message you posted "Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV" seems to be pretty common.
From this link :
http://christerblog.wordpress.com/2010/05/04/tag-library-woes-deploying-war-on-tomcat-6/
Do you have any conflicting/incompatible jar libraries in your WAR file ?
Another one here also points to incompatible jars in the build path:
Unable to read TLD "META-INF/c.tld"

A: I upgraded from Tomcat 8 to Tomcat 9, which has 125: jstl.jar,taglibs-standard-spec-*.jar, in its catalina.properties. Does this mean that jstl is preinstalled, unlike tomcat 8 where jstl 1.2 was needed in the build.gradle ?
Since I had to remove the following lines to get it working
//compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
//compile group: 'javax.servlet.jsp.jstl', name: 'jstl', version: '1.2'

If my answer is incorrect, please let me know I am happy to delete it. Since @BalusC answer gave me the clue.

A: I faced the exact same issue with my JSP file.
Server - Tomcat 10
I removed the tag lib (below) from my JSP and it worked for me
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

A: First of all, I don't think I can really answer this question, no idea if this is relevant to you.
I've struggled with this problem too, until I switched to Pax Web. It worked pretty much out of the box. I intended to go back and figure out exactly why my previous setup did not work, but, well, it never happened.
So, if it is possible in your situation, use Pax Web over hand picking your own bundles.


text:
Q: Navigation Drawer DrawerArrowStyle Click effect I added navigation drawer with material design using this tutorial. http://www.nkdroid.com/2014/11/Android-Lollipop-Navigation-Drawer-Example-Using-Appcompat-21.html every thing works fine and smooth. when I click on the arrow or menu, button click effect is not showing. thanks in advance.
How can I give the selector for DrawerArrowStyle so that i can have the button effect for that.
    style.xml
<resources>

    <style name="myAppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/primaryColor</item>
        <item name="colorPrimaryDark">@color/primaryColorDark</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/black</item>
    </style>

</resources>

    active_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <include layout="@layout/toolbar" />

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <!-- activity view -->

        <include layout="@layout/main_contents" />

        <!-- navigation drawer -->

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="left|start"
            android:background="#fff" >

            <ListView
                android:id="@+id/left_drawer"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#fff"
                android:divider="#eee"
                android:dividerHeight="1dp" />
        </RelativeLayout>
    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

    toolbar.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" >

    </android.support.v7.widget.Toolbar>

A: Just replaced my toolbar.xml to this and it works awesome. thanks to all...:-)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

</android.support.v7.widget.Toolbar>


text:
Q: Why did Narcissa think Harry knew if Draco was dead or alive? When Voldemort did the Killing Curse on Harry in The Deathly Hallows Part 2 and he asked Narcissa to see if Harry was dead, and she asked if Draco was dead - why did she think Harry knew if he was alive or not? It's not like they're brothers.

A: She wasn't sure Harry would know, but he was more likely to know than anyone else there.
He'd been on the inside of Hogwarts, with the defenders, and she knew Draco was also inside. Stuck in the Death Eater camp, she had no way of knowing what was happening to Draco or even of getting in contact with anyone who knew - until Harry came along. He was the only person in that clearing who might have a chance of knowing whether Draco was alive or dead, so she took that chance and asked him.


text:
Q: How to serve an image as a stream I've noticed in my many years of using the web (and occasionally developing websites) that there are some website that serve images differently than others.

*

*The first kind serves a low quality image first then gradually serve more data so that the image becomes clearer.

*The second kind serves the image as if it's being scanned vertically top to bottom.

This image illustrates what i'm trying to say
As far as I can remember, every PHP, NodeJS server that i have ever set serves images like the second kind.
So my question is how can I achieve behavior 1 in PHP or NodeJS (with ExpressJS) ?
PS:

There is no javascript/ajax/(any 3rd party library being used)
The websites that i have noticed this thing on are not using JS/multiple request to achieve this. It's all purely server side.

A: For the fisrt point , you can use image magick of PHP ,
$im = new imagick();
$im->setResolution(200,200);
$im->readImage('path to the image');
$im->writeImage('path to store the new image with name of image and extension');
$im->clear();
$im->destroy();

You need to set Resolution before  read the image. and then repeat the script depend on your use cases .

Hope that help you .


text:
Q: Вероятностнй анализ алгоритма с двумя переменными Столкнулся с проблемой при вероятностном анализе алгоритма, а именно с индикаторной функцией. Но, начну сначала: есть массив чисел A, все числа в нём разные и заданы случайно (интервал чисел неизвестен). Нужно написать алгоритм на псевдокоде, который будет возвращать все пары чисел A[i]+A[j] mod 2 = 0, при условии, что i<j. C алгоритмом у меня проблем не возникло, т.к. нет никаких ограничений на его эффективность, сделал такой вариант:
procedureDisjunktePaare(Array)%(Input - Array, Output - Array of Paars)
Result = ([])
for i = 1 to Array.size-1 do
   while j=i+1 to Array.size do
       if Array.i+Array.j mod 2 == 0 then
            append(Result, (Array.i, Array.j))
       j++
   i=i++
return Result

Алгоритм простой как валенок: i начинается с первого элемента массива, заканчивается на предпоследнем. j начинается с i+1, заканчивается последним элементом. Во вложенном цикле проверяем условие и если оно выполняется - просто добавляем пару в список Result. Когда цикл For проходит полностью - возвращаем результат.
Очевидно, что в самом худшем случае у нас будет (n-1)(n-1) операций (в случае если все элементы в массиве отсортированы по возрастающей и все они удовлетворяют условию для попадания в список. В данном случае мы делаем n-1 итераций в цикле for, а в цикле While мы делаем в первый раз n-1 поторений, затем n-2 итд вплоть до одной единственной итерации для последней итерации цила for). Но вероятность такого исхода не очень велика. Поэтому для ожидаемого времени надо применить вероятностный анализ. С этим чуть сложнее.
Я понимаю, что надо использовать как советует Кормен индикаторную функцию. Но я не очень понимаю, как задать её для условия, что одна переменная будет меньше другой.
Но каково тогда E[Xi]?  Насколько я понимаю, я должен отталкиваться от следующего:
Xi=1, если A[i]+A[j] mod 2 = 0; 0 - во всех остальных случаях.
Для этого либо оба элемента должны быть чётные, либо оба элемента должны быть нечётные. Т.к. у нас предполагается полный рандом, то вероятность любого из этих событий 1/4, что делает суммарную вероятность 0.5. Но мне кажется, что такой подход абсолютно наивен и ошибочен.

A: Вообще ваш алгоритм при любых входных данных сделает ~n^2/2 сравнений (1+2+ ... +(n - 1)). Но кажется вы спрашиваете, какая средняя величина результирующего массива в конце алгоритма.
Пусть F(n, k) - количество пар в результирующем массиве, если во входных данных k четных чисел и n - k нечетных чисел. Очевидно, что F(x) = k * (k - 1) / 2 + (n - k) * (n - k - 1) / 2. Тогда мат. ожидание размера результирующего массива будет выражаться следующей функцией:

И если вы верите вольфраму, то результат будет следующим:

Это, конечно, не вероятностный анализ, но как мне кажется, мой способ даже проще и точнее.

A: Немного посидев и подумав, я нашёл то, что искал. Искомое решение было следующим:
Пусть индикаторная переменная Х будет следующей:

Тогда:

Как я уже писал в вопросе, наше условие работает когда оба сверяемых числа чётные или оба нечётные. Вероятность каждого из этих событий 1/4. Вероятность, что выпадет одно из этих событий - 1/2. В этом случае

Моей ошибкой было то, что я забыл, что в случае ряда, если у нас константа под знаком, то мы всё равно можем применить формулу (см последнее изображение).


text:
Q: Electrons diffusion in gas with present of electric field For research purposes, I am looking for a way to calculate how far the electrons "spread" perpendicularly to the electric field in a chamber of gas.
For example, if a beam of alpha particles ionize the gas in a chamber and leave a track of electron-postive ion pairs, is there a way to calculate how far the electrons move away from the point of ionization (perpendicular to the electric field). Note: also present in the gas chamber is an electric field, so the electrons and positive ions would move in opposite direction. I am reading W. R. Leo's Techniques for Nuclear and Particles Physics Experiments for hints on how to calculate this, but I haven't found any mention of this yet. The closest thing I found was about electron diffusion with the absent of an electric field. Please point me to articles, book chapters, equations, or links regarding information of this topic. Thanks in advance.

A: I have found the answer in the W. R. Leo's Techniques for Nuclear and Particles Physics Experiments. The equations that I needed are Eq. 6.18
$D=\frac1 3 v \lambda $ and Eq. 6.46 $\sigma=\sqrt{2Dx/\mu E}$.


text:
Q: grep regex .* not matching everything I've recently gotten into using tools like grep, wc, cat, etc. because I have to deal with some very large CSV files (>10GB) which aren't quite delimited correctly (for instance, having occurrences of the delimiter character inside some of the fields.
In my working with one of these files, I've run the following command in the process of trying to figure out a way to correctly identify which instances of ; is a delimiter and replace them with some other character:
grep -v -n --text "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" < Transactions.csv

The regex can probably be done much better, but anyway; what is surprising is that, among others, the above code outputs the following line:
12345678:2016-10-25;12345678912345;2016-10-25;gobbledegook �IDNR: 69 ;12345.67;.00;2003-09-05;12345678;2003-09-03;stuff stuff         ;12345 fgadfkjgbsdkb;12/3/45678/9

(as this was actually transaction data, I've changed most of the fields' values, except for the offending �) Maybe I'm being silly, but why doesn't the above regex match that line? It seems like the regex .* somehow doesn't match that character for some reason.
I suspect that the file is saved using the UTF-16 encoding, if that makes any difference.
Edit: Thanks to @exore for the answer. As it turns out, my file was encoded in ISO-8859-15, which I was able to figure by grepping out the lines containing special characters, which were relatively few, into a file and opening that in gedit. I then used iconv to convert that to utf8, after which it worked fine!

A: This is a typical char encoding problem. . means any character. But which sequence of byte is a legal character is a matter of encoding. Dealing with text without the knowledge of the encoding is a sure failure. Your grep command probably expect UTF-8 encoded string. UTF-8 is a multibyte encoding, meaning that some char are represented by multiple bytes. However, not all sequence of bytes are valid. See, for example, the Wikipedia article on UTF-8.
When grep encounters a byte sequence that is not a valid char in the expected encoding, it cannot recognise it as a character, the line doesn't match, it's output. Since your terminal doesn't recognise the char either, you get a �.
There is a workaround in your case. Tell grep not to bother about encoding, and consider one byte as one char.
env LANG=C grep ....

or maybe
env LANG=C LC_ALL=C grep ....

You may test easily:
Create 2 files, one utf-8 encoded, one utf-16-be:
$ echo éléphant | tee file.std | iconv -f utf8 -t utf16be >file.utf16be

Check content of files:
$ cat file*
éléphant
�l�phant

Try to grep. The utf16be string is not recognised, no output:
$ grep '^.*$' file*
file.std:éléphant

Don't use encoding at all. One byte is one char. all strings are matched
the � just means the terminal doesn't recognise the utf16be sequence as a
valid utf-8 char. Note the use of -a to tell grep to consider binary is
is some text.
$ env LANG=C grep -a '^.*$' file*
file.std:éléphant
file.utf16be:�l�phant

Alternatively, if you know the encoding, then you can use iconv to first convert your file then use grep. One of the following should work.
iconv -f utf16   -t utf8 < file | grep ...
iconv -f utf16le -t utf8 < file | grep ...
iconv -f utf16be -t utf8 < file | grep ...


text:
Q: Part of my layout goes upward with keyboard My android app have a layout like this when i open keyboard two imageview at the bottom of the page shows up over the keyboard , i couldnt see the problem why it goes upward with the keyboard can you help me about this ?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <LinearLayout
        android:id="@+id/searchLinear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/upperbackground">

           <EditText
            android:id="@+id/searchBox"
            android:layout_alignParentTop="true"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:layout_margin="12dip"
            android:paddingLeft="35dip"
            android:textSize="15sp"
            android:background="@drawable/search_bar"/>

    </LinearLayout>

    <LinearLayout
            android:id="@+id/searchButtons"
            android:layout_below="@id/searchLinear"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:background="@color/upperbackground">

        <ImageView
            android:id="@+id/btnSukela"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:onClick="sukelaClickEvent"
            android:paddingRight="8dip"
            android:paddingBottom="5dip"
            android:src="@drawable/sukela"/>

        <ImageView
            android:id="@+id/btnSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/btnSukela"
            android:clickable="true"
            android:focusable="true"
            android:onClick="searchEntryClickEvent"
            android:paddingLeft="8dip"
            android:paddingBottom="5dip"
            android:src="@drawable/search"/>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/bottomLinear"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:background="@drawable/bottom_back">

        <ImageView
            android:id="@+id/btnToday"
            android:src="@drawable/today"
            android:background="@color/bottombackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/bottomLinear"
            android:layout_marginBottom="19dip"
            android:layout_centerVertical="true"
            android:clickable="true"
            android:focusable="true"
            android:onClick="todayClickEvent"/>

        <ImageView
            android:id="@+id/btnPopular"
            android:src="@drawable/popular"
            android:background="@color/bottombackground"
            android:layout_toRightOf="@+id/btnToday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:clickable="true"
            android:focusable="true"
            android:onClick="popularClickEvent"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/searchButtons"
        android:layout_above="@+id/bottomLinear"
        android:background="@color/background">

        <ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </RelativeLayout>

</RelativeLayout>

A: I think you need to set the soft input mode:
<activity android:windowSoftInputMode="adjustPan" ...>

in your manifest, so the window will not resize when the keyboard appears.


text:
Q: Excel formula gives error when write using Apache-poi library in Java I have requirement to write data to excel file which I have achieved. And another requirement is to include piece cell in the summation if status cell of same row is "Recived".
And the summation should be done for visible cells only. I have 2 column like "Status"(Column A2:A10) and "piece" (B2:B10) now I have put the formula in my java class using  apache-poi library:
SUMPRODUCT(SUBTOTAL(9,OFFSET(B2:B10,ROW(B2:B10)-(ROW(B2)),0,1)),(--(A2:A10="Recived")))

After executing the Java code it writes the file successfully but when I open the file it shows the formula cell as #VALUE!.  When I go to formula bar and press enter then the value for the formula comes.
I want the value for the formula to be displayed every time I open the Excel file.
Below is Java code
cell.setCellType(Cell.CELL_TYPE_FORMULA);
cell.setCellFormula("SUMPRODUCT(SUBTOTAL(9,OFFSET(B2:B10,ROW(B2:B10)-(ROW(B2)),0,1)),(--(A2:A10=\"Recived\")))");

A: I have tried a sample code. You need to set the cell type to Numeric (or whichever data type your excel formula will return).
See below example:
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Row row = sheet.getRow(0);
Cell cell2 = row.createCell(2);
//set cell formula
cell2.setCellFormula("SUM(A1:B1)+10");
//evaluate the formula
evaluator.evaluateFormulaCell(cell2);
//set the cell type to numeric
cell2.setCellType(Cell.CELL_TYPE_NUMERIC);
System.out.println(cell2.getNumericCellValue());

//write data to excel file
FileOutputStream out = new FileOutputStream(new File("res/Book1.xlsx"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");

I have tried this example and it is not giving me #VALUE! error.


text:
Q: catalog/products_list not working with different static blocks I want to display category wise products on my homepage, for that i am using catalog/list via custom static blocks. Below is my code which i am pasting in my static block content.
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="3" template="catalog/product/list.phtml"}}

The problem is when i am pasting the same code in my another static block to display products from different category it is not working.
Please assist me what i am doing wrong.

A: From ,Magento Community v1.9.2.x,you need to remove a block of a static block
from white list.
Try to navigate to `System > Configuration > Permissions > Blocks > Add New Block
Block Name: catalog/product_list
Is Allowed: Yes
Make sure to clear cache and it should work.

A: I have resolved it, actually i am using flexslider along with this block.
Everything was in place i have created the block, got it displayed on custom homepage and then changed the category id but because i didn't created another id in flexslider for my another category it was not being displayed on the homepage but actually block was working products were coming from db. Its because of the slider id it was not working.
Hope this helps someone :-)


text:
Q: Subgroups of semi-direct products of two elementary abelian subgroups. First question: Let $H'$ be a subgroup of $H$ and $K'$ a subgroup of
$K$. Is it true that $H'\rtimes K'$ and $H'\times K'$ are subgroup of $H\rtimes
K$?
Second question: Let $G=(\mathbb{Z}/p\mathbb{Z})^{n}\rtimes
(\mathbb{Z}/p\mathbb{Z})^{m}$. What is the number of subgroups of
$G$ isomorphic to $(\mathbb{Z}/p\mathbb{Z})^{2}$?
Third question: Is it true that if $\gcd (|H|,|K|)=1$ then all
subgroups of $H\rtimes K$ are of the form $H^{\prime }\rtimes K^{\prime }$.

A: First question: If it exists, it's a subgroup, but since conjugation by elements of $K^{\prime}$ may take elements of $H^{\prime}$ to elements of $H\setminus H^{\prime}$, it need not exist.
Second question: That depends on the action involved in the semidirect product.  For example, consider $2^2\rtimes 2$.  If the action is trivial, we get $2^3$ which has seven subgroups isomorphic to $2^2$.  If the action is non-trivial, we get $D_4$, which has only two such subgroups.
(Note that $p^n$ is traditional shorthand for $(\mathbb{Z}/p\mathbb{Z})^{n}$.)
Third question: No, since at the very least, if the action is non-trivial, $K$ has conjugates that intersect $H$ trivially and are not contained in $K$.


text:
Q: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY error thrown in random places Recently I've started getting error message:

System.DmlException: Upsert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, Access to entity 'AIInsightValue' denied: []

What's interesting it happens randomly while performing operations like closing Opportunities, updating Work Order statuses and closing Orders.
Moreover on second ORG I've spotted similar error, but it throws different message

System.DmlException: Upsert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, Access to entity 'CollabDocumentMetricRecord' denied: []

I've double checked permissions, user privileges and Sharing and Security settings. What's more intereting it occurs inconsistently. There are "windows" when placing orders and processing works as it should work, but after 30-40 mins ORG is unusable because of this error.
Any ideas?

A: You can check the record access of the following record by querying on UserRecordAccess
SELECT RecordId,MaxAccessLevel,HasAllAccess,
    HasDeleteAccess,
    HasEditAccess,
    HasReadAccess,
    HasTransferAccess
FROM UserRecordAccess
WHERE UserId = 'The UserId of the user with whom you are getting error'
AND RecordId = 'Pass the record id for which you are getting this error'

This will given you clear picture of what kind of access is there for the user.
If there is no access, then you might have to check if the access to this records gets assigned by some related record.
The root cause should be in sharing the record access. You might have access from Permissionset or Profile, but you may have defined related or object access as Private or Controlled By Parent etc... And might not have any read or readwrite permissions from Sharing rules.


text:
Q: Sidescroller game with customer gestures on unity I was wondering what turotials are out there for creating games for the windows phone? What I'm trying to do is create a sidescroller game which will allow gesture control. Such as if you click on an enemy, it moves to them then attacks them. If you swipe with one finger, it does one move. If you swipe with 2 fingers, it does another. If you make a circle, it does another move.

A: There's plenty of community help on the topics of touch inputs, you'll either have to write your own custom input handling class for gesture detection or purchase an asset store package that does the same.
You could start here


text:
Q: loki reject_old_samples_max_age vs retention_period We're using latest loki, but confused how to define the retention properly:
What is the difference between:

*

*reject_old_samples_max_age

*retention_period

What takes the priority?
In the example below, will the data be deleted after 168h or 336h?
limits_config:
      enforce_metric_name: false
      reject_old_samples: true
      reject_old_samples_max_age: 168h
      max_cache_freshness_per_query: 10m
      retention_period: 336h

A: Data will be deleted after 336h because the "retention_period" parameter defines that. The "reject_old_samples" (true or false) and "reject_old_samples_max_age" parameters are related to if old log entries received by Loki should or shouldn't be accepted by the tool and how old these log entries can be and still be accepted.
See more information about the Loki configuration here.


text:
Q: Error: "Activation could not be completed because the InfoPath Forms Services support feature is not present ." We have been using form uploaded on sharepoint online and after a simple modification (adding some text fields) the form shows the following error:
"Activation could not be completed because the InfoPath Forms Services support feature is not present ."
I have tried with no success:

*

*a) Uploading an old versión that used to work;

*b) Creating a new form library for the same form;

*c) Creating a new form library for a new form;

All other site collections in the farm do not have this issue. Please help on how to resolve this.

A: Try de-activating and reactivating the "SharePoint Server Enterprise" features at both the site collection and the site level.

Update:
Try de-activating and re-activating "IPFSSiteFeatures" feature. It is a hidden site collection feature. We can do that with PowerShell.
The "IPFSSiteFeatures" feature id "c88c4ff1-dbf5-4649-ad9f-c6c426ebcbf5".
SharePoint Online: Deactivate Feature using PowerShell
How to enable a SharePoint Online Feature using PowerShell

A: Disable-SPFeature "IPFSSiteFeatures" -URL "http://yoursitecollectionURL"
Enable-SPFeature "IPFSSiteFeatures" -URL "http://yoursitecollectionURL"

This fix worked for me.


text:
Q: Can Kendo UI grid be bound to a JSON-serialized Microsoft.NET System.Data.DataTable Can Kendo UI grid be bound directly to a JSON-serialzed Microsoft.NET System.Data.DataTable?
When serialized to JSON, the System.Data.DataTable becomes an array of objects with the fieldnames repeated in each object:
     [{"name":"joe", "age":40},
      {"name":"pam", "age":33}]

A: Yes. The Kendo UI grid can be bound to any JSON object which has an array of "records". For example:
$("#grid").kendoGrid({
   dataSource: [
      {"name":"joe", "age":40},
      {"name":"pam", "age":33}
   ]
});

Here is a live demo: http://jsbin.com/edokun/1/edit


text:
Q: re.sub replace spaces with comma I have a list of items which look like so:
 2.4       -2.0           4.3
-6.0       12.5           1.0

What I would like is to remove all those spaces and replace them with "," (comma) except for the spaces in front of first numbers (they should be just deleted (the spaces) and not replaced with anything). So the upper string items should look like so, after replacement:
2.4,-2.0,4.3
-6.0,12.5,1.0

Not like this:
,2.4,-2.0,4.3
,-6.0,12.5,1.0

Which is what the following code does:
newStrings = []
for s in strings:
    newStrings.append(re.sub('\s+', ',', s))

What regular expression for re.sub should be used to achieve that?
Thank you.

A: To remove the leading and trailing spaces you can use .strip(), and then to replace consecutive whitespace characters using the regular expression \s+:
>>> import re
>>> s = " 2.4       -2.0           4.3"
>>> re.sub("\s+", ",", s.strip())
'2.4,-2.0,4.3'

A: There are many solutions... This doesn't even briefly cover the whole topic, but it works:
Quick solution:
In [1]: import re
   ...: d_in = "strip \t\r\n\x00er \ter\rMY\   nr\x00 \t\r\nSPAC       ES\x00  ! "
   ...: d_out = re.sub("\s+", r",", d_in)
   ...: d_out
   ...:
Out[1]: 'strip,\x00er,er,MY\\,nr\x00,SPAC,ES\x00,!,'


text:
Q: Trick to remember when to reject null (p-values vs alpha) I teach introductory statistics to undergraduates and they are often confused with hypothesis testing. In particular, while the rule is

we reject the null hypothesis at significance level $\alpha$ when p value is less than $\alpha$

they many times interpret it the opposite. Say, if p value is 0.04, they say "we reject at 1% but not at 5%".
On one level, it is about the deeper understanding, which might be my fault as a teacher. But on another level (given that we are not always engaging with the deeper side of things), perhaps a cool mnemonic tip would help them with correct interpretation
Do you have a cool, undergraduate-level tip about how to correctly interpret p values vs significance level $\alpha$? I haven't come across any such tip.

A: This surely will not top the list of possible "cool undergraduate-level tips", but simply recalling the definition of a p-value might be helpful (quoted from Wikipedia):

The probability of obtaining test results at least as extreme as the
results actually observed, under the assumption that the null
hypothesis is correct.

So the smaller the probability, the smaller significance level at which we are willing to reject.

A: The standard mnemonic for remembering how to make a conclusion in a hypothesis test is:

If p is low, the null must go!

As to why this is the case, the best explanation of a classical hypothesis test is that it is the inductive anologue of a proof by contradiction.  In a proof by contradiction we begin with a null hypothesis, show that this leads logically to a contradiction, and therefore reject the initial premise that the null is true.  In a classical hypothesis test, we begin with a null hypothesis, show that this leads to a highly implausible result in favour of the alternative (so not quite a deductive contradiction, but close), and therefore reject the initial premise that the null is true.  The p-value in this test is the probability of a result at least as conducive to the alternative hypothesis, assuming the null is true (see formal explanation here).  If this is low then it means that something very implausible happened (under the assumption that the null is true) which gives the "contradiction" in the "inductive proof by contradiction".