text:
Q: How to push readme.txt into azure container registry for the docker images? I have created a lot of customized docker images and I have pushed the same into Azure container registry with tags. Now the major problem that the team face is that they are unaware of how to run the docker images (the run command with env/port and volumes) or define the docker-compose files.
Could any let me know if we can attach/push a readme.txt on how to use the image in azure container registry and how to use it?
Please share me code or link on how to use it.

A: Content formats supported in Azure Container Registry
Use a private repository in Azure Container Registry to manage one of the following content formats (at the time of writing).
Docker-compatible container images
The following Docker container image formats are supported:

*

*Docker Image Manifest V2, Schema 1

*Docker Image Manifest V2, Schema 2 - includes Manifest Lists which allow registries to store multi-architecture images under a single image:tag reference

OCI images
Azure Container Registry supports images that meet the Open Container Initiative (OCI) Image Format Specification, including the optional image index specification. Packaging formats include Singularity Image Format (SIF).
OCI artifacts
Azure Container Registry supports the OCI Distribution Specification, a vendor-neutral, cloud-agnostic spec to store, share, secure, and deploy container images and other content types (artifacts). The specification allows a registry to store a wide range of artifacts in addition to container images. You use tooling appropriate to the artifact to push and pull artifacts. For examples, see:

*

*Push and pull an OCI artifact using an Azure container registry

*Push and pull Helm charts to an Azure container registry
To learn more about OCI artifacts, see the OCI Registry as Storage (ORAS) repo and the OCI Artifacts repo on GitHub.

Helm charts
Azure Container Registry can host repositories for Helm charts, a packaging format used to quickly manage and deploy applications for Kubernetes. Helm client version 3 is recommended. See Push and pull Helm charts to an Azure container registry.

Now to answer your specific question,
You can either masquerade your readme.txt file as an OCI artifact with single file and push it to the Azure Container Registry and pull from the registry as shown here or push the README file as part of a Helm Chart structure (if you are pushing a Helm chart to the Azure Container Registry).


text:
Q: Анализ выполнения android приложения? Всем доброго времени суток.
Пишу сейчас небольшое приложение, и по-неопытности оно у меня получается не оптимизированным, меня интересует можно ли в момент выполнения приложения в GenyMoution каким то образом проверить количество классов которые создает приложение?

A: Если делать проект в Android Studio, то можно отслеживать количество свободной и занятой оперативной памяти для вашего приложения. Нажимаете на вкладку (внизу) Android Monitor, далее жмякаете вкладку Memory, там динамически можно отслеживать свободную и занятую память по графику, также там можно смотреть объекты в стеке и куче. Посмотрите статью, которую посоветовал @Eugene Krivenja, там описано это более подробно

redpajama_set_name: RedPajamaStackExchange


text:
Q: Source developed using Android 2.3.3 google Apis does not work for Android 4.0.3 I developer an Android app using Android 2.3.3 Google apis . The same source I tried to build again using Android 4.0.3 Google apis. But when I try to run the app the console is showing error as "Failed to install Shared Library" "Check LogCat  for more details". When checked in "Logcat" its showing error as  unable to find com.google.android.maps .Can anyone help me in sorting out this issue.

A: for eclipse you have to install GOOGle maps api seprately for each version might be your eclipse have Google Map api for 2.3 but not for 4.0

A: You might forgot to add librery in your mainfest file.
add the following code within mainfest file( Inside Appication tag)
      <uses-library android:name="com.google.android.maps" />

A: Library management changed from r17. If you updated your ADT to this version or higher try this:
Right click project > Properties > Java Build > Order and Export
Move your libraries to the top


text:
Q: Consider a branching process $\{X_n , n \geq 0 \}$ in which the offspring distribution is binomial $(k,p)$ Consider a branching process $\{ X_n , n \geq  0  \}$ in which the offspring distribution is  binomial $(k,p)$. Find probability of ultimate extinction when $k = 3$.
So I've tried this:
$P_k = P(\lambda = t) = {3 \choose t} p^t (1-p)^{3-t} $
$ \phi(s) = \sum_{k=0}^\infty p_k s^k = p_0 s^0 + p_1s^1 +p_2s^2 + p_3s^3  $ (as  $k =3$)
$ \phi(s) = (1-p)^3 + 3p(1-p)^2 s + 3p^2(1-p)s^2 + p^3s^3$
I've gotten till here but I'm unsure if I'm on the right track and if right, how do I proceed?
Thanks!

A: Let $\mu=3p$ be the mean of the offspring distribution. If $\mu\leqslant 1$, then the probability $\pi$ of extinction is one. If $\mu>1$, then $\pi$ is the unique solution to the equation $\varphi(s)=s$ on the interval $(0,1)$. Solving
$$
(1-p)^3 + 3p(1-p)^2 s + 3p^2(1-p)s^2 + p^3s^3 = s
$$
yields the solutions
\begin{align}
s &= 1\tag1\\
s &= \frac{2 p^3-3 p^2-\sqrt{4 p^3-3 p^4}}{2 p^3}\tag2\\
s &= \frac{2 p^3-3 p^2+\sqrt{4 p^3-3 p^4}}{2 p^3}.\tag3
\end{align}
By inspection, $(3)$ is the correct solution (since it yields numbers between zero and one when $\frac13<p<1$).


text:
Q: Create a dockerfile that runs a python http server to display an html file I have a directory with one simple HTML file (name: index.html) which displays some basic text. I run the python command:
python -m SimpleHTTPServer 7000

to run a server, at port 7000, in the same directory to display the page in a browser.
Now I want to be able to dockerize this process and need help with that.
Basically, the dockerfile should run a server at 7000 port using this python command and then display the html on a browser.
What I thought of:
FROM ubuntu:14.04
COPY index.html
FROM python:latest
EXPOSE 80
CMD ["python SimpleHTTPServer 7000", "-m"]

Also, how would I build and run this file once it is done?
I am pretty sure this won't work but since I am new to this, I don't know how to correct it.

A:
Also, how would I build and run this file once it is done?

You were close. Several pointers:

*

*If you use python3 then you have to either use http.server or install SimpleHTTPServer separately

*If you use python 2.7 then you can't use 'latest' tag in manner you are using it

*Container port and your desired target local port are not the same

Here are Dockerfile variations for python 3:
FROM python:latest
COPY index.html /
EXPOSE 7000
CMD python -m http.server 7000

and python 2.7:
FROM python:2.7
COPY index.html /
EXPOSE 7000
CMD python -m SimpleHTTPServer 7000

alongside with build
docker build -t my-docker-image .

and run commnand:
docker run --rm -it --name my-docker-instance -p 80:7000 my-docker-image

After run you can go to http://localhost to get container's port 7000 there, providing your host doen't run something on port 80 (remap if so).
Notes:

*

*Using latest image is ok for development, but problematic in production

*work dir is set to root, maybe you would like to position files appropriately

*running code off simple server is ok for defvelopment

Edit:
I see that b0gusb beat me to it :)


text:
Q: Charting journey frequency in Excel I have a list of 10 start destination and 25 Points of Interest(POI) like;
Start            POI
Town A           Aquarium
Town B           Library
Town C           Museum
Town D           Fair
Town E           Race Track
                 Auto Track
                 Planetarium

Each journey is from a Start to a POI, I want to visually show the journey and the frequency, so it could be a line from Town A to Library, the line gets thicker the higher the journey frequency. How can I create a chart that could represent this, is it possible.


text:
Q: Can't connect to service when using consul for service discovery | Node.js I am working on creating an API gateway and so far I can manage to get everything to work for single instances where I hard code the IP and port of the server I want my API gateway to connect to.
I have seen few examples of how to accomplish service discovery with Consul/Node.js.
I did find this one and I have tried to make it work but I can't get the watcher to work right and pass me the IP:port combo I need to connect to the service.
All of the below files are just parts and not the whole thing. The important parts are there though.
This is my app.js file
app.listen(port, () => {
    const CONSUL_ID = require('uuid').v4();
    const ip = require('ip');
    const my_IP = ip.address();
    let options = {
      name: 'api-gateway',
      address: `${my_IP}`,
      port: 8080,
      id: CONSUL_ID,
      check: {
        ttl: '10s',
        deregister_critical_service_after: '1m'
      }
    };
    consul.agent.service.register(options, function(err) {
      if (err) throw err;
      console.log(`Registered service with ID of ${CONSUL_ID}`);
    });

    setInterval(() => {
      consul.agent.check.pass({id:`service:${CONSUL_ID}`}, err => {
        if (err) throw new Error(err);
      });
    }, 5 * 1000);

    process.on('SIGINT', () => {
      console.log(`SIGINT. De-Registering service with ID of ${CONSUL_ID}`);
      consul.agent.service.deregister(CONSUL_ID, (err) => {
        if(err) console.log(`Error de-registering service from consul, with error of : ${err}`);
        if(!err) console.log(`De-registered service with ID of ${CONSUL_ID}`);
        process.exit();
      });
    });
    console.log(`API gateway server running express started on port ${port}.`);
});

I have two other test services running that the only difference between my app.js above and these test ones are that they have name: 'test-service', for the service name.
This is my routes file
var consul = require("consul")({host: '10.0.1.248'});
var known_data_instances = [];
const apiAdapter = require('./apiAdapter')

// Keep a list of healthy services
var watcher = consul.watch({
  method: consul.health.service,
  options: {
    service:'test-service',
    passing:true
  }
});

watcher.on('change', data => {
  console.log('received discovery update:', data.length);
  known_data_instances = [];

  data.forEach(entry => {
    known_data_instances.push(`http://${entry.Service.Address}:${entry.Service.Port}/`);
  });
});

watcher.on('error', err => {
  console.error('watch error', err);
});

const BASE_URL = known_data_instances[Math.floor(Math.random()*known_data_instances.length)];
// const api = apiAdapter(BASE_URL + ':8081');
const api = apiAdapter(BASE_URL);

// router.get('/login', isAuthorized, (req, res) => {
router.get('/login', (req, res) => {
  api.get(req.path).then(resp => {
    res.send(resp.data);
  });
});

API adapter file
const axios = require('axios');

module.exports = (baseURL) => {
  return axios.create({
    baseURL: baseURL,
  });
};

I am expecting to be able to send a request using axios to a HTTP endpoint on a different service on a different server when getting the IP and port from consul.
Actual result is:
(node:3230) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)

Seems to me like it is not picking up the URLs and is defaulting back onto localhost port 80.
I'm a bit lost on all of this since I have never build an application with consul and while the consul.io docs are great, there just isn't much of a guide base online for making this easy to learn.
Guess the question comes down to, how do I get my api adapter to make requests to my different services, in this case test-service?


text:
Q: How to extract subject information from certificate signing request? I am trying to extract suject information from the CSR using python.
Here is a CSR created with cryptography library.
Generate key
from cryptography.hazmat.primitives.asymmetric import rsa

key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)

Create CSR
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes

# Generate a CSR
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([

    # Provide various details about who we are.
    x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
    x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"),
    x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
    x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"),
])).add_extension(
    x509.SubjectAlternativeName([

        # Describe what sites we want this certificate for.
        x509.DNSName(u"mysite.com"),
        x509.DNSName(u"www.mysite.com"),
        x509.DNSName(u"subdomain.mysite.com"),
    ]),
    critical=False,
# Sign the CSR with our private key.
).sign(key, hashes.SHA256())

Extract public key
public_key = csr.public_key()

Extract subject information
Is there a way to extract subject information from the CSR using python ?


text:
Q: Kafka Java API offset operations clarification I'm trying to use low-level Consumer  Java API to manage offsets manually, with the latest kafka_2.10-0.8.2.1. To verify that the offsets I commit/read from Kafka are correct, I use the kafka.tools.ConsumerOffsetChecker tool.
Here is an example of the output for my topic/consumer group:
./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --group   elastic_search_group --zookeeper localhost:2181 --topic my_log_topic
Group           Topic                          Pid Offset          logSize         Lag             Owner
elastic_search_group my_log_topic              0   5               29              24              none

Here is my interpretation of the result:
Offset = 5 --> this is the current offset of my 'elastic_search_group' consumer
logSize = 29 --> this is the Latest offset - the offset of the next message that will come to this topic/partition
Lag = 24  --> 29-5 - how many messages are not yet processed by my 'elastic_search_group' consumer
Pid - partition ID
Q1: is this correct?
Now, I want to get the same information from my Java consumer. Here, I found that I had to use two different APIs:
kafka.javaapi.OffsetRequest to get Earliest and Latest offsets, but kafka.javaapi.OffsetFetchRequest to get the current offset.
To get Earliest (or Latest) offset I do:
TopicAndPartition topicAndPartition = new TopicAndPartition(myTopic, myPartition);
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.EarliestTime(), 1));
// OR for Latest: requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), clientName);
OffsetResponse response = simpleConsumer.getOffsetsBefore(request);
long[] offsets = response.offsets(topic, partition);
long myEarliestOffset = offsets[0];
// OR for Latest: long myLatestOffset = offsets[0];

And to get the current offset I have to use a completely different API:
short versionID = 0;
int correlationId = 0;
List<TopicAndPartition> topicPartitionList = new ArrayList<TopicAndPartition>();
TopicAndPartition myTopicAndPartition = new TopicAndPartition(myTopic, myPartition);
topicPartitionList.add(myTopicAndPartition);
OffsetFetchRequest offsetFetchReq = new OffsetFetchRequest(
kafkaGroupId, topicPartitionList, versionID, correlationId, kafkaGroupId);
OffsetFetchResponse offsetFetchResponse = simpleConsumer.fetchOffsets(offsetFetchReq);
long currentOffset = offsetFetchResponse.offsets().get(myTopicAndPartition).offset();

Q2: is it correct? why are there two different APIs to get a very similar information?
Q3: does it matter which versionId and correlationId I am using here? I though  versionId should be 0 for pre-0.8.2.1 kafka, and be 1 for 0.8.2.1 and later - but seems like it works with 0 for 0.8.2.1 as well - see below ?
So, for the the example state of the topic above, and the above output of the ConsumerOffsetChecker, here is what I get from my
Java code:
currentOffset=5; earliestOffset=29; latestOffset=29
'currentOffset' seems to be Ok, 'latestOffset' is correct too, but the 'earliestOffset'? I would expect it to be at least '5'?
Q4: How could it happen that the earliestOffset is higher than the currentOffset?
My only suspicion is that maybe messages from the topic were cleaned out due to retention policy…. Any other cases this could have happened?

A: I was searching for means of finding lag in partitions. And that involves same steps you have taken. So far, from whatever I have learnt, I can give you answers.

*

*logSize directly points to how many messages have been accumulated in that specific partition. Or, it specifies max offset of messages in that partition. Offset is the offset of last successfully consumed message. So lag is just the difference between Log size and Offset.

*Yes it is correct. So far, those are the only two ways of finding current offset and earliest or latest offset

*I don't know why there's a need to specify versionId. You can use kafka.api.OffsetRequest.CurrentVersion() to  get versionId. So hardcoding can be avoided. You can safely assume correlationId as 0.

*This is strange. When I use EarliestTime() I get earliest offset as 0 even when my current offset has progressed much further. It means it's the start of partition. So when some messages get expired in some future time, this earliest offset will then be some non-zero number. Now if messages were cleared out because of retention policy lag should have been changed. I am uncertain about this behaviour. One way to be certain would be, running consumer after noting such reading and checking in it's logs. It should show lines like these.
2015-06-09 18:49:15 :: DEBUG :: PartitionTopicInfo:52 :: reset consume offset of requests:2: fetched offset = 405952: consumed offset = 335372 to 335372
2015-06-09 18:49:15 :: DEBUG :: PartitionTopicInfo:52 :: reset consume offset of requests:2: fetched offset = 405952: consumed offset = 335373 to 335373
Note that in above log lines, fetched offset remains same and consumed offset is increasing. Finally it would end in
2015-06-09 18:49:16 :: DEBUG :: PartitionTopicInfo:52 :: reset consume offset of requests:2: fetched offset = 405952: consumed offset = 405952 to 405952
Then this would mean that due to log retention policy offset from 335372 to 405952 were expired


text:
Q: undefined reference within the same file I'm getting an undefined reference to one private methods in a class.  Here is a short snippet of the code (but the whole thing currently is in one source file and not separated into header and source files).
#include <iostream>

using namespace std;

struct node
{
    int key_value;
    node *left;
    node *right;
};

class btree
{
    node *root;
    btree();
    ~btree();
    void destroy_tree(node *leaf);

    public:
    void destroy_tree();
};

btree::btree()
{
    root = NULL;
}

btree::~btree()
{
    destroy_tree();
}

void btree::destroy_tree()
{
    destroy_tree(root);
}

void destroy_tree(node *leaf)
{
  if(leaf!=NULL)
  {
    destroy_tree(leaf->left);
    destroy_tree(leaf->right);
    delete leaf;
  }
}

int main()
{
    return 0;
}

The compiler outputs "undefined reference to `btree::destroy_tree(node*)' for this line:
destroy_tree(root);

but isn't the definition of that function immediately right below it?

A: Your destroy_tree overload is not scoped to btree.  The implementation is missing btree:: and is required since it is not inside the class definition:
 void btree::destroy_tree(node * leaf)
 {
   if(leaf!=NULL)
   {
     destroy_tree(leaf->left);
     destroy_tree(leaf->right);
     delete leaf;
   }
}

A: The main problem I can see is that:
void destroy_tree(node *leaf)

should be:
void btree::destroy_tree(node *leaf)

Also there is no way to create a btree object.  You should maybe do this:
class btree
{
public:
    btree();
    ~btree();

    void destroy_tree();

private:
    void destroy_tree(node *leaf);
    node *root;
};


text:
Q: How to fetch data from past 2 week in SQL? I have a table with 6GB of data and it has past 6 years of records (few millions of rows), but I want to collect data from past 2 weeks.
How to fetch All column data from past 2 weeks in the table. There is any Query helps me to get those data or should I do partition, etc? Any help.

A: It sounds to me like a straight forward select query.
Select field1, field2, etc
from tablename
Where datefield > getdate() -14;

Substitute the fields you want to select and filter, and the tablename.
I would highly reccomend that you take some time to start reading about sql queries. W3 schools would be a good place to start


text:
Q: How to display two 1-m related CoreData entities in two NSTableViews using NSArray bindings I have an entity 'person' and a 1-m related entity 'visit' defined in CoreData. Now I want to display and modify their values in related tables using NSArray controllers with COCOA bindings on MacOS
My project is for MacOS and I'm using Xcode with Swift.
I have defined the data structure and Viewcontroller objects using the Xcode builder. The table for the 'person' is already working and I can add or delete persons. However I'm not able to find a way to bind the 'visit' table to the selected person. I tried several options, like connecting the content of the 'visit' array controller as recommended in Master-detail using bindings with TWO NSTableViews, but all ended up in compile time errors.
As I'm working with the visual Xcode builders, the is not much code for the moment. Here is what I did so far:
I have defined the two entity classes with the Xcode data model builder, then the two tables and array controllers with the storyboard interface builder. Then I bound the table views content to the respective array controllers and the columns to their own table view with the respective entity attribute. I also added + and - buttons to add some rows. So far everything worked fine. But the details ('visit') had no connection to any 'person'. Hence I deleted all entries in the 'visit' table and tried to bind the content of its array controller to the selected person.  That is where I get stuck.
Maybe I missed some initialization of the CoreData entities, but I have no clue how to proceed

A: I'm looking at my working macOS project which has two NSTableViews in Master-Detail.

*

*The .xib has two array controllers, one for the master and detail entities.  Let's call them MasterAC and DetailAC.  The Master and Detail table columns are bound to these array controllers.

*In the bindings for the DetailAC, the Content Array binding is bound to: MasterAC.selection.details, where details is the name of the master-to-detail relationship.

*In the bindings for both MasterAC and DetailAC, the Managed Object Context binding in both are bound to the same managed object context.

*In the array controllers, only these two bindings (Content Array and Managed Object Context) are bound.

If that does not fix it, I can poke around some more.  Cocoa Bindings with Core Data in macOS are beautiful once you get them working :))
Appendix.  If you've got an-ordered set
If the master-to-detail to-many relationship is an unordered set, and you are using the old school method of defining an index attribute on your Detail entity, you can define a detailsOrdered attribute in your Master class like this:
func detailsOrdered() -> [Any]? {
    return details().arraySorted(byKeyPath: "index")
}

and then bind to MasterAC.selection.detailsOrdered instead of MasterAC.selection.details.
The above implementation requires the following extension of Set:
extension Set<AnyHashable> {
    func arraySorted(byKeyPath keyPath: String?) -> [Any]? {
        let unorderedArray = Array(self)
        let sortDescriptor = NSSortDescriptor(key: keyPath, ascending: true)
        let orderedArray = (unorderedArray as NSArray).sortedArray(using: [sortDescriptor])
        return orderedArray
    }
}


text:
Q: List within single quotes I have a list which is in single quotes.
'[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]'

I receive this as an input parameter and I would like to assign this to a variable without the enclosing single quotes in python.
Could you please help?
The sample data received is close to something below..
 '[{"name":"emp_id","value":3232323},{"name":"dd_approval","value":"-paid -fulltime \"05/03/21 19:46\" \"05/04/21 19:46\" xyz@dmuil.com 3232323"}]'
 json.loads(this string)

Gives an error as given below
File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

A: What you have is not a list, but a JSON string representing a list of object, loading it in python will result in a list of dict
import json
a = '[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]'
content = json.loads(a)
print(content) # [{'Name': 'name1', 'value': 'value1'}, {'name': 'name2', 'value': 'value2'}]

A: You can use ast.literal_eval
import ast
x = ast.literal_eval('[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]')

If I preform type() on x I will be presented with <class 'list'>
Also everything inside this list turns to its desired form. The code below proves just that.
import ast
x = ast.literal_eval('[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]')
print(x[0])
print(type(x[0]))

output
{'Name': 'name1', 'value': 'value1'}
<class 'dict'>


text:
Q: How do I get my discord bot to forward its dms I saw the similar question when writing this but that was 2 years ago and when I tried it it didn't work. This is the code I was able to come up with
@client.event
async def on_message(message):
    if message.guild:
        return
    channel = client.get_channel(793586177328283660)
    await channel.send(message)

and whenever he gets dmed he says something in the channel but not what I wanted. He says this: <Message id=811285760304218153 channel=<DMChannel id=811037483255988274 recipient=<User id=760967899388051486 name='Ledip4001' discriminator='2308' bot=False>> type=<MessageType.default: 0> author=<User id=760967899388051486 name='Ledip4001' discriminator='2308' bot=False> flags=<MessageFlags value=0>>.
Probably something else when someone else dms him but I want him to say the right thing. Can you please help.

A: message is a Message object with a bunch of information about the message, not just the message itself. message.content is what contains the message itself. Use await channel.send(message.content) to achieve your desired result.


text:
Q: small flier with lualatex here is my code for a flier:
\documentclass[a4paper]{article}

\usepackage[verbose,vmargin=20mm,hmargin=20mm]{geometry}
\usepackage{fontsize,fix-cm}

\usepackage{graphicx}
\setkeys{Gin}{keepaspectratio}
\pagestyle{empty}
\changefontsize{24}
\setlength{\parindent}{0pt}

\renewcommand{\familydefault}{\sfdefault}

\begin{document}
\includegraphics[height=70mm]{example-image-10x16}
\hfill
\includegraphics[height=70mm]{example-image-10x16}

\begin{center}
    \begin{bfseries}
    {\LARGErrr My title}\\
    \end{bfseries}
\end{center}

\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \centering
    purpose of this flier (like "annual meeting", "anniversary"...)
\end{minipage}

\rule{\textwidth}{2pt}
\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \begin{itemize}
        \item ...anything like "no fees required"
        \item ..."transports for free" ...
    \end{itemize}
\end{minipage}
\rule{\textwidth}{2pt}

\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \centering
    "venue", "date", "time"???
\end{minipage}
\end{document}

This document is for an a5 size flier (2 pages as i will repeat the code for another language, like french of spanish...). Here with the article class I get warnings for annotation space if I reduce furthermore the margins:
Package fancyhdr Warning: \headheight is too small (12.0pt):
(fancyhdr)                Make it at least 88.9583pt, for example:
(fancyhdr)                \setlength{\headheight}{88.9583pt}.

I also have to add some code to avoid the page number. What document class would be more appropriate for such purpose?
The two images at the top, i'd like to have them in the header part. This way i wouldn't need to include them again for the second page. With fancyhdr in \fancyhead[L/R]{...} they are aligned with the first line "My title" below the top margin.
Also could anyone do something to make the list being vertically centered between the two rules? right now the is more space at the bottom of the list.
EDIT: i forgot to put the two horizontal rules in my mwe. Now it's done.

A: Put the definition of headheight in the geometry parameters, and use includehead so that it will adjust textheight.
\documentclass[a4paper]{article}

\usepackage[verbose,vmargin=20mm,hmargin=20mm,headheight=203pt,includehead]{geometry}
\usepackage{fontsize,fix-cm}

\usepackage{graphicx}
\setkeys{Gin}{keepaspectratio}
\pagestyle{empty}
\changefontsize{24}
\setlength{\parindent}{0pt}

\renewcommand{\familydefault}{\sfdefault}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\includegraphics[height=70mm]{example-image-10x16}}
\fancyhead[R]{\includegraphics[height=70mm]{example-image-10x16}}

\begin{document}

\begin{center}
    \begin{bfseries}
    {\LARGErrr My title}\\
    \end{bfseries}
\end{center}

\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \centering
    purpose of this flier (like "annual meeting", "anniversary"...)
\end{minipage}

\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \begin{itemize}
        \item ...anything like "no fees required"
        \item ..."transports for free" ...
    \end{itemize}
\end{minipage}

\begin{minipage}[t][.2\textheight][c]{\textwidth}
    \centering
    "venue", "date", "time"???
\end{minipage}
\end{document}


text:
Q: Como usar date table bootstrap Queria usar esse date table, para pesquisar bastante dados do banco. Eu até consegui, porém demora 12 segundos para carregar a página. Pois tem muitos dados cadastrados. Alguém tem um exemplo de como poderia fazer ?
Segue o código:
Front:

            LISTAR FROTA

                    CADASTRAR FROTA

                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas

                // Aqui eu coloquei o Laço de repetição
                <?php
                $read = new Read;
                $read->ExeRead('frota', 'ORDER BY id DESC');

                foreach ($read->getResult() as $v):
                   extract($v);

                ?>

                    $dadosaqui
                    $dadosaqui
                    $dadosaqui
                    $dadosaqui
                    $dadosaqui
                    $dadosaqui

                <?php
                endforeach;
                ?>

                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas
                        Nome das colunas

Js:
$(document).ready(function() {
    $('#example').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "js/scripts/recebe_frotas.php",
        "deferLoading": 57,
        "oLanguage": {
                    "sProcessing":   "Processando...",
                    "sLengthMenu":   "Mostrar _MENU_ registros",
                    "sZeroRecords":  "Não foram encontrados resultados",
                    "sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                    "sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
                    "sInfoFiltered": "",
                    "sInfoPostFix":  "",
                    "sSearch":       "Buscar:",
                    "sUrl":          "",
                    "oPaginate": {
                        "sFirst":    "Primeiro",
                        "sPrevious": "Anterior",
                        "sNext":     "Seguinte",
                        "sLast":     "Último"
                    }
                }
    });
} );

Arquivo que recebe o Js (recebe_frotas.php)

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simply to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'frota';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'id', 'dt' => 0 ),
    array( 'db' => 'seguradora_id',  'dt' => 1 ),
    array( 'db' => 'rastreador_id',   'dt' => 2 ),
    array( 'db' => 'placacavalo',     'dt' => 3 )
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'sistema_frota',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' ); // na documentação tem esse arquivo, mas não sei o que seria!

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

A: Galera, eu consegui arrumar o erro, eu simplesmente inclui o arquivo (ssp.class.php), que baixei aqui: https://github.com/DataTables/DataTables/blob/master/examples/server_side/scripts/ssp.class.php
E nos campos de do array, tem que ter a mesma quantidade das colunas da sua tabela:
Ficou assim:
$columns = array(
    array( 'db' => 'id', 'dt' => 0 ),
    array( 'db' => 'cliente_id', 'dt' => 1 ),
    array( 'db' => 'seguradora_id', 'dt' => 2 ),
    array( 'db' => 'rastreador_id', 'dt' => 3 ),
    array( 'db' => 'placacavalo', 'dt' => 4 ),
    array( 'db' => 'marca', 'dt' => 5 ),
    array( 'db' => 'modelo', 'dt' => 6 ),
    array( 'db' => 'data', 'dt' => 7 ),
    array( 'db' => 'chassi', 'dt' => 8 )
);
MAS AGORA A DÚVIDA É, COMO COLOCAR DOIS BOTÃO, DE EDITAR E EXCLUIR NO FINAL DA TABELA, SENDO QUE SE COLOCAR BOTÃO NO FINAL, A TABELA NÃO FUNCIONA :(


text:
Q: Import QML Components from Custom QML Library I have created a library to store custom QML components that I am making for an application. I am using Pyside6 with python. This is what the basic directory looks like:
library
|    |__CustomComponents
|       |__Components1
|          |__CustomComponent1.qml
|
|__test
   |__MainComponent
      |__main.py
      |__Main.qml

library and test are on the same level. I want to be able to access the CustomComponent1.qml file for use in the Main.qml, but how would I go about writing an import statement for that in Python? Also, to be able to import Components1 as a module, is the qmldir file all I need to have there? It would be neat if there is a command I can use to generate the files I need to make a module.
Edit: Possible to use QQuickView and QQmlApplicationEngine together?
view = QQuickView()
view.setResizeMode(QQuickView.SizeRootObjectToView);

newWidget = newWidget()
view.rootContext().setContextProperty("headerWidget", headerWidget)

qml_file = os.fspath(Path(__file__).resolve().parent / 'Main.qml')
view.setSource(QUrl.fromLocalFile(qml_file))
if view.status() == QQuickView.Error:
    sys.exit(-1)
view.show()

A: You have to use qmldir to indicate that there is a module in that folder and for it to be used it must be in the list of imports of the engine and for this you must use the addImportPath method.
├── library
│   └── CustomComponents
│       └── Components1
│           ├── CustomComponent1.qml
│           └── qmldir
└── test
    └── MainComponent
        ├── main.py
        └── main.qml

CustomComponent1.qml
import QtQuick

Rectangle{
    id: root
    width: 100
    height: 100
    color: "salmon"
}

qmldir
module Components1
CustomComponent1 CustomComponent1.qml

main.py
import os
from pathlib import Path
import sys

from PySide6.QtCore import QCoreApplication, Qt, QUrl
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine

CURRENT_DIRECTORY = Path(__file__).resolve().parent

LIBRARY_DIR = CURRENT_DIRECTORY.parents[1] / "library" / "CustomComponents"

def main():
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.addImportPath(os.fspath(LIBRARY_DIR))
    url = QUrl.fromLocalFile(os.fspath(CURRENT_DIRECTORY / "main.qml"))

    def handle_object_created(obj, obj_url):
        if obj is None and url == obj_url:
            QCoreApplication.exit(-1)

    engine.objectCreated.connect(
        handle_object_created, Qt.ConnectionType.QueuedConnection
    )

    engine.load(url)

    sys.exit(app.exec())

if __name__ == "__main__":
    main()

main.qml
import QtQuick
import QtQuick.Window

import Components1

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    CustomComponent1{

    }
}

QQuickView
In the case of QQuickView, it has an engine so you must use that one, so the changes are:
main.py
import os
from pathlib import Path
import sys

from PySide6.QtCore import QCoreApplication, Qt, QUrl
from PySide6.QtGui import QGuiApplication
from PySide6.QtQuick import QQuickView

CURRENT_DIRECTORY = Path(__file__).resolve().parent

LIBRARY_DIR = CURRENT_DIRECTORY.parents[1] / "library" / "CustomComponents"

def main():
    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.engine().addImportPath(os.fspath(LIBRARY_DIR))
    url = QUrl.fromLocalFile(os.fspath(CURRENT_DIRECTORY / "main.qml"))

    def handle_status_changed(status):
        if status == QQuickView.Error:
            QCoreApplication.exit(-1)

    view.statusChanged.connect(
        handle_status_changed, Qt.ConnectionType.QueuedConnection
    )

    view.setSource(url)
    view.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    main()

main.qml
import QtQuick

import Components1

Rectangle {
    width: 640
    height: 480

    CustomComponent1{

    }
}


text:
Q: How to prevent mmenu's default off-canvas menu display on large screens I'm using mmenu.js with Foundation 6.2 and want to prevent mmenu's off-canvas default menu display on large screen sizes. Foundation's visiblity classes are used to hide the off-canvas menu for large screens, where an on-canvas menu takes over. However, if the off-canvas menu is not closed prior to resizing the browser window to a large screen size, a blank space persists where the menu would be positioned. Is there a way to prevent the off-canvas API from displaying entirely at large screen sizes?

A: Found a solution that was helpful using window.matchMedia explained by Craig Butler at http://www.sitepoint.com/javascript-media-queries/. This causes the blank window space to close up (or rather slide close with the default mmenu setting) and the browser content to expand to full width at 1024px.
          $(document).ready(function() {            //Off canvas mmenu options
          $("#igreens").mmenu({

          navbar:{
                  title: ''
            }

            });
             var API = $("#igreens").data( "mmenu" );

            $("#nav-toggle").click(function() {
            API.open();

            });
                                                   // media query event handler
            if (matchMedia) {
                var mq = window.matchMedia("(min-width: 1024px)");
                mq.addListener(WidthChange);
                WidthChange(mq);
            }

            // media query change
            function WidthChange(mq) {
              if (mq.matches) {
              API.close();

              } else {                             // window width is less than 1024px
                mq.preventDefault();
              }
            }
         });


text:
Q: Issue with contact form (html and php): 405 not allowed I'm trying to make a very basic contact form using HTML and PHP. For some reason, however, when I click the "submit" button I get the error "405 Not Allowed". Why? How could I fix this? (I'm hosting my website on GitHub)
my HTML:
<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<body>

    <form action="send_form_email.php" method="POST">
            <input type="text" name="name" placeholder="Full Name">
            <input type="text" name="mail" placeholder="Your e-mail">
            <input type="text" name="subject" placeholder="Subject">
            <textarea name="message" placeholder="Message"></textarea>
            <button type="submit" name="submit">Send e-mail</button>
    </form>

</body>

</html>

my PHP:
<?php

if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];

$mailTo = "example@gmail.com";
$headers = "From: ".$mailFrom;
$txt = "You have received an e-mail from ".$name.".\n\n".$message;

mail($mailTo, $subject, $txt, $headers);
header("Location: index.php?mailsend");
}

(PS. I wrote "example@gmail.com" just because I wanted to keep my personal e-mail private on here.
PPS. I have been trying to make a very simple contact form (you write your name mail and message and the owner of the website receives it in the inbox) but none of my (desperate) attempts seems to work. Can anyone help me out?)

A: Github is a  hosting service for static web pages. PHP is not static.   Deploying PHP to GitHub Pages - is it possible?


text:
Q: Parse html using xpath Need get html from server and parse it using xpath (xpath is necessarily i can't using something else). My code :
TagNode tagNode = new HtmlCleaner().clean(html);
Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
XPath xpathObject = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpathObject.evaluate(xpathString, html, XPathConstants.NODESET);

It works good but function clean() take a lot of time (for a page can take > 30 s).
I found other solution - using Jsoup, so my new code is -
Document doc = Jsoup.parse(html);
W3CDom w3cDom = new W3CDom();
org.w3c.dom.Document w3cDoc = w3cDom.fromJsoup(doc);

XPath xpathObject = XPathFactory.newInstance().newXPath();
str = (String) xpathObject.evaluate(xpathString, w3cDoc, XPathConstants.STRING);

Now parse and convert to org.w3c.dom.Document take about 1s + evaluate 0.4s ~ 1.5 second. But this is very slow too.
How can I increase speed of processing more?

A: We use regex patterns over one string containing HTML.
This approach is more stable when HTML document occasionally has structure changes (after a page redesign, etc.)

A:
How can I increase speed of processing more?

Move away from DOM based parsers (memory intensive) and move towards an event based approach (SAX parsers).
https://en.wikipedia.org/wiki/Simple_API_for_XML
With a sax parser you basically implement a stack to extract the nodes of interest.


text:
Q: Java Threads How do I implement a ThreadPoolExecutor? What needs to be done to use it?

A: The API Specification for the ThreadPoolExecutor class has four constructors which can be used to create an instance of the ThreadPoolExecutor.
The Executors class also has methods such as newCachedThreadPool and newFixedThreadPool methods, but those are only listed as returning an ExecutorService, so it doesn't necessarily have to be a ThreadPoolExecutor.
For more general information on Executors and the Java concurrency package, the Lesson: Concurrency from The Java Tutorials has more information. In particular, the Executors and Thread Pools section may be of interest.

A: Executor is a interface.  Implementing it allows clients to pass you runnable tasks, which are then executed in a particular manner.  ThreadPoolExecutor is one class implementing that interface (and ExecutorService).  It uses a thread pool so you can have multiple threads executing jobs without needing a new thread for every job.  ThreadPoolExecutor can be subclassed, or you can just instantiate it with one of the public constructors.
Other methods, such as Executors.newFixedThreadPool, return a thread pool of some kind though not (necessarily) a ThreadPoolExecutor.

A: Java Concurrency in Practice - Addison Wesley ISBN:0321349601
I used this book to learn about Executors. I has a bunch of good examples you can steal.

A: I suggest you start with the tutorial for this class http://java.sun.com/docs/books/tutorial/essential/concurrency/exinter.html


text:
Q: pamr.cv in R Warning: a class contains only 1 sample I want to cross-validate the nearest shurnken centroid classifier in R. But every time I'm running the pamr.cv function it gives a warning that a class contains only 1 sample.
Here is a link to a little part of my file in excel http://gyazo.com/f6aab67674ffbac45d915cbb947c85c1.
I import the file via pamr.from.excel function. here is my code:
gen.data <- pamr.from.excel("C:\\~data_groep_1-4\\Core_probesets-gene_summary3.txt", 36, sample.labels=TRUE)
mytrain <- pamr.train(gen.data)
mycv <- pamr.cv(mytrain, gen.data)
So could anyone tell me what this warning is and how to avoid it?


text:
Q: How to redirect user after submitting form with React I'm learning React. I have a login page with a form ("/login") which after submitting successfully I wanna redirect the user to the root path ("/") of the domain. I'm using Redux that seems to work fine. My code is:
const handleSubmit = (e) => {

        e.preventDefault()

        setSubmitBtn(true)

        setTimeout(async (e) => {

            const { data } = await axios.post( axiosURL + '/login', inputs)

            dispatch({ type: 'LOGIN' })

            history.push("/")

            setReturnMessage(data.message)

            setSubmitBtn(false)

        }, 1000)
    }

The problem is the history.push("/") that's not working and it gives the following error message:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in Login (created by Context.Consumer)
    in Route (at routes.js:36)

Does anyone know how to fix it? Thanks!!

A: The thing is that you are doing this after history.push("/"):
setReturnMessage(data.message)
setSubmitBtn(false)

Comment those lines and the error should disappear.
You can also do this:
setReturnMessage(data.message)
setSubmitBtn(false)
history.push("/")  <--- as the last line of code


text:
Q: Como ativar e desativar plugins conforme o Workspace no Eclipse Luna Eu uso o Eclipse para praticamente tudo em meu ambiente de trabalho, sei que muitos irão criticar tal escolha, mas esta não é a questão, tenho diversos Workspace criados, um para programar em C/C++ para ARM outro para C/C++ genérico, outro C/C++ para AVR, mais um para programar em PHP e outro para programar em Java-EE e ainda mais um para Android.
Até já tentei manter versões do Eclipse para cada workspace, mas chega uma hora que atualizar tudo me cansa, e sempre fica mais bagunçado. Fora a perda de espaço e tempo de download.
Estou tendo sucesso razoável em usar o Eclipse Luna SR2 (4.4.2) com diversos plugins para cada linguagem citada funcionando com sucesso. Porém uma coisa me chateia, a quantidade de tipos de projetos que posso usar, e as vezes um plugin do JBoss me incomoda quando estou usando o Workspace para programar para ARM, sem dúvida não vou precisar dele neste momento.
Como faço então para desabilitar um ou outro plugin conforme o Workspace que estou usando, o Eclipse Luna já tem este recurso?


text:
Q: How to target a component in svelte with css? How would I do something like this:

<Nested />

i.e. How do I apply a style to a component from its parent?

A: using :global(*) is the simplest solution.
No need to specify a class in the child if you want to style all immediate children for example
In the parent component:

   <Nested />

Maybe you will found something but this one works.

A: You need to pass props to the parent component with export let, then tie those props to class or style in the child component.
You can either put a style tag on the element in the child you want to style dynamically and use a variable you export for the parent to determine the value of a style directly, then assign the color on the tag like this:

<Nested color="green"/>

    Yes this will work

Upside here is flexibility if you only have one or two styles to adjust, downside is that you won't be able to adjust multiple CSS properties from a single prop.
or
You can still use the :global selector but just add a specific ref to the element being styled in the child like so:

<Nested ref="green"/>

    Yes this will work also

This ensures global only affects the exact ref element inside the child it's intended for and not any other classes or native elements. You can see it in action at this REPL link

A: The only way I can think of is with an additional div element.
App.svelte

    <Nested />

Nested.svelte

    Colored based on parent style

Multiple Nested elements
You could even allow the class name to be dynamic and allow for different colors if you use multiple Nested components. Here's a link to a working example.

A: You could use inline styles and $$props...

<Nested style="background: green; color: white; padding: 10px; text-align: center; font-weight: bold" />

    Hello World

REPL

A: The way I do it is like this:

This generates css selectors like section.svelte-15ht3eh img that only affects the children img tag of the section tag.
No classes or tricks involved there.


text:
Q: Angular.js - 403 Forbidden access is denied I know this might be very general but I need some help.
I have a job interview and they have asked me to clone a project and learn how it works - Repository HUBTaxi-Server. I've never worked in something this large and im quite stuck.
I've done everything as explained in the repository but still can't make it work.
I've reached the manager-loggin of the app and is giving me a 403 forbidden access. Printed Screen of the error i'm getting
I guess has something to do with the Mongo database. I have little experience with this.

A: 403 means you are not allowed to see the page. The readme on github says the login and the password are both 'admin' Try that and see if you can login.


text:
Q: how to make specific application window as active window using autoIt script? Many applications are running in my system. I need to bring specific application window as an active window. From my knowledge this will be done by shell script that's why i am choosing AutoIt script.

A: Try to have a look at the helpfile.
WinActivate, Winexists ...
#include<Array.au3>
$a = ProcessGetId('firefox.exe')
For $i = 1 To UBound($a) - 1
    ConsoleWrite(ProcessGetWindow($a[$i]) & @CRLF)
Next

Func ProcessGetWindow($PId)
    If IsNumber($PId) = 0 Or ProcessExists(ProcessGetName($PId)) = 0 Then
        SetError(1)
    Else
        Local $WinList = WinList()
        Local $i = 1
        Local $WindowTitle = ""
        While $i <= $WinList[0][0] And $WindowTitle = ""
            If WinGetProcess($WinList[$i][0], "") = $PId Then
                $WindowTitle = $WinList[$i][0]
            Else
                $i += 1
            EndIf
        WEnd
        Return $WindowTitle
    EndIf
EndFunc   ;==>ProcessGetWindow

Func ProcessGetId($Process)
    If IsString($Process) = 0 Then
        SetError(2)
    ElseIf ProcessExists($Process) = 0 Then
        SetError(1)
    Else
        Local $PList = ProcessList($Process)
        Local $i
        Local $PId[$PList[0][0] + 1]
        $PId[0] = $PList[0][0]
        For $i = 1 To $PList[0][0]
            $PId[$i] = $PList[$i][1]
        Next
        Return $PId
    EndIf
EndFunc   ;==>ProcessGetId

Func ProcessGetName($PId)
    If IsNumber($PId) = 0 Then
        SetError(2)
    ElseIf $PId > 9999 Then
        SetError(1)
    Else
        Local $PList = ProcessList()
        Local $i = 1
        Local $ProcessName = ""

        While $i <= $PList[0][0] And $ProcessName = ""
            If $PList[$i][1] = $PId Then
                $ProcessName = $PList[$i][0]
            Else
                $i = $i + 1
            EndIf
        WEnd
        Return $ProcessName
    EndIf
EndFunc   ;==>ProcessGetName


text:
Q: Creating WPF BitmapImage from MemoryStream png, gif I am having some trouble creating a BitmapImage from a MemoryStream from png and gif bytes obtained from a web request. The bytes seem to be downloaded fine and the BitmapImage object is created without issue however the image is not actually rendering on my UI. The problem only occurs when the downloaded image is of type png or gif (works fine for jpeg).
Here is code that demonstrates the problem:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
    Byte[] buffer = new Byte[webResponse.ContentLength];
    stream.Read(buffer, 0, buffer.Length);

    var byteStream = new System.IO.MemoryStream(buffer);

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.DecodePixelWidth = 30;
    bi.StreamSource = byteStream;
    bi.EndInit();

    byteStream.Close();
    stream.Close();

    return bi;
}

To test that the web request was correctly obtaining the bytes I tried the following which saves the bytes to a file on disk and then loads the image using a UriSource rather than a StreamSource and it works for all image types:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
    Byte[] buffer = new Byte[webResponse.ContentLength];
    stream.Read(buffer, 0, buffer.Length);

    string fName = "c:\\" + ((Uri)value).Segments.Last();
    System.IO.File.WriteAllBytes(fName, buffer);

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.DecodePixelWidth = 30;
    bi.UriSource = new Uri(fName);
    bi.EndInit();

    stream.Close();

    return bi;
}

Anyone got any light to shine?

A: Add bi.CacheOption = BitmapCacheOption.OnLoad directly after your .BeginInit():
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
...

Without this, BitmapImage uses lazy initialization by default and stream will be closed by then. In first example you try to read image from possibly garbage-collected closed or even disposed MemoryStream. Second example uses file, which is still available.
Also, don't write
var byteStream = new System.IO.MemoryStream(buffer);

better
using (MemoryStream byteStream = new MemoryStream(buffer))
{
   ...
}

A: I'm using this code:
public static BitmapImage GetBitmapImage(byte[] imageBytes)
{
   var bitmapImage = new BitmapImage();
   bitmapImage.BeginInit();
   bitmapImage.StreamSource = new MemoryStream(imageBytes);
   bitmapImage.EndInit();
   return bitmapImage;
}

May be you should delete this line:
bi.DecodePixelWidth = 30;


text:
Q: How can I synchronize two JTextFields in Java swing? I'm trying to synchronize two JTextFields. If I write in one JTextField, I want to write the same text in other JTextField simultaneously.
I'm not sure what event use for this requirement.
My example code:
private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    txt_codigoEstablecimiento.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim());
            System.out.println(txt_codEstabQVT);
        }
    });
}

My example code:
 private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: txt_codigoEstablecimiento.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim()); System.out.println(txt_codEstabQVT); } }); }

A:
If I write in one JTextField, I want to write the same text in other JTextField simultaneously.

Share the "model" between the two components. In the case of a JTextField the model is the Document:
JTextField textField1 = new JTextField(...);
JTextField textField2 = new JTextField(...);
textField2.setDocument( textField1.getDocument() );

There is no need for any listeners.


text:
Q: Counter that will remember its value I have a task to operate on complex number. Each number consists of double r = real part, double i = imaginary part and String name. Name must be set within constructor, so I've created int counter, then I'm sending its value to setNextName function and get name letter back. Unfortunately incrementing this 'counter' value works only within costructor and then it is once again set to 0. How to deal with that?Some constant value? And second problem is that I also need to provide setNextNames(char c) function that will change the counter current value.
The code :
public class Imaginary {

private double re;
private double im;
private String real;
private String imaginary;
private String name;
private int counter=0;

public Imaginary(double r, double u){
    re = r;
    im = u;
    name = this.setNextName(counter);
    counter++;
}

public static String setNextName(int c){

    String nameTab[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
                        "O","P","Q","R","S","T","U","W","V","X","Y","Z"};

    String setName = nameTab[c];
    System.out.println("c: "+c);
    return setName;
}

public static String setNextName(char c){

//
//don't know how to deal with this part
//
}

A: It's hard to tell what you're doing, but I suspect this will solve your immediate problem:
private static int counter = 0;

A: You should make counter static.
You should also make nameTab a private static field, then in setNextName(), you can iterate through it to find the name corresponding to the given character, and get its index. (in the plain ASCII world, of course one could simply calculate the index by subtracting the numeric value of 'A' from the given character, but I am not quite sure how it would work out with Java, in Unicode, with crazy inputs - iteration is on the safe side.)

A: In OO languages there are typically two types of variables that go into a class:

*

*instance variables that are unique to each instance

*class variables that are shared by all instances of the class

Given a class like:
public class Person
{
    // class variable
    private static int numberOfEyes;

    // instance variable
    private String name;

    // other code goes here
}

If you were to do something like:
Person a = new Person("Jane Doe");
Person b = new Person("John Doe");

and then do something like:
a.setName("Jane Foe");

the name for Person "a" would change, but the one for Person "b" would stay the same.
If you woke up one morning and decided you wanted 3 eyes:
Person.setNumberOfEyes(3);

then Person "a" and Person "b" and every other Person instance out there would suddenly have 3 eyes as well.
You want to put "static" in your counter declaration.

A: is your code being used by multiple threads than i would suggest that making counter static won't solve ur problem.
you need to take extra care by implementing thread synchronization use lock keyword as shown below.
private static readonly obj = new Object();
private static int counter =0;

public Imaginary(double r, double u)
{
    re = r;
    im = u;
    lock(obj)
    {
        name = this.setNextName(counter);
        counter++;
    }
}

this will ensure thread safety also while incrementing your counter (there are another ways also to provide thread security but this one is having least code).

A: Because the field counter is not static, every object has its own counter.


text:
Q: pyspark.sql.functions - count to consider null values: I am trying to get the pyspark.sql.functions.count() function or the pyspark.sql.functions.count_distinct() function to consider null values when counting the number of distinct elements within a column.
Let me give the following reproducible example, for which I need to create a dataset:
# Dataframe Creation
df = spark.createDataFrame([(1,"arun","engineering",20000),\
                            (2,"manoj","finance",25000),\
                            (3,None,"accounts",None),\
                            (4,"vikram",None,None)],\
                           ["id","name","dept","salary"])

The resulting dataframe looks as follows:
+---+------+-----------+------+
| id|  name|       dept|salary|
+---+------+-----------+------+
|  1|  arun|engineering| 20000|
|  2| manoj|    finance| 25000|
|  3|  null|   accounts|  null|
|  4|vikram|       null|  null|
+---+------+-----------+------+

Now if I run the following code to count the number of distinct values in each column:
import pyspark.sql.functions as func
df.agg(func.count("id").alias("n_ids"),\
       func.count("name").alias("n_names"),\
       func.count("dept"),\
       func.count("salary"))\
  .show()

I get the following output:
+-----+-------+-----------+-------------+
|n_ids|n_names|count(dept)|count(salary)|
+-----+-------+-----------+-------------+
|    4|      3|          3|            2|
+-----+-------+-----------+-------------+

I get the same output if I substitute func.count() for func.count_distinct() in the above snippet.
From my research, this seems to be related to the fact that count_distinct() works in the same way as HIVE count(DISTINCT expr[, expr])

count(DISTINCT expr[, expr]) - Returns the number of rows for which
the supplied expression(s) are unique and non-NULL.

I would like the null values to be considered in the count of distinct values, resulting in the following output:
+-----+-------+-----------+-------------+
|n_ids|n_names|count(dept)|count(salary)|
+-----+-------+-----------+-------------+
|    4|      4|          4|            3|
+-----+-------+-----------+-------------+

This is in fact the output we get if we use the DataFrame API functions distinct() and count() applied to one column, because distinct() coniders null values by default.
df.select("salary").distinct().count() # Returns 3, taking the null value into account.

QUESTION:
How can I use the pyspark.sql.functions.count() or pyspark.sql.functions.count_distinct() to consider the null values when determining the number of distinct records in a column?
Thanks a lot for your help!

A: You can create a function of your own.
basically, count the distinct values and then count the non-null rows. if the non-null rows are not equal to the number of rows in the dataframe it means at least one row is null, in this case add +1 for the null value(s) in the column.
def count_distinct_with_nulls(c):
    distinct_values = func.count_distinct(c)
    null_rows = func.sum(func.when(func.col(c).isNull(), 1).otherwise(0))

    return func.when(
        null_rows == 0,
        distinct_values
    ).otherwise(distinct_values + 1)

Running it in a select or agg clause will work just fine.
df.select(*[count_distinct_with_nulls(c).alias(c) for c in df.columns]).show()

+---+----+----+------+
| id|name|dept|salary|
+---+----+----+------+
|  4|   4|   4|     3|
+---+----+----+------+

An additional solution, not sure if it's best practice but you can fill all na columns with values and run the normal count_distinct function.
e.g: df.fillna(-1).fillna("-1") will fill -1 in numeric columns and "-1" in string columns.


text:
Q: Merge CPT Taxonomy and Post Taxonomy in $query->set I'm merging blog posts and a custom post type into a single query and displaying them on my feed as well, here's the code:
function add_query_news_projects( $query ) {
    if ( is_home() && $query->is_main_query() || is_feed() )
        $query->set( 'post_type', array( 'post', 'portfolio' ) );
    return $query;
}
add_filter( 'pre_get_posts', 'add_query_news_projects' );

The issue I'm having is that blog posts have a taxonomy of "category" and the CPT has a taxonomy of "portfolio_category". I'd like to display the CPT category AS a category in my template AND in my RSS feed. Is there are means to rewrite the results of the $query with "porfolio_category" being "category" for those posts?


text:
Q: How to swap columns in a datagridview My intent is to allow the user to drag and drop the columns.
In form 1, there is button and when the respective button is clocked, form 2 opens with the datagridview.
Swap the column 1 with column 2 by using the mouse.
Now when you close the form2 and gain click on the button on form 1, form 2 should appear with the changed column.
What I tried?

*

*I tried to save the column index of the column which is moved and index of the columns with which it is swapped in columnsorder.

*I am not sure ow to carry the changed column details from child form to parent form and again parent form to child after clicking the button.

Public Class Form2
    Public ctlDataGridDirect As System.Windows.Forms.DataGridView

    Public columnOrder As New List(Of ColumnOrderItem)
    Public ColumnChanged As Boolean = False

    Public NotInheritable Class ColumnOrderItem
        Public Property DisplayIndex As Integer
        Public Property ColumnIndex As Integer
    End Class

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ctlDataGridDirect = Me.ctlDataGrid
        ctlDataGridDirect.ClipboardCopyMode = Windows.Forms.DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
        With ctlDataGrid
            .AllowUserToAddRows = False
            .RowHeadersVisible = False
        End With
        ctlDataGrid.Rows.Add()
        ctlDataGrid.Rows(0).Cells("Column1").Value = Trim(0)
        ctlDataGrid.Rows(0).Cells("Column2").Value = Trim(1)
        ctlDataGrid.Rows(0).Cells("Column3").Value = Trim(2)
        ctlDataGrid.Rows(0).Cells("Column4").Value = Trim(3)
        If ColumnChanged = True Then
            For i = 0 To columnOrder.Count - 1

            Next

        End If

    End Sub

    Private Sub ctlDataGrid_ColumnDisplayIndexChanged(sender As Object, e As DataGridViewColumnEventArgs) Handles ctlDataGrid.ColumnDisplayIndexChanged
        ColumnChanged = True

    End Sub

    Private Sub SaveColumnOrder(Datagridview As DataGridView)

        Dim columns As DataGridViewColumnCollection = ctlDataGrid.Columns
        For i = 0 To columns.Count - 1
            columnOrder.Add(New ColumnOrderItem With {.ColumnIndex = i, .DisplayIndex = columns(i).DisplayIndex})
        Next

    End Sub

    Private Sub Form2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed

        SaveColumnOrder(ctlDataGrid)

    End Sub
End Class

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Form2.Show()
    End Sub
End Class

A: Workaround is...

*

*Store the order of the column in settings. Example: 0123546

*write a routine which reorders datagrid columns as per settings data stored

*update the settings data every time you swap column..


text:
Q: Why can't I place downloaded rooms on to the lot? I downloaded some rooms from the Community. When I go to place them in the lot, they just don't show up. There's no indication as to why this is happening. I have sufficient funds and there's no error message. What would be causing this?
Example rooms that I can't place are the Hemlock Grove Landing by the user hmsdrco2012, Elenor Rigby Kitchen by MorganaLaFata, the Ocean Bedroom by MorganaLaFata - the list goes on, really. There's no indication as to why they can't be placed, either when placing them or when downloading them - I select the room and try to click to place it and nothing happens.
This also appears to be fairly common. In addition to my post on the EA support forums, I found two other posts, without a solution as well - here and here.

A: I've read another post and I think the problem is that you should favorite the rooms instead of putting them into your library. If you have more than 28 rooms in your library it appears that you can't place them. I can't really explain why though


text:
Q: Symfony doctrine determine foreign Alias List is empty In Symfony 1.4, Doctrine I have this snippet from schema.yml
Attendance:
  columns:
    id: { type: integer(4), primary: true, autoincrement: true }
    user_id: { type: integer(4) }

  relations:
    JoomlaUser: { class: JosUser, local: user_id, foreignAlias: AttendanceList }

and
JosUser:
  tableName: jos_users
  columns:
    id: { type: integer(4), primary: true, autoincrement: true }
  relations:
    AttendanceList: { class: Attendance, local: id, foreign: user_id }

What is the most efficient way to determine from JosUser that there are no Attendance records. I tried model/doctrine/JosUser.class.php
count($this->getAttendanceList())

but this returns a Doctrine Record with all fields empty but user_id

A: Schema :
JosUser:
    tableName: jos_users
    columns:
        id: { type: integer(4), primary: true, autoincrement: true }
    relations:
    AttendanceList: { type: many, class: Attendance, local: id, foreign: user_id }

With type: many, getAttendanceList() should return a Doctrine_Collection (see the JosUser base class in lib/model/doctrine/base/BaseJosUser.class.php), then you can use
$this->getAttendanceList()->count()


text:
Q: How do I implement task prioritization using an ExecutorService in Java 5? I am implementing a thread pooling mechanism in which I'd like to execute tasks of varying priorities.  I'd like to have a nice mechanism whereby I can submit a high priority task to the service and have it be scheduled before other tasks.  The priority of the task is an intrinsic property of the task itself (whether I express that task as a Callable or a Runnable is not important to me).
Now, superficially it looks like I could use a PriorityBlockingQueue as the task queue in my ThreadPoolExecutor, but that queue contains Runnable objects, which may or may not be the Runnable tasks I've submitted to it.  Moreover, if I've submitted Callable tasks, it's not clear how this would ever map.
Is there a way to do this?  I'd really rather not roll my own for this, since I'm far more likely to get it wrong that way.
(An aside; yes, I'm aware of the possibility of starvation for lower-priority jobs in something like this.  Extra points (?!) for solutions that have a reasonable guarantee of fairness)

A: At first blush it would seem you could define an interface for your tasks that extends Runnable or Callable<T> and Comparable. Then wrap a ThreadPoolExecutor with a PriorityBlockingQueue as the queue, and only accept tasks that implement your interface.
Taking your comment into account, it looks like one option is to extend ThreadPoolExecutor, and override the submit() methods. Refer to AbstractExecutorService to see what the default ones look like; all they do is wrap the Runnable or Callable in a FutureTask and execute() it. I'd probably do this by writing a wrapper class that implements ExecutorService and delegates to an anonymous inner ThreadPoolExecutor. Wrap them in something that has your priority, so that your Comparator can get at it.

A: You can use these helper classes:
public class PriorityFuture<T> implements RunnableFuture<T> {

    private RunnableFuture<T> src;
    private int priority;

    public PriorityFuture(RunnableFuture<T> other, int priority) {
        this.src = other;
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return src.cancel(mayInterruptIfRunning);
    }

    public boolean isCancelled() {
        return src.isCancelled();
    }

    public boolean isDone() {
        return src.isDone();
    }

    public T get() throws InterruptedException, ExecutionException {
        return src.get();
    }

    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return src.get(timeout, unit);
    }

    public void run() {
        src.run();
    }

    public static Comparator<Runnable> COMP = new Comparator<Runnable>() {
        public int compare(Runnable o1, Runnable o2) {
            if (o1 == null && o2 == null)
                return 0;
            else if (o1 == null)
                return -1;
            else if (o2 == null)
                return 1;
            else {
                int p1 = ((PriorityFuture<?>) o1).getPriority();
                int p2 = ((PriorityFuture<?>) o2).getPriority();

                return p1 > p2 ? 1 : (p1 == p2 ? 0 : -1);
            }
        }
    };
}

AND
public interface PriorityCallable<T> extends Callable<T> {

    int getPriority();

}

AND this helper method:
public static ThreadPoolExecutor getPriorityExecutor(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
            new PriorityBlockingQueue<Runnable>(10, PriorityFuture.COMP)) {

        protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
            RunnableFuture<T> newTaskFor = super.newTaskFor(callable);
            return new PriorityFuture<T>(newTaskFor, ((PriorityCallable<T>) callable).getPriority());
        }
    };
}

AND then use it like this:
class LenthyJob implements PriorityCallable<Long> {
    private int priority;

    public LenthyJob(int priority) {
        this.priority = priority;
    }

    public Long call() throws Exception {
        System.out.println("Executing: " + priority);
        long num = 1000000;
        for (int i = 0; i < 1000000; i++) {
            num *= Math.random() * 1000;
            num /= Math.random() * 1000;
            if (num == 0)
                num = 1000000;
        }
        return num;
    }

    public int getPriority() {
        return priority;
    }
}

public class TestPQ {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolExecutor exec = getPriorityExecutor(2);

        for (int i = 0; i < 20; i++) {
            int priority = (int) (Math.random() * 100);
            System.out.println("Scheduling: " + priority);
            LenthyJob job = new LenthyJob(priority);
            exec.submit(job);
        }
    }
}

A: I will try to explain this problem with a fully functional code. But before diving into the code I would like to explain about PriorityBlockingQueue
PriorityBlockingQueue : PriorityBlockingQueue is an implementation of BlockingQueue. It accepts the tasks along with their priority and submits the task with the highest priority for execution first. If any two tasks have same priority, then we need to provide some custom logic to decide which task goes first.
Now lets get into the code straightaway.
Driver class : This class creates an executor which accepts tasks and later submits them for execution. Here we create two tasks one with LOW priority and the other with HIGH priority. Here we tell the executor to run a MAX  of 1 threads and use the PriorityBlockingQueue.
     public static void main(String[] args) {

       /*
       Minimum number of threads that must be running : 0
       Maximium number of threads that can be created : 1
       If a thread is idle, then the minimum time to keep it alive : 1000
       Which queue to use : PriorityBlockingQueue
       */
    PriorityBlockingQueue queue = new PriorityBlockingQueue();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(0,1,
        1000, TimeUnit.MILLISECONDS,queue);

    MyTask task = new MyTask(Priority.LOW,"Low");
    executor.execute(new MyFutureTask(task));
    task = new MyTask(Priority.HIGH,"High");
    executor.execute(new MyFutureTask(task));
    task = new MyTask(Priority.MEDIUM,"Medium");
    executor.execute(new MyFutureTask(task));

}

MyTask class : MyTask implements Runnable and accepts priority as an argument in the constructor. When this task runs, it prints a message and then puts the thread to sleep for 1 second.
   public class MyTask implements Runnable {

  public int getPriority() {
    return priority.getValue();
  }

  private Priority priority;

  public String getName() {
    return name;
  }

  private String name;

  public MyTask(Priority priority,String name){
    this.priority = priority;
    this.name = name;
  }

  @Override
  public void run() {
    System.out.println("The following Runnable is getting executed "+getName());
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}

MyFutureTask class : Since we are using PriorityBlocingQueue for holding our tasks, our tasks must be wrapped inside FutureTask and our implementation of FutureTask must implement Comparable interface. The Comparable interface compares the priority of 2 different tasks and submits the task with the highest priority for execution.
 public class MyFutureTask extends FutureTask<MyFutureTask>
      implements Comparable<MyFutureTask> {

    private  MyTask task = null;

    public  MyFutureTask(MyTask task){
      super(task,null);
      this.task = task;
    }

    @Override
    public int compareTo(MyFutureTask another) {
      return task.getPriority() - another.task.getPriority();
    }
  }

Priority class : Self explanatory Priority class.
public enum Priority {

  HIGHEST(0),
  HIGH(1),
  MEDIUM(2),
  LOW(3),
  LOWEST(4);

  int value;

  Priority(int val) {
    this.value = val;
  }

  public int getValue(){
    return value;
  }

}

Now when we run this example, we get the following output
The following Runnable is getting executed High
The following Runnable is getting executed Medium
The following Runnable is getting executed Low

Even though we submitted the LOW priority first, but HIGH priority task later, but since we are using a PriorityBlockingQueue, any task with a higher priority will execute first.

A: I have solved this problem in a reasonable fashion, and I'll describe it below for future reference to myself and anyone else who runs into this problem with the Java Concurrent libraries.
Using a PriorityBlockingQueue as the means for holding onto tasks for later execution is indeed a movement in the correct direction. The problem is that the PriorityBlockingQueue must be generically instantiated to contain Runnable instances, and it is impossible to call compareTo (or similiar) on a Runnable interface.
Onto solving the problem. When creating the Executor, it must be given a PriorityBlockingQueue. The queue should further be given a custom Comparator to do proper in place sorting:
new PriorityBlockingQueue<Runnable>(size, new CustomTaskComparator());

Now, a peek at CustomTaskComparator:
public class CustomTaskComparator implements Comparator<MyType> {

    @Override
    public int compare(MyType first, MyType second) {
         return comparison;
    }

}

Everything looking pretty straight forward up to this point. It gets a bit sticky here. Our next problem is to deal with the creation of FutureTasks from the Executor. In the Executor, we must override newTaskFor as so:
@Override
protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
    //Override the default FutureTask creation and retrofit it with
    //a custom task. This is done so that prioritization can be accomplished.
    return new CustomFutureTask(c);
}

Where c is the Callable task that we're trying to execute. Now, let's have a peek at CustomFutureTask:
public class CustomFutureTask extends FutureTask {

    private CustomTask task;

    public CustomFutureTask(Callable callable) {
        super(callable);
        this.task = (CustomTask) callable;
    }

    public CustomTask getTask() {
        return task;
    }

}

Notice the getTask method. We're gonna use that later to grab the original task out of this CustomFutureTask that we've created.
And finally, let's modify the original task that we were trying to execute:
public class CustomTask implements Callable<MyType>, Comparable<CustomTask> {

    private final MyType myType;

    public CustomTask(MyType myType) {
        this.myType = myType;
    }

    @Override
    public MyType call() {
        //Do some things, return something for FutureTask implementation of `call`.
        return myType;
    }

    @Override
    public int compareTo(MyType task2) {
        return new CustomTaskComparator().compare(this.myType, task2.myType);
    }

}

You can see that we implement Comparable in the task to delegate to the actual Comparator for MyType.
And there you have it, customized prioritization for an Executor using the Java libraries! It takes some bit of bending, but it's the cleanest that I've been able to come up with. I hope this is helpful to someone!

A: My solution preserves submition order of tasks for same priorities. It's an improvement of this answer
Task execution order is based on:

*

*Priority

*Submit order (within same priority)

Tester class:
public class Main {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService executorService = PriorityExecutors.newFixedThreadPool(1);

        //Priority=0
        executorService.submit(newCallable("A1", 200));     //Defaults to priority=0
        executorService.execute(newRunnable("A2", 200));    //Defaults to priority=0
        executorService.submit(PriorityCallable.of(newCallable("A3", 200), 0));
        executorService.submit(PriorityRunnable.of(newRunnable("A4", 200), 0));
        executorService.execute(PriorityRunnable.of(newRunnable("A5", 200), 0));
        executorService.submit(PriorityRunnable.of(newRunnable("A6", 200), 0));
        executorService.execute(PriorityRunnable.of(newRunnable("A7", 200), 0));
        executorService.execute(PriorityRunnable.of(newRunnable("A8", 200), 0));

        //Priority=1
        executorService.submit(PriorityRunnable.of(newRunnable("B1", 200), 1));
        executorService.submit(PriorityRunnable.of(newRunnable("B2", 200), 1));
        executorService.submit(PriorityCallable.of(newCallable("B3", 200), 1));
        executorService.execute(PriorityRunnable.of(newRunnable("B4", 200), 1));
        executorService.submit(PriorityRunnable.of(newRunnable("B5", 200), 1));

        executorService.shutdown();

    }

    private static Runnable newRunnable(String name, int delay) {
        return new Runnable() {
            @Override
            public void run() {
                System.out.println(name);
                sleep(delay);
            }
        };
    }

    private static Callable<Integer> newCallable(String name, int delay) {
        return new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(name);
                sleep(delay);
                return 10;
            }
        };
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

}

Result:

A1 B1 B2 B3 B4 B5 A2 A3 A4 A5 A6 A7 A8
First task is A1 because there were no higher priority in the queue when it was inserted. B tasks are 1 priority so executed earlier, A tasks are 0 priority so executed later, but execution order is follows submition order: B1, B2, B3, ... A2, A3, A4 ...

The solution:
public class PriorityExecutors {

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new PriorityExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS);
    }

    private static class PriorityExecutor extends ThreadPoolExecutor {
        private static final int DEFAULT_PRIORITY = 0;
        private static AtomicLong instanceCounter = new AtomicLong();

        @SuppressWarnings({"unchecked"})
        public PriorityExecutor(int corePoolSize, int maximumPoolSize,
                long keepAliveTime, TimeUnit unit) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, (BlockingQueue) new PriorityBlockingQueue<ComparableTask>(10,
                    ComparableTask.comparatorByPriorityAndSequentialOrder()));
        }

        @Override
        public void execute(Runnable command) {
            // If this is ugly then delegator pattern needed
            if (command instanceof ComparableTask) //Already wrapped
                super.execute(command);
            else {
                super.execute(newComparableRunnableFor(command));
            }
        }

        private Runnable newComparableRunnableFor(Runnable runnable) {
            return new ComparableRunnable(ensurePriorityRunnable(runnable));
        }

        @Override
        protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
            return new ComparableFutureTask<>(ensurePriorityCallable(callable));
        }

        @Override
        protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
            return new ComparableFutureTask<>(ensurePriorityRunnable(runnable), value);
        }

        private <T> PriorityCallable<T> ensurePriorityCallable(Callable<T> callable) {
            return (callable instanceof PriorityCallable) ? (PriorityCallable<T>) callable
                    : PriorityCallable.of(callable, DEFAULT_PRIORITY);
        }

        private PriorityRunnable ensurePriorityRunnable(Runnable runnable) {
            return (runnable instanceof PriorityRunnable) ? (PriorityRunnable) runnable
                    : PriorityRunnable.of(runnable, DEFAULT_PRIORITY);
        }

        private class ComparableFutureTask<T> extends FutureTask<T> implements ComparableTask {
            private Long sequentialOrder = instanceCounter.getAndIncrement();
            private HasPriority hasPriority;

            public ComparableFutureTask(PriorityCallable<T> priorityCallable) {
                super(priorityCallable);
                this.hasPriority = priorityCallable;
            }

            public ComparableFutureTask(PriorityRunnable priorityRunnable, T result) {
                super(priorityRunnable, result);
                this.hasPriority = priorityRunnable;
            }

            @Override
            public long getInstanceCount() {
                return sequentialOrder;
            }

            @Override
            public int getPriority() {
                return hasPriority.getPriority();
            }
        }

        private static class ComparableRunnable implements Runnable, ComparableTask {
            private Long instanceCount = instanceCounter.getAndIncrement();
            private HasPriority hasPriority;
            private Runnable runnable;

            public ComparableRunnable(PriorityRunnable priorityRunnable) {
                this.runnable = priorityRunnable;
                this.hasPriority = priorityRunnable;
            }

            @Override
            public void run() {
                runnable.run();
            }

            @Override
            public int getPriority() {
                return hasPriority.getPriority();
            }

            @Override
            public long getInstanceCount() {
                return instanceCount;
            }
        }

        private interface ComparableTask extends Runnable {
            int getPriority();

            long getInstanceCount();

            public static Comparator<ComparableTask> comparatorByPriorityAndSequentialOrder() {
                return (o1, o2) -> {
                    int priorityResult = o2.getPriority() - o1.getPriority();
                    return priorityResult != 0 ? priorityResult
                            : (int) (o1.getInstanceCount() - o2.getInstanceCount());
                };
            }

        }

    }

    private static interface HasPriority {
        int getPriority();
    }

    public interface PriorityCallable<V> extends Callable<V>, HasPriority {

        public static <V> PriorityCallable<V> of(Callable<V> callable, int priority) {
            return new PriorityCallable<V>() {
                @Override
                public V call() throws Exception {
                    return callable.call();
                }

                @Override
                public int getPriority() {
                    return priority;
                }
            };
        }
    }

    public interface PriorityRunnable extends Runnable, HasPriority {

        public static PriorityRunnable of(Runnable runnable, int priority) {
            return new PriorityRunnable() {
                @Override
                public void run() {
                    runnable.run();
                }

                @Override
                public int getPriority() {
                    return priority;
                }
            };
        }
    }

}

A: Would it be possible to have one ThreadPoolExecutor for each level of priority? A ThreadPoolExecutor can be instanciated with a ThreadFactory and you could have your own implementation of a ThreadFactory to set the different priority levels.
 class MaxPriorityThreadFactory implements ThreadFactory {
     public Thread newThread(Runnable r) {
         Thread thread = new Thread(r);
         thread.setPriority(Thread.MAX_PRIORITY);
     }
 }


text:
Q: mysql + node.js - how to execute every or none queries? I am currently using mysql and Node.js, with multipleStatements I can do several queries at the same time, but if a query fails it doesn't break as I expected
app.post('/api3/stock5', function (req, res) {
  var connection = mysql.createConnection({
       host : conf.host,
       user : conf.user,
       password : conf.pass,
       database : conf.database,
       multipleStatements: true    //<- essential for several queries at the same time

    });
    var sql ="UPDATE  (...)"; INSERT INTO (...)";
    var query = connection.query(sql);
    query.on('error', function(err) {
    console.log("error: /api3/stock5 /n");
    console.log(sql);
  });
  query.on('result', function(result) {
  });
  query.on('end', function(result) {

  });
      res.send('OK');
});

Is there any way to make sure every query was performed correctly and only in that case commit? Thanks


text:
Q: The concept of non-blog content I'm fairly new to this wordpress stuff and wrapped my head around the blogging part.
Now it comes to the non-blog part of a webpage. I understood the principle of creating static pages and displaying them using various templates, but there is one major problem that i do not understand:
If i'm correct, i can have just one main-block of content for a page. For example, i could have an about section on my front-page and write it's content with the WP editor. But what if i need two or more sections? Should i create a (child)-page for every content-block and load it in the front-page's template file? This would be unnecessary bloating, wouldn't it?


text:
Q: Site Structure Regarding Custom Post Types and Taxonomies I need assistance with site structure with regard to properly setting up my Custom Post Types and Taxonomies.
I am developing a lifestyle site. It will not be a WP multi-site configuration.
This site will focus on several cities with several categories/topics and sub cats/topics.

*

*domain

*

*City

*

*City Topic

*

*City Topic Sub

*

*City Topic Sub Sub

domain_name/city/city_topic/city_topic_sub/city_topic_sub_sub/
As you can imagine there is a lot of "cross pollination" of all of these post. For example a topic or sub topic may be relevant and therefore associated with more than one city eg a specific post on heath topic might appear in all cities. Or a maybe another post might only be associated with just 2 cities. There will also be an "all cities" for readers that do not live within the area of a city that we have.
My first question is how is the best way to structure the backend with regard to CPT's and Taxonomies. I know there are a lot of ways "to skin a cat" but I need to set it up to give me the most flexibility for future expansion and also provide the most flexibility with regard displaying the content within the database in various scenarios.
I know I want/need to utilize custom post types to segment all the numerous posts that will be within this site.
My current thoughts are to utilize Pippins "Content Post Type" plugin for the creation and management of the CPTs, Taxonomies and Meta Info.
I also think that Scribu's "Posts 2 Posts" plugin  would play a part in this based on it's many-to-many post relationship capabilities, but for the life of me I can't figure it out.
Any advice would be appreciated.

A: URL structure and data storage are separate issues. You can use any data in an URL, so let's ignore that part for now.
Next step: By naming the parts sub and sub sub you went into the wrong direction. Just focus on what the information is, not where it belongs.
Data objects
City should probably a custom type, because you will need custom meta data for that. And I would make that a hierarchical post type, because in large cities it is rather useless to present results from a part of the town that is two or three hours away.
Now look at the relationships between the objects:

*

*1:1 or 1:n (n = many) post meta data; examples: latitude and longitude, average price for a cup of coffee or a bockwurst. :)

*n:m (many to many) taxonomy; each term can apply to many objects, each object can be part of multiple terms; examples: spoken languages, accepted currencies.

*If an object needs many custom meta data, use a custom post type for that. There is still no term meta in WordPress. You can use the Posts 2 Posts plugin to misuse the post types as pseudo-taxonomies, but this is not trivial.
Permalinks
You can use any data in any permalink. See my plugin T5 Rewrite for an example. You can even use that plugin and create custom child classes to add post meta data or custom taxonomies to any permalink. Examples for regular posts are already included.
Search
By default, WordPress will not search in terms and post meta data. You can change that by filtering the_search_query (example).


text:
Q: how to change text color of a particular item in navigation view? I tried alomst every link on stackoverflow but I could not find the right solution to my question. I tried this...
<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:itemTextColor="#fff"
    app:itemIconTint="#fff"
    android:background="#393737"
    app:headerLayout="@layout/nav_header_navigation"
    app:menu="@menu/activity_navigation_drawer"/>

But its changing the text color of each item. Is there any to change text color of single item? I am talking about changing the text color of particular item i.e. if we have four items

*

*sugar

*bread

*milk

*egg

This list is embedded in menu of navigation view. If we want to change the color of milk to red. How to do that??

A: You need to do that programatically.
// Get the navigation view first.
mNavigationView = (NavigationView) findViewById(R.id.nav_view);

Now you need to get the menu item from the navigation view and set the icon here.
// Get the index of milk
mNavigationView.getMenu().getItem(INDEX_OF_MILK).setIcon(R.drawable.milk_red);

The idea is keeping two separate icons for milk. You may change the icon anytime when needed. So the complete pseudo code should look like
if(milkIsRed)
    mNavigationView.getMenu().getItem(INDEX_OF_MILK).setIcon(R.drawable.milk_red);
else
    mNavigationView.getMenu().getItem(INDEX_OF_MILK).setIcon(R.drawable.milk_white);

A: You need to customize your navigation drawer View for that you can use this link  http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
XML look Like
<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/nav_home" />
    <item
        android:id="@+id/nav_photos"
        android:icon="@drawable/ic_photo_library_black_24dp"
        android:title="@string/nav_photos" />
    <item
        android:id="@+id/nav_movies"
        android:icon="@drawable/ic_local_movies_black_24dp"
        android:title="@string/nav_movies" />

    <item
        android:id="@+id/nav_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/nav_notifications" />

    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/nav_settings" />
</group>