text:
Q: Given P(Y | X) and random samples of Y drawn from P(Y), can one probabilistically assign values of X to each Y? Say I have a set of Y values drawn randomly from P(Y).  I'd like to probabilistically assign a value of X to each Y.  However, I don't know P(X|Y), but I do know P(Y|X).  Bayes' theorem relates these two conditional probabilities, but directly implementing Bayes would require knowledge of P(X) which I don't know a priori.
Any ideas?  Seems like this should be possible...

A: Most concretely without knowledge of $P(X|Y)$ or $P(X)$ you can not get at $P(X|Y)$.  To be precise one could construct distinct joint distributions $P(X,Y)$ and $Q(X,Y)$ such that $P(Y)=Q(Y)$ and $P(Y|X) = Q(Y|X)$ but $P(X) \neq Q(X)$ and $P(X|Y) \neq Q(X|Y)$.
At this point your best bet is perhaps to make assumptions about $P(X)$.  For example if you assume the (possibly improper) uniform distribution on $P(X)$ then sampling with probabilities proportional to $P(Y|X)$ is equivalent to sampling from $P(X|Y)$.
You can make other assumptions about $P(X)$ and follow these to consequences for $P(Y|X)$.  I'm not sure if you have access to any samples from $P(X)$ or any feedback about the $(x,y)$ pairs that you generate, but these could help inform the process.


text:
Q: Posterior predictive checks and the real world In general, when performing posterior predictive checks, one calculates a posterior predictive p-value like so: $$p_B = \frac{1}{S}\sum_{s=1}^{S}\mathbb{1} (T(x^{(rep,s)},\theta^{s}) \ge T(x,\theta^{s}))$$ for some test quantity $T(x,\theta)$ and replicate datasets $x^{rep,s}$.
I understand that this method is only used for probing the model for areas of weakness and that using the data twice is a necessary evil. See here for more details. That's not my problem however.
The whole idea is that we can make inferences on our model based on the outcome (ideally $p_B \approx$ 0.5) which depends on our test quantity/statistic. And while we shouldn't select a $T(X)$ that is a sufficient statistic for the model (like the mean or variance for exponential families), who is to say that the $T(X)$ we select is any good at telling us anything useful about the model?
For example, say my test statistic is $Min(X)$. A poor test statistic can only tell me that my model does not capture this aspect of the data well, based on the prior and likelihood that I set up. Then I could tweak my likelihood to somehow result in a better posterior predictive check. But then I'd be potentially overfitting. And what's more, overfitting to some test statistic that I think is a good one.
It seems to me to be a pretty complex and convoluted approach to model diagnostics, compared to cross validation and sensitivity analysis. Outside of academia and tightly controlled settings with well specified Bayesian models, do practitioners actually use posterior predictive checks? Anyone with real world use cases where this approach was helpful? I'm happy to use them in daily analysis because I strongly believe in model checking but this seems like a hassle for little insight gained.

A: Now that you've clarified in comments that you are worried about discovering a problem with a posterior predictive check but not knowing where to attribute the problem, I'll try to gather stuff into an answer instead of a long comment chain...
In the first place, I'd emphasize that posterior predictive checks are an additional layer of checks on top of what you already use -- or at least an additional option. Additional layers are always a win. You can compare what your model predicts versus what you would expect (i.e. the data you have) in a variety of ways, depending on what's important to you.
You can do this visually with plots, or you can do this quantitatively. As you say, it takes some thought to come up with statistics that reflect your concerns, but that's true from the first step of any analysis: what analysis will support the question you are asking of your data?
Second, the other things you mention can also fool you. I see all the time people who say they're using "CV" who are using it improperly. They're tweaking on their models -- making it a model selection problem -- but they're using CV within model fitting rather than around their entire process. When you're model selecting/comparing/tweaking you need to use nested CV and lots of people don't get that.
Third, some things people tend to look at with models are a reflection of Model World, not Real World. They are the model's opinion, as it were: they are based on the model being properly specified, among other things. So your question isn't unique to posterior predictive checks, and in fact having that additional, unique check is an important benefit. (This is related to the overfitting you fear: if your model seems to predict well, but it doesn't predict in a way that looks like what you'd expect, it's probably overfitted.)
Fourth, I'd disagree with your characterization that it's complex and convoluted. In fact, it's very straightforward: does my (generative) model predict things that act and look as I'd expect?
Last, don't forget that there are other permutation/sampling checks that should also be used on a model you care about. And more tests are better, since it's so easy to fool ourselves.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show a message when the client doesn't use Chrome? You also see it on Google search homepage. If the client doesn't use Chrome, then you'll see a promotion message for Chrome. It doesn't show up when the client is already using Chrome.
I'd like to achieve the same on my website. If the client is not using Chrome, then I'd like to display a message.

"For Better View Use Chrome"

How can I achieve this? I'm using HTML5 and CSS3.

A: You can check window.chrome in JavaScript.
<script>
    if (window.chrome) {
        alert('chrome');
    }
</script>

A: Per request, here's conditional code for IE:
<!--[if IE]>
    Code for any IE in here. You can load css and/or js.
<![endif]-->

If you use jQuery you can do:
if (!$.browser.webkit) {} // Targets non-wekbit browsers, Chrome, Safari...

A: Use this:
if(!(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase()))){
    alert("This browser is not fully supported yet, For best results please use Chrome");
}


text:
Q: Single SQLAlchemy mapped object resulting in many different instances in memory I know that title was convoluted, so I'll try to give a simplified example of what I'm trying to do. Please bear with me for a bit.
I'm working on an option values calculation and portfolio risk analysis server, and I've run into a problem I'm not quite sure how to address when loading my persisted object graph and then accessing some cached properties that I've dynamically added database load.
Say I have the following mapped classes:
Base = declarative_base()

class Portfolio(Base):
    __tablename__ = "portfolios"
    id = Column(Integer, primary_key=True)
    asset_classes = relationship("AssetClass", backref="portfolios")

class AssetClass(Base):
    __tablename__ = "asset_classes"
    id = Column(Integer, primary_key=True)
    portolio_id = Column(Integer, ForeignKey("portfolios.id"))
    assets = relationship("Asset", backref="asset_classes")

class Asset(Base):
    id = Column(Integer, primary_key=True)
    asset_class_id = Column(Integer, ForeignKey("asset_classes.id"))

Then I load a Portfolio and do some initialization as follows:
session = Session()
# pretend there's only one Portfolio
portfolio = session.query(Portfolio).one()
init_portfolio(portfolio)
while(keep_server_alive):
# session stays open for server life
    gevent.sleep(0)
session.close()

def init_portfolio(p):
    # note that this is a dynamically added property
    portfolio.values_store = ValuesStore()
    for asset_class in p.asset_classes:
        init_asset_class(asset_class)

def init_asset_class(ac):
    for asset in ac.assets:
        init_asset(asset)

Once everything is initialized I use a long running gevent thread to process price updates and calculate certain derivative values, as follows:
def on_underlying_update(asset, underlying_price):
    # the next line non-deterministically fails with an AttributeError
    values_store = asset.asset_class.portfolio.values_store
    values_store.get_asset_price(asset, underlying_price)

These calculations can be quite expensive, so the ValuesStore object has a caching strategy to store the results. On random passes through the on_underlying_update function, I'll get an AttributeError saying that the Portfolio object doesn't have a values_store property.
At first this really confused me, but as I debugged the issue a bit I seemed to find that the child AssetClass objects referring to the same Portfolio might actually be referencing different objects in memory. I came to believe this after using python's id() function to check Portfolio.id's against memory id's during each access. Doing so, I would routinely find that while I might have only ever access one Portfolio.id, I was referencing several different memory addresses depending on which child was doing the accessing.
I know this was long winded, and I appreciate anyone who's stuck with me this far. My question is, is there a way for me to load an entire object graph in to memory once and only once? This ValuesStore object can be expensive from a resources perspective, and I'd prefer to instantiate it as few times as possible.
For reference, I"m using Python 2.7.3, SQLAlchemy 0.8, gevent 1.0rc2, and I'm experiencing the same issue on both Windows 7 and OS X 10.8.
Thanks again.
** edit **
I spent a lot of time going through my code looking for statements that would cause a Portfolio object to be detached from the current session and attached to a new one. I couldn't find anything of the sort. I tried to listen to all sorts of Instance and Session events, and each time, I could see the "new" Portfolio being loaded but it was being loaded by the original Session.
Is it possible that the Portfolio object is being garbage collected? I tried testing this hypothesis by spawning a new Gevent thread to hold onto a strong reference to the Portfolio as follows:
def keep_portfolio_alive(p):
    portfolio = p
    while True:
        gevent.sleep(0)

This seems to solve the issue. I never see the Session load the portfolio a second time.
** edit 2 **
So I'm not sure, but I believe I've found my problem. When defining the relationships between mapped classes, I actually used attribute_mapped_collections instead of normal lists. When initializing the classes, I would iterate over the child objects like so:
for asset_class in portfolio.asset_classes.itervalues():
    # do something

Since some of these classes are multiply nested, along the hierarchy there was a class that had been referenced using this copied-iterator, and it then referenced its own child classes using another copied-iterator. My best guess is that the Portfolio class ended up with no strong references between either it and its parent object, or it and any of its child objects. The GC then marked it for collection at some point.
Hope this helps someone in the future.


text:
Q: How to trigger a task in airflow if immediate parent task fails? What i am mainly aiming for is that the restore_denormalized_es_Data should only get triggered when the load_denormalized_es_data task fails. If the load_denormalized_es_data task is successful then the command should be directed to end . Here as you can see , my restore is working when archive fails and load is skipped or retrying as a result i am getting wrong answers.
Have stated the code i am using
import sys
import os
from datetime import datetime
#import files what u want to import

# Airflow level imports
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator,BranchPythonOperator
from airflow.operators.bash_operator import BashOperator
from airflow.utils.trigger_rule import TriggerRule

#Imported all the functions and the code is able to call the functions with ease

# Name of the Dag
DAG_NAME = "DAG"

#Default arguments
default_args = {
    "owner": "Mehul",
    "start_date": datetime.today().strftime("%Y-%m-%d"),
    "provide_context": True
}

# Define the dag object
dag = DAG(
    DAG_NAME,
    default_args=default_args,
    schedule_interval=None
)
archive_denormalized_es_data = PythonOperator(
    task_id = "archive_denormalized_es_data",
    python_callable = archive_current_ES_data,
    trigger_rule=TriggerRule.ALL_SUCCESS,
    provide_context =  False,
    dag=dag
    )
load_denormalized_es_data = PythonOperator(
    task_id = "load_denormalized_es_data",
    python_callable = es_load,
    provide_context = False,
    trigger_rule = TriggerRule.ALL_SUCCESS,
    dag=dag
    )
restore_denormalized_es_data = PythonOperator(
    task_id = "restore_denormalized_es_data",
    python_callable = restore_current_ES_data,
    trigger_rule=TriggerRule.ALL_FAILED,
    provide_context=False,
    dag=dag
    )
END = DummyOperator(
    task_id="END",
    trigger_rule=TriggerRule.ALL_SUCCESS,
    dag=dag)

denormalized_data_creation>>archive_denormalized_es_data>>load_denormalized_es_data
load_denormalized_es_data<<archive_denormalized_es_data<<denormalized_data_creation

load_denormalized_es_data>>restore_denormalized_es_data
restore_denormalized_es_data<<load_denormalized_es_data

load_denormalized_es_data>>END
END<<load_denormalized_es_data

restore_denormalized_es_data>>END
END<<restore_denormalized_es_data

Here is the picture of the pipelines referred above

A: If I understand correctly, you want to skip the rest of the pipeline if A fails.
ShortCircuitOperator will allow Airflow to short circuit (skip) the rest of the pipeline.
Here is an example that does what you outlined.
from datetime import datetime

from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator, ShortCircuitOperator

from airflow.utils.trigger_rule import TriggerRule
from airflow.utils.state import State

def proceed(**context):
    ti = context['dag_run'].get_task_instance(a.task_id)
    if ti.state == State.FAILED:
        return False
    else:
        return True

dag = DAG(
    dag_id="dag",
    start_date=datetime(2021, 4, 5),
    schedule_interval='@once',
)

with dag:
    a = PythonOperator(
        task_id='archive_denormalized_es_data',
        python_callable=lambda x: 1
    )

    gate = ShortCircuitOperator(
        task_id='gate',
        python_callable=proceed,
        trigger_rule=TriggerRule.ALL_DONE
    )

    b = PythonOperator(
        task_id='load_denormalized_es_data',
        python_callable=lambda: 1
    )

    c = DummyOperator(
        task_id='restore_denormalized_es_data',
        trigger_rule=TriggerRule.ALL_FAILED
    )

    d = DummyOperator(
        task_id='END',
        trigger_rule=TriggerRule.ONE_SUCCESS
    )

    a >> gate >> b >> c
    [b, c] >> d

If archive_denormalized_es_data fails, the rest of the pipeline is skipped, meaning Airflow does not run restore_denormalized_es_data

If load_denormalized_es_data fails, restore_denormalized_es_data runs and continues to END.

If load_denormalized_es_data succeeds, restore_denormalized_es_data is skipped and continues to END.

You code is essentially missing the logic to skip when archive_denormalized_es_data fails, which the ShortCircuitOperator takes care of for you.


text:
Q: Trouble with using class types within other classes I have absolutely no idea what's going on. I've been looking up explanations for the weirdness going on here but it seems my situation is in some ways unique. I imagined it was the order in which I include my header files in each of my files, but to no avail, I have not found a combination that seems to be the solution.
The exact error I seem to be getting is "log does not name a type" when declaring LogArray[maxLength].
One of my classes, class logmgmt:
class logmgmt
{
private:
static const int maxLength = 500;
log LogArray[maxLength];
int length;

public:
void fillLogs(int index, int iD, std::string date, double startTime, double endTime);
void displayThisLog(int index);
void setLength(int length);

};

Pre-processor directives within logmgmt.cpp:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
#include "log.h"
#include "Logmgmt.h"

And directives within main.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#include "employee.h"
#include "log.h"
#include "employeemgmt.h"
#include "Logmgmt.h"

A: Remove using namespace std.
That is polluting the global namespace with lots of symbol names that can cause these conflicts.
In your example, the function std::log becomes log.  So it can no longer name a global type.


text:
Q: Copy only the entered character from one text box to another I have two text box #textBox1 and #textBox2.
User will input to #textBox1 and all the values need to be copied to #textBox2 automatically [I have a onkeyup event here]. Only copy and paste from one to another is not a problem. My requirement is once user press space or enter my English word from #textBox1  will convert to local language but I need only the English version on #textBox2.
See the example below:
textBox1 = "Bhuwan", textBox2="Bhuwan"
once user press space bar
textBox1 = "भुवन ", textBox2="Bhuwan "

textBox1 = "भुवन Gautam", textBox2="Bhuwan Gautam"

Again once user press space bar
textBox1 = "भुवन गौतम", textBox2="Bhuwan Gautam"

I have used the following but it is not complete if the user use backspace on #textBox1.
$("#textBox1").keyup(function(e) {
            $('#textBox2').val($('#textBox2').val()+String.fromCharCode(e.which));
});

I know there is a better solution. How do I achieve this either from jquery or javascript ?

A: I think You can go through this solution Click
I will highlight some points.
Use Google translation API. Easy to use. For example the following translates Spanish to English. To translate from and to other languages, simply change 'es' and 'en'
google.load("language", "1");

function initialize() {
    var content = document.getElementById('content');
    content.innerHTML = '
Hola, me alegro mucho de verte.<\/div>
';
    var text = document.getElementById("text").innerHTML;
    google.language.translate(text, 'es', 'en', function(result) {
        var translated = document.getElementById("translation");
        if (result.translation) {
            translated.innerHTML = result.translation;
        }
    });
}
google.setOnLoadCallback(initialize);

try google translate: http://code.google.com/apis/language/translate/overview.html
You can also use this JQuery plugin http://www.openxrest.com/translatejs
You can use bing translate .. http://setahost.com/bing-translate-api-with-jquery-ajax/ Bing api is still free


text:
Q: How to get value from objects in array of objects? I'm making an aggregation and I'm at a step where I have the following:
˅ typeCount: Array
    ˅ 0: Object
        _id: "System"
        count: 1002
    ˅ 1: Object
        _id: "Application"
        count: 3065
˅ affectedComputers: Array
    ˅ 0: Object
        _id: ObjectId('...')
        count: 1
    ˅ 1: Object
        _id: ObjectId('...')
        count: 1
    ...

Now I'm trying to get the following result:
application: 3065
system: 1002
affectedComputers: 2951

The affectedComputers array is a group by computers, so I just use $size to get the count of computers. But I don't know how to get the Application and System count... And keep in mind that they can also be 0 if there is no instances when I group.
I've done the following:
{
    $project {
        'affectedComputers': { $size: '$affectedComputers'}
    }
}

This only gives me the affected computers count, how do I get the System and Application count if there are any, if not then get it as 0?

A: Easiest way to do this generically is just to use $arrayToObject and convert the whole array, You can also define it manually field by field, here's how to do the first approach:
db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            "affectedComputers": {
              $size: "$affectedComputers"
            }
          },
          {
            "$arrayToObject": {
              $map: {
                input: "$typeCount",
                in: {
                  k: "$$this._id",
                  v: "$$this.count"
                }
              }
            }
          }
        ]
      }
    }
  }
])

Mongo Playground


text:
Q: How can I use a decorator to wrap the result of my function, inside of a multiple external library functions I've only recently learned about decorators, and despite reading nearly every search result I can find about this question, I cannot figure this out. All I want to do is define some function "calc(x,y)", and wrap its result with a series of external functions, without changing anything inside of my function, nor its calls in the script, such as:
@tan
@sqrt
def calc(x,y):
    return (x+y)

### calc(x,y) = tan(sqrt(calc(x,y))
### Goal is to have every call of calc in the script automatically nest like that.

After reading about decorators for almost 10 hours yesterday, I got the strong impression this is what they were used for. I do understand that there are various ways to modify how the functions are passed to one another, but I can't find any obvious guide on how to achieve this. I read that maybe functools wraps can be used for this purpose, but I cannot figure that out either.
Most of the desire here is to be able to quickly and easily test how different functions modify the results of others, without having to tediously wrap functions between parenthesis... That is, to avoid having to mess with parenthesis at all, having my modifier test functions defined on their own lines.

A: A decorator is simply a function that takes a function and returns another function.
def tan(f):
    import math
    def g(x,y):
        return math.tan(f(x,y))
    return g


text:
Q: Cannot connect docker swarm agent from outside internet I try to provide Python Flask (port 5000) on Docker swarm by Azure Container Service.
The deployed agent can be connected by curl 0.0.0.0:5000 from swarm management but cannot connect from outside of internet.
The port 5000 is well defined in agent Azure load balancer. What else can I inspect more?
I launch flask by follwing command.
docker run -d -p 5000:5000 bbb/web /root/startScript.sh

The result of docker ps is as below. bbb/web is what I want to serve.
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
05a96351290c        bbb/web       "/root/startScript.sh"   43 minutes ago      Up 43 minutes       0.0.0.0:5000->5000/tcp                                                                                jovial_meitner
adcc2d45cbe0        swarm:1.1.0         "/swarm manage --repl"   8 months ago        Up 7 weeks          0.0.0.0:2375->2375/tcp                                                                                containers_swarm_1
2264e2b1636f        progrium/consul     "/bin/start -server -"   8 months ago        Up 7 weeks          0.0.0.0:8300-8302->8300-8302/tcp, 0.0.0.0:8400->8400/tcp, 53/tcp, 53/udp, 0.0.0.0:8500->8500/tcp, 0.0.0.0:8301-8302->8301-8302/udp   containers_consul_1

The result of docker network ls is as below
NETWORK ID          NAME                DRIVER              SCOPE
66bf169bd8f9        bridge              bridge              local
2aeb61431acf        host                host                local
19448e290e2c        none                null                local

The result of docker info is as below
Containers: 5
Running: 3
Paused: 0
Stopped: 2
Images: 3
Server Version: 1.12.2
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 48
Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: overlay null host bridge
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: apparmor
Kernel Version: 3.19.0-65-generic
Operating System: Ubuntu 14.04.4 LTS
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 3.36 GiB
Name: swarm-master-A501B991-0
ID: KKRP:45CG:NSBD:EUP5:PDGV:S3QA:4UUJ:NUIS:YP7I:DBLM:GSXU:47SC
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Username: bbb
Registry: https://index.docker.io/v1/
WARNING: No swap limit support
Insecure Registries:
127.0.0.0/8

A: Man, forgive my stupidity.
I missed to make ssh tunnel. It was run on my local machine actually.
ssh -L 2375:localhost:2375 -f -N myname@dockertestmgmt.eastasia.cloudapp.azure.com -p 2200
export DOCKER_HOST=:2375

A: It is probably that you have not opened port 5000 correctly, e.g. missing NSG. See https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access (that document talks about DC/OS but the process is the same).


text:
Q: Difference between .exe and .pe files? When compiling visual studio c# applications PE and EXE files will generate.
So what main difference between PE and EXE file?
As i know PE file contains
PE/COFF Headers,
CLR Headers,
CLR Data,
Meta Data,
IL code,
.data,.text...

than what exe contains?.How  PE differ from EXE?

A: Portable Executables (PE) are files that contain all the necessary information for the operating system to correctly load executable code (.exe, .dll, ...)
This may include dynamic library references for linking, resource management, TLS data, among other things.
Executables (.exe), however, are the files that denote the main execution point on a computer program, that is, speaking in C# terms, the file that contains the Main function or entry point.

A: .exe files are a subset of PE files, while PE files include .exe, .dll and .ocx files.

A: So, PEstands for Portable Executable which is the file format for executable binaries in Windows 32bits and 64bits environments.
In my understanding, the information inside the generated PEfile would consist in:

*

*Headers

*Metadadata

*CLR Data segments

However, the IL Code would be inside the EXE file, since it is supposed to be platform independent and it will be compiled to native code when you run the application (Just-in time-compiler). The PEsection is also in charge of the initialisation of the CLR.
Keep in mind the PE section can be inside the executable file, which make more sense in most applications.


text:
Q: How to add an element to the first row of a div which contains some elements (jQuery)? I have some elements as below:

           some content blah blah blah...

I need to add lets say the below div to shareswrapper:

           Some new content here!!!!

The output would as below:

           Some new content here!!!!

           some content blah blah blah...

I used first child but gain no success. .before() method wont work for me because I don't know which divs I have inside the shareswrapper.
Any suggestion?

A: Use prepend..
$('#shareswrapper').prepend('
Some new content here!!!!
');

A: You're on the right track with both. Chain them together
$('#shareswrapper:first-child').before("injection content")


text:
Q: Why is my return value wrong? I have a vector class in C# (a fragment below). My issue is that when I call GetMagnitude(), it always returns 0.0f - even with the debugger running and I check that Sq has a valid value, as soon as it gets passed back into other function (eg: Normalize() ), it has return 0.0f. Can someone explain this and help me fix it? My guess is that it has something to do with double->float conversion but I just can't figure it.
public class float3
{
    public float x;
    public float y;
    public float z;

    public float GetMagnitude()
    {
        float SumSquares = (float)( Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2));
        float Sq = (float)Math.Sqrt(SumSquares);
        return Sq;
    }

    public void Normalize()
    {
        float inverse = 1.0f / GetMagnitude();

        x *= inverse;
        y *= inverse;
        z *= inverse;
    }
}

A: I just tested your code with this set up and it worked perfectly:
void Main()
{
    var myData = new float3
    {
        x = 1,
        y = 1,
        z = 1
    };
    float result = myData.GetMagnitude();
}

I get the result 1.73...
Is it possible that the problem is elsewhere?  Could you create a small console app and insert that code just to isolate it?


text:
Q: Docker run vs Podman run I have got the following Dockerfile:
FROM node:18.6.0-alpine3.15
RUN apk --no-cache add --virtual .builds-deps build-base python3 python3-dev py3-pip && \
    echo "echo http://dl-cdn.alpinelinux.org/alpine/latest-stable/main" >> /etc/apk/repositories && \
    echo echo "http://dl-cdn.alpinelinux.org/alpine/latest-stable/community" >> /etc/apk/repositories && \
    apk update && apk upgrade && \
    apk add linux-headers && \
    pip3 install --upgrade pip
RUN pip3 install RPi.GPIO rpi_ws281x adafruit-circuitpython-neopixel
WORKDIR /usr/src/app
COPY . .
RUN npm install && mkdir -p backend/images
EXPOSE 3000
CMD [ "node", "server.js" ]

This container image is running on a raspberry pi and I am controlling for example a led stripe.
The weird thing is that everything works with this docker run command:
docker run --rm --name cm_back_test --privileged -e CM_USER=superuser -e CM_PASSWORD=superuser -e CM_CLUSTER=cluster.xxxx.mongodb.net cm-back:1.0.0

I need the privileged flag for the gpio stuff.
But for some reasone the exact same command with podman does not work.
Can someone explain me why?


text:
Q: How to highlight dates between fromDate and toDate, Jquery datepicker? I have created a JS fiddle with my current code. What I want is to highlight the days between the selected "from" date all the way until the "to" date. For example if I select 29.01.2014 as my from date and the 02.02.2014 as my to date, all dates in between should be highlighted.
Also, if anyone could guide me on making the minDate for the "to" date be either the current date or the date selected in the From picker, that would be great.
What I have so far. Fiddle below.
$(function () {
    $("#From").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        numberOfMonths: 1,
        gotoCurrent: true,
        minDate: 0,
        maxDate: "+1y",
        onClose: function (selectedDate) {
            $("#To").datepicker("option", "minDate", selectedDate);
        }
    });
});

$(function () {
    $("#To").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        numberOfMonths: 1,
        gotoCurrent: true,
        minDate: "From",
        maxDate: "+1y",
        onClose: function (selectedDate) {
            $("#From").datepicker("option", "maxDate", selectedDate);
        }
    });
});

http://jsfiddle.net/4n4Cu/

A: Try changing your code to this
$(function () {
    $("#To").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        numberOfMonths: 1,
        gotoCurrent: true,
        minDate:$("#From").val() == ""|| undefined ? 0 : $("#From").val() ,
        maxDate: "+1y",
        onClose: function (selectedDate) {
            $("#From").datepicker("option", "maxDate", selectedDate);
        }
    });
});


text:
Q: Python Pytest files to convert single executable file and executed via batch file I have 10 pytest files and the demand is to convert these to a single executable file, The project contains properties file in which data is present.I need the data for pytest as in the console I was running via python -m pytest but in pyinstaller it is asking for a single .py file to be converted. I tried but came into no solution. Please help me its important. Even though I convert to a single executable the exe file never runs.
In Java I used to create a jar file and it can be processed via .bat file and it reads data from properties file and it works
If in python something like that we can achieve will be welcomed


text:
Q: Make a MySQL query reusable with double ?? for tables and ? for selectors with NodeJS and JavaScript Hi. I am looking to create a reusable query with MySQL and NodeJS
The first step I took after the DB connection was to create a data access object and interact with the DB while using promises. To stay relative secure, I am using placeholders:

*

*" ? " for rows and values and double " ?? " for tables.

I want to create functions to be reused. So if I am creating one function for insert, I need to use same function to insert records in different tables while using parameters.

*

*The Data access layer looks like this: Here I am using parameters that will go to each function and replace the placeholders from the sql statements.
       /*
           Insert user accepts three parameters. Statement from mysql, table marked with ?? in the statement and the
           payload object that have to match the database columns
       */
       insertRecord: (sqlStatement, table, payload) => {
           return new Promise((resolve, reject) => {
               db.query(sqlStatement, [table, payload], (error, response) => {
               if (error) return reject(error);
               return resolve(response);
           });
         });
       },

   /*
       This function accepts four parametters. The first parameter is the statement. Second parameter is the table selector
       marked with ?? in the statement.
       The selector is the row, and the value specified
   */
   selectSimpleStatement: (sqlStatement, table, row, value) => {
       return new Promise((resolve, reject) => {
           db.query(sqlStatement, [table, row, value], (error, response) => {
           if (error) return reject(error);
           else return resolve(response);
       });
     });
   }
}

*The second implementation was to create all the MySQL queries separately because I wanted to keep it Clean
module.exports = {
insertStatement:            'INSERT INTO ?? SET ?',
sqlSimpleSelect:            'SELECT * FROM ?? WHERE ? = ?'
}

*Using the first sql statement was easy. I worked to insert in all the tables with the same function. But the select is a pain. With postman I am getting empty arrays even if the values are correct...
const { sqlSimpleSelect } = require('../../database/statements.js');
const bcrypt = require('bcrypt');

exports.add = async (req, res, next) => {
    const {username, password} = req.body;

try {
    // Select from users where username = username variable
    const user = await selectSimpleStatement(sqlSimpleSelect, 'users', 'username', username);
    res.send(user);
}
catch (error) {
    res.send(error)
    }
}```

I am getting empty array. Can please help me?
Thanks, Daniel


text:
Q: Xrandr message: Rate 144.0 Hz not available for this size When I type xrandr and press enter, the output I get says that I have 144.0 hz available to use on my 1920x1080 resolution, but when I try the command:
xrandr -s 1920x1080 -r 144.0

or 144 without .0 I get the message:

Rate 144.0 Hz not available for this size

I get that message with every possible refresh rate, even the current using refresh rate (60 Hz). I have nvidia-settings installed which also handles the refresh rate, might the problem be there?

A: I had the same problem with my 144hz monitor. You might try using a full set of parameters. For example, to get my 2560x1440 screen to operate at 144hz, I had to do the following:

*

*Run xrandr to find the name of your connected display output. In this case, DP-0 is my connected DisplayPort:
$ xrandr
Screen 0: minimum 8 x 8, current 2560 x 1440, maximum 16384 x 16384
DVI-I-0 disconnected (normal left inverted right x axis y axis)
DVI-I-1 disconnected (normal left inverted right x axis y axis)
HDMI-0 disconnected (normal left inverted right x axis y axis)
DP-0 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 598mm x 336mm
2560x1440     59.95*+ 144.00   120.00    99.95    84.98    23.97
DP-1 disconnected (normal left inverted right x axis y axis)

*Then use the xrandr command again with the --output, --mode, and --rate parameters. For my 2560x1440 monitor, I specified the following:
$ xrandr --output DP-0 --mode 2560x1440 --rate 144.00

The monitor blinks and switches to the new rate. I'm not sure how to properly use the -s parameter.


text:
Q: VMware write eager zeros after disk creation It would be nice to be able to convert a Lazy Zeroed disk to an Eager Zeroed disk after disk creation in VMware - is this possible?
I understand the basic difference between Thick Provision Lazy Zeroed and Thick Provision Eager Zeroed.  I usually want to do Lazy Zero so I can create the disk faster.  And the eager zeroed performance increase is not large in most circumstances.
However, it would be nice to make the disk Eager Zeroed after disk creation, perhaps as a background task.

A: Storage vMotion or a powered-off datastore migration will allow you to select a different disk type.  Then just migrate the disk back to the original datastore, if desired.

A: You can use the vmkfstools with the -k option. For example:
vmkfstools -k disk.vmdk

However, you will have to shutdown the VM first and login to the ESXi Shell.
Also, to determine if a disk is zeroedthick or eagerzeroedthick, you can use the same command with the -D parameter as:
vmkfstools -D disk.vmdk

Then look for tbz 0 in the resulting output. If the value is 0 then the disk is eagerzeroedthick, otherwise it is zeroedthick.
Both commands are described in the follwing VMware KB article:
Determining if a VMDK is zeroedthick or eagerzeroedthick (1011170)

A: If your VM is running Linux you can use the Zerofree tool to do this.  Keep in mind if your running this on the root filesystem you'll first need to mount it as read-only.  The Zerofree man page explains how to do this.  It's pretty simple.

A: If you're using windows you can use sdelete as part of the sysinternals toolkit or (faster) the Nimble space reclaim powershell which will zero out the free space


text:
Q: Regex lookahead and lookbehind assertions I'm used to the standard usage of lookahead and lookbehind assertions like so
(for e.g.): .(?=foo) and (?<=foo).. That is in lookahead case we need to place the search token before the lookahead, in case of lookbehind we need to place the search token after the lookbehind. But i've also seen such a construct: (?=foo). .Does that make sense and if so what will it match?

A: I've also seen (?=foo).. Does that make sense and if so what will it match?
It's still a positive lookahead regexp:

Source regex101: Online regex tester and debugger
Notes:

*

*If your test expression is afoo it will match f.

*To match foo use (?=foo).+


text:
Q: Two differents views depending on the URL file extension using Spring MVC 3 I want to have the same request mapping but resolve to different view depending on the file extension. I have two JSPs one that renders HTML and another that renders XML. Depending on the file extension I should resolve to the corresponding jsp.
This is my controller:
@Controller
public class FileManagementController {

    @RequestMapping(value="/filemanagements", method=RequestMethod.GET)
    public ModelAndView list() {
        //if file extension .xml return  /filemanagement/listXml
        //if no file extension present return /filemanagement/list
    }

}

And I Have the following y Root of my WebApp:
/jsp/filemanagement/list.jsp
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

..
/jsp/filemanagement/listXml.jsp
<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="text/xml" pageEncoding="UTF-8"%>

....
This is how I have configured my ViewResolver in the servletContext.xml:
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
</bean>

A: Have a look at ContentNegotiatingViewResolver.  From the javadoc:

This view resolver uses the requested media type to select a suitable View for a request.
If the requested path has a file extension and if the setFavorPathExtension(boolean) property is true, the mediaTypes property is inspected for a matching media type.

There is also a section of the ref manual covering this resolver.

A: Following skaffman advice. I did solve this using ContentNegotiatingViewResolver.
servletContext.xml:

<bean id="resourceResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"/>

<bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>

<mvc:annotation-driven/>

The resolvers are picked up automatically by ContentNegotiatingViewResolver.
Controller:
@Controller
@RequestMapping("/filemanagements")
public class FileManagementController {

    @RequestMapping(method=RequestMethod.GET)
    public ModelAndView list(@RequestParam(required=false) String contentType) {
        return new ModelAndView(baseLogicView + "/list");
    }

    private static final String baseLogicView = "/filemanagement";
}

These jsps:
/WEB-INF/jsp/filemanagements/list.jsp
/WEB-INF/jsp/filemanagements/listXml.jsp

Resource bundle views.properties:
/filemanagement/list.(class)=org.springframework.web.servlet.view.JstlView
/filemanagement/list.url=/WEB-INF/jsp/filemanagement/listXml.jsp
/filemanagement/list.contentType=text/xml

It was necessary to specify the contentType there because if you don't it defaults to this "text/html;charset=ISO-8859-1" even if you set <%@ page contentType="text/xml" %> in the JSP that renders the XML.
After that I could do the following requests:
http://localhost:8080/filemanagement-web/filemanagements (list.jsp)
http://localhost:8080/filemanagement-web/filemanagements.html (list.jsp)
http://localhost:8080/filemanagement-web/filemanagements.xml (listXml.jsp)


text:
Q: JavaScript var declaration style - susceptible to ASI? In my coding style I generally tend to have the commas for comma separators before the next value, example:
var x
   ,y
   ,z

I find this is easier to assimilate as the pattern when broken is obvious to the human eye.
Question - is this likely to fall foul of automatic semicolon insertion (ASI) - I read this linked question and it was not obvious after a couple of readings so I decided to ask.
[EDIT] I voted to re-open this question. My point is that whilst the answer can eventually be pulled from the linked question, it is not at all obvious. I linked to the same question as was proposed as duplicate as I had found it to be the best discussion of the overall ASI concept. Summary - I don't think the answer to my question is clear in the linked question therefore, this question should stand.


text:
Q: How to render an image to a JTable cell I want to apply a renderer on a cell of my JTable, to do so I created a class named myRenderer :
import java.awt.Component;

import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class MyRenderer extends DefaultTableCellRenderer {

public Component getTableCellRendererComponent(JTable table, ImageIcon icon) {

setIcon(icon);
return this;
}
}

And I use this piece of code to apply the renderer on the cell :
MyRenderer renderer = new MyRenderer();

renderer.getTableCellRendererComponent(table, icon);

table.getColumnModel().getColumn(6).setCellRenderer(renderer);

The problem is that the rebderer is applied on all the cells in the column 6, and I want it to be applied on one cell only (row/column) but I don't know how to do so ?
Thanks in advance

A: Besides the fact that you are not even properly overriding the getTableCellRendererComponent method, you don't even need a custom renderer to display an image in a column
From How to Use Tables. Here's a list of types with default pre-configured renderers

*

*Boolean — rendered with a check box.

*Number — rendered by a right-aligned label.

*Double, Float — same as Number, but the object-to-text translation is performed by a NumberFormat instance (using the default number format for the current locale).

*Date — rendered by a label, with the object-to-text translation performed by a DateFormat instance (using a short style for the date and time).

*ImageIcon, Icon — rendered by a centered label.

*Object — rendered by a label that displays the object's string value.

So you can put add an ImageIcon to the table and it will be rendered as such, given you properly override the getColumnClass()
Also from tutorial:

To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model's getColumnClass method, which gets the data type of the column's cells. Next, the table compares the column's data type with a list of data types for which cell renderers are registered

So say you have a DefaultTableModel with three columns and you want an ImageIcon in the last column. You would do something like this
DefaultTableModel model = new DefaultTableModel(...) {
    @Override
    public Class<?> getColumnClass(int column) {
        switch (column) {
            case 2: return ImageIcon.class;
            default: return String.class
        }
    }
};
JTable table = new JTable(model);

Then by just adding an ImageIcon to the third column, it will be rendered as such
String colOneDate = "Data";
String colTwoData = "Data";
ImageIcon colThreeIcon = new ImageIcon(...);
model.addRow(new Object[] { colOneData, colTwoData, colThreeIcon });

You will probably also want to set the column widths and height accordingly, to the size of the image. For that you can see any of these questions

A: You can use getTableCellRendererComponent function in as described below. The icon, row and coulmn to display icon, you can set from out side using a setter methode
import java.awt.Component;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

  public class MyRenderer extends DefaultTableCellRenderer {

public MyRenderer() {
    // TODO Auto-generated constructor stub
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
            row, column);

    int neededRow=0; // set the needed row here in which the icon to be dispayed
    int neededcolumn=0; // set the needed column here in which the icon to be dispayed

    if(row==neededRow && column==neededcolumn)
    {
        setIcon(icon);
    }

    return this
}
}


text:
Q: Fetching reminders in background using EventKit I am creating an Apple Watch app which has a button that makes a call to the parent iOS app.
WKInterfaceController.openParentApplication(message, reply: {
            (response: [NSObject:AnyObject]!, error: NSError!) in
    // processing data from iOS app
})

The iOS app responds by retrieving some reminders using EventKit, like so:
eventStore.fetchRemindersMatchingPredicate(predicate, completion: {
                [unowned self] reminders in
    // sending back data as reply to Apply Watch
})

When the parent app is in the foreground, everything works like a charm. But when I make the app go to the background, something strange happens. The call to EKEventStore, eventStore.fetchRemindersMatchingPredicate(predicate), never calls my completion block. So I never send a reply back to the Apple Watch because of that?
So what is going wrong? I suspect a bug in EventKit, or maybe calling EventKit in the background is not supported. Can anyone shed some light on this?

A: I figured it out! Before letting EKEventStore spawn an async process, I have to start a background task. When I complete the async call, I have to explicitly end the background task.
// First let iOS know you're starting a background task
let taskIdentifier = application.beginBackgroundTaskWithExpirationHandler() {
    () -> Void in
    // Do something when task is taking too long
}
// Then do the async call to EKEventStore
eventStore.fetchRemindersMatchingPredicate(predicate, completion: {
            [unowned self] reminders in
    // Do what I have to do, and afterwards end the background task:
    application.endBackgroundTask(taskIdentifier)
})


text:
Q: Trace of the product af oa positive definite matrix and a negative semidefinite matrix Let $A$ and $B$ be $n\times n$ real symmetric matrices. Let us assume $A$ to be a positive difinite and $B$ negative semidefinite.
Is it true that
$$
\text{trace}(AB) \le 0 \quad \text{?}
$$
Thanks!

A: Hint: $-B$ is positive (semi)definite. Compute ${\rm trace}(A(-B))$.


text:
Q: Reading/writing C arrays from R matrices Below is a minimal example of creating 3 matrices in R that should be manipulated by calling C code.
In short, I'd like to pass a matrix A from R to C, which then copies some values to the W and H matrices. The latter 2 I want back in R with the modified values.
However, this doesn't quite work (segfault, or empty matrices returned). I suspect that R copies the objects for use in C instead of passing them by reference.
C source (test.c):
void test(double *A, double *W, double *H, int m, int n, int k) {
    // A is input with dimensions (m,n)
    // W has dimensions (m,k)
    // H has dimensions (k,n)

    int i;

    for(i=0; i<m*k; i++)
        W[i] = A[i];

    for(i=0; i<k*n; i++)
        H[i] = A[i];
}

Some build instructions (Makefile):
CCFLAGS = -fPIC

all: shared

shared: test.o
    $(CC) -shared -Wl,-soname,test.so -o test.so test.o

test.o: test.c
    $(CC) $(CCFLAGS) -c $<

And that's the R code to call it:
dyn.load("test.so")

m = 3
n = 3
k = 2

A = matrix(c(1:(m*n)), nrow=m, ncol=n)

W = matrix(0, nrow=m, ncol=k)
H = matrix(0, nrow=k, ncol=n)

.C("test", as.double(A), as.double(W), as.double(H),
   as.integer(m), as.integer(n), as.integer(k))

Now my questions:

*

*Why does this segfault most of the time?

*Is there a way to call C functions with uninitialized R matrices?

*Why does a 'void' function return something?

And, most importantly,

*

*How to get this working?

A: *

*Why does this segfault most of the time?

This is (probably) because your function takes integers, whereas, the .C interface will pass in pointers.  Your signature should be
void test(double *A, double *W, double *H, int *m, int *n, int *k)

*

*Is there a way to call C functions with uninitialized R matrices?

Setting DUP=FALSE in your call to .C will prevent .C from copying the arrays you pass into it.  See ?.C for details.

*

*Why does a 'void' function return something?

The C function doesn't return anything, but the R function .C returns a list, corresponding the the arguments passed in to the C function.  Again, see ?.C.

*

*How to get this working?

You have two choices.  The first is to set DUP=FALSE and let the C function modify the existing R objects.  If you do this, though, you want to make sure that you call as.double before you pass them into the external call, otherwise as.double will be forced to create new objects, because as currently defined W and H will be type integer.
Your second choice is to leave DUP=TRUE, and use the return value from the .C call, as in:
result<-.C("test", as.double(A), W=as.double(W), H=as.double(H),
  as.integer(m), as.integer(n), as.integer(k))
W<-result$W
H<-result$H


text:
Q: Taylor Series of Rational Function I must admit that my understanding of Taylor and power series is flimsy at best. I am supposed to find the Taylor series for the following function centred at $x=0$:
$$\frac{1}{(1-5x)^2}$$
I honestly have no idea as to the approach to take from here. Should I look to relate this to the function $\frac{1}{1-x}$, attempt to determine the first few terms of the series and notice a pattern, or something else entirely? I'm not necessarily looking for an answer but rather an explanation as to how to best tackle problems of this nature.

A: HINT:
Let $f(x)=\frac{1/5}{1-5x}$ so that $f'(x)=\frac{1}{(1-5x)^2}$.  Now, differentiate the geometric series for $f(x)$ term by term.


text:
Q: AppBar tabs on click listener I have a tabbed activity with fragments.
The number of tabs is generate from the default code bellow:
public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 6;
        }
    }

I have add icons on my tabs with the code bellow:
private int[] tabIcons = {
            R.drawable.web,
            R.drawable.social,
            R.drawable.contact,
            R.drawable.partners,
            R.drawable.exclusivevideo,
            R.drawable.jobifyblack
    };

And inside onCreate(Bundle savedInstanceState) i am using the code bellow:
// primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        //Add icons on tabs
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);
        tabLayout.getTabAt(5).setIcon(tabIcons[5]);

By default all tabs are generated inside AppBarLayout.
Now the only thing that i want is how to trigger a click on last tab to open a new activity and do not open fragment inside container.
I tried a lot of examples without any luck!

A: http://www.mkyong.com/android/android-tablayout-example/
Try this example if you are not looking this please comment


text:
Q: Formatting a file name when using %1$s Anyone help me with a formatting issue I have? I have a relative file path that my app uses to copy the file over and save it, such as:
\users\user1\test.pdf

Only problem is if you use %1$s as your formatter string it will copy this file over as a folder and then save the file in that folder, so you end up with the file name as part of the path, such as:
\users\user1\test.pdf\test.pdf

Anyone know the correct format string to get around this?

A: You should use File objects for handling paths.
File f = new File("test/something");

f.getParent();
f.getName();

etc...


text:
Q: Android GridView Adapter using ArrayList I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {

JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();

 // JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";

static String FLAG = "flag";

private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.jgrid66);
    grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);

}//--- END onCreate

//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        JGrid4Adapter jParser = new JGrid4Adapter();
        // getting JSON string from URL
        JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
        try {
            JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
            // looping through All gallery images
            for (int i = 0; i < JSArrGallery.length(); i++) {
                JSONObject galleryJO = JSArrGallery.getJSONObject(i);
                String idStr = galleryJO.getString(TAG_ID);
                String urlStr = galleryJO.getString(TAG_GALLERYURL);
                String descrStr = galleryJO.getString(TAG_GALLERYDESCR);

                idStrArrList.add(idStr);
                urlStrArrList.add(urlStr);
                descrStrArrList.add(descrStr);

            }// -- END for loop
        } catch (JSONException e) {
            e.printStackTrace();
        }// --- END Try
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
        grid65_gv.setAdapter(jGr7Adap);
        jGr7Adap.notifyDataSetChanged();
    }

}

//--- END DownloadJSON Class
}

Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;

public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
    super();
    this.urlStrArrList = urlStrArrList;
    }

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

@Override
    public String getItem(int position) {
    return urlStrArrList.get(position);
    }

@Override
public long getItemId(int position) {
    return 0;
}

    public static class ViewHolder
    {
    public ImageView wcbc_image_iv;
    }

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHldr;
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();

    if(convertView==null){
        viewHldr = new ViewHolder();
        convertView = inflater.inflate(R.layout.jgrid66_item, null);
        viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById   (R.id.jgrid66_iv);
        convertView.setTag(viewHldr);
    }
    else
    {
        viewHldr = (ViewHolder) convertView.getTag();
    }
    //--- I commented this out because this is where it breaks.
    //viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
    return convertView;
}

}

Any help would be great!

A: private ArrayList<String> urlStrArrList;

is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)

Added in API level 1
Sets a drawable as the content of this ImageView.

You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying


text:
Q: How to solve the spam outgoing emails from a VPS? I bought a new VPS and using WHM i created a cpanel account.
After doing some research about why are the emails were going on spam
without any reasons and by this i mean :
 1. No blacklisted IP,
 2. No blacklisted hostname,
 3. Normal emails with only text, not html,
 4. SPF, DKIM and PTR records configured .

If there is any other reasons for this please help me .


text:
Q: Ruby on rails 4: showing error messages I have trouble displaying error message for invalid inputs using Ruby on rails. If anyone can help me with it? Currently new to the area.
I suspect the area is due to :user and @user.
This is my form generated on index.html.erb
<%= form_for :user, url: '/login', html:{id:"form"} do |f| %>

Login

                <input type="name" placeholder="Name" name="user[name]" class="form-input" required />

<% end %>

My ActiveRecord Model:
class User < ActiveRecord::Base
    validates :name, :uniqueness => true

    has_secure_password

end

I try to use the following error handling, by passing the following code after <%= form_for :user, url: '/login', html:{id:"form"} do |f| %> but it did not work with and showed:
NoMethodError in Users#register
: undefined method `errors' for nil:NilClass
 <% if @user.errors.any? %>

<%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:

        <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

    <% end %>

A: You should be able to do something like this.
/app/views/shared/_error_messages.html.haml:
- if object.errors.any?
  .alert.alert-danger
    The form contains #{pluralize(object.errors.count, "error")}.
  %ul#error_explanation
    - object.errors.full_messages.each do |msg|
      %li= msg

Then, wherever you want errors to be shown in your views, something like:
= render 'shared/error_messages', object: f.object

Note object in the method.  When you call, you could pass either an object instance from your controller or (in the above case), the object of a form builder.


text:
Q: Why doesn't Gran Turismo save on PSX for Mac? I'm playing Gran Turismo on my iBook g4, it works really well. I save my games all the time to both the digital memory cards when I'm quitting. However when I try to load a game  it says "No Save Files found" in each memory cards.
Why does this happen, is it possible to fix?
Computer: iBook g4 PowerPc g4 1.42 GHz

A: Really i never played gran turismo on the ibook but i think is about the ibook incapability to save on the memory card.Try save it on something else or switch the memory card(it might be him the cause just try another one)


text:
Q: Change jQuery daterange picker to disallow a date range if it contains disabled dates I have created a jQuery date range picker. I am able to select the dates ranges and show them in a textbox. Now what I need is, I need to disable certain dates and assign different classes to those dates.
E.g. I must be able to give class A to April 2, class B to April 4 etc.

I have tried the results I got while I googled but nothing helped. What I am trying to do is to pass some dates and classes that should be assigned to those dates. That class should be assigned to those dates plus I must have option to enable or disable those dates.
The next thing I am trying to do is if there is a disabled date in between 2 dates, then that range cannot be selected.
E.g. Suppose I want to select April 2 to April 7 and April 5 is a disabled date.
Then I could be able to select either April 2 to April 4 or April 6 to April 7.

That means only one range should be selectable. Please help to solve this.
Please find the fiddle here:

A: You have to create two arrays, one that maps the css Class with each Date you want to be disabled class:date, and one that maps the css class with the date you want to give a special class, and then:

*

*Inside beforeShowDay, check if the date is in the disabled dates array, and if you find it, use the associated class and return false, example: [false,"classA"], if not , check in the special array and return the class with true, else just do whatever you are doing right now.

*Inside onSelect, check if the selected range includes any of the dates in the array and act accordingly

*Then In the class:date array, you can add any class:date you desire to be disabled with its own class, and the code will handle it

Full working solution here.
Notes:

*

*The code disables the 22nd of April and the 15th of May (try playing with the dates)

*The code gives a special class to the 15th of April and the 10th of May.

*The css class is applies as a background-color on the td, it does't show properly, you will have to modify the picker's css for it to do

*Reference that hepled me provide this answer is here

A: You need to implement beforeShowDay and onSelect functions as shown in the following demo:
http://jsfiddle.net/salman/H3ra3/
The code may look daunting but it is not. The basics are as follows:
The dateConfig variable
The date information is stored in an associative array in which we store whether a date is selectable AND/OR its CSS class name.
beforeShowDay
Let date be the date for which the function was called
Let date1 be the date inside start date textbox
Let date2 be the date inside end date textbox

*

*If the date is unselectable then
return [false, date_class or ""]

*If user has chosen date1

*

*If user has chosen date2 and date is between date1 ...date2 then
return [true, selected_class]

*If date is less than date1 then
return [false, date_class or ""] (do not allow second date to be less than first date)

*If date is equal to date1 then
return [true, selected_class] (allow second date to be same as first)

*return [true, date_class or ""]
onSelect
Let date1 be the date inside start date textbox
Let date2 be the date inside end date textbox

*

*If user has chosen date1 and date2 then

*

*Iterate over all unselectable dates

*If an unselectable date is between date1 ...date2 then throw an error


text:
Q: calling a method in a class with listview I am new to android coding and was making a project with ListView.  I wrote a program that displays information in a text file in a listview. Right now I have my main file extending ListActivity and everything works.  The main file is calling another class

fileop.ReadFileAsList("Installed_packages.txt");

which reads each line of the text file.  What I want is to make this a method in a class called FileOperations and do exactly what it is doing now, but my main class in my other project Extends Activity and I do not know how to "call" Extend Listactivity AND Activity.  I don't think this can be done in Java probably for good reason.  Could anyone show me how I would/should refactor it? Main file followed by code below:
Bottom line I am trying to make this a method in fileop and move fileop to a new project where the main extends Activity and not ListActivity.
 MAIN:

package com.example.hellolistview;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HelloListViewActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, file));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                          Toast.LENGTH_SHORT).show();
             }
        });
    }
    static FileOperations fileop= new FileOperations();
    static final String[] file =fileop.ReadFileAsList("Installed_packages.txt");
    }

package com.example.hellolistview;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.os.Environment;
import android.util.Log;

public class FileOperations {

    public String[] ReadFileAsList(String fileName){
        try{
            File f = new File(Environment.getExternalStorageDirectory()
                + "/Nullwall/" + fileName);
            FileInputStream fileIS = new FileInputStream(f);
            BufferedReader buf = new BufferedReader(new InputStreamReader(
                    fileIS));
            StringBuilder DbLines = new StringBuilder();
            String line = buf.readLine();
            while (buf.readLine() != null)
                {
                DbLines.append(line);
                DbLines.append("\r\n");
                }
            String[] ListItems = DbLines.toString().split("\r\n");

            return ListItems;
            }

 catch (FileNotFoundException e) {

    e.printStackTrace();
    Log.e("FileOp_ReadFileAsList","File Not Found in ReadFileAsList()");

}
 catch (IOException e) {
        e.printStackTrace();
        Log.e("FileOp_ReadFileAsList","IOException in ReadFileAsList()");
    }
        Log.e("FileOp_ReadFileAsList","Probably an Error in ReadFileAsList()");
        return null;

}
}

EDIT:
My new Main file (Where I want to go):
package com.IPR2.viewlog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class Main extends Activity {
    private TextView tv;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        FileOperations fileOperations = new FileOperations();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        //fileOperations.ClearFile("Installed_packages.txt");
        ApplicationOperations.ListAllInstalledApplications(getApplicationContext());
        ReadFileAsList("Installed_packages.txt"); <--What Im trying to be able to do.  It wont let me

    }
    public String[] ReadFileAsList(String fileName){

}

A: you are calling the ReadFileAsList() method before onCreate().
this is not allowed.
change to the following:
public class HelloListViewActivity extends ListActivity {
    /** Called when the activity is first created. */

    static FileOperations fileop=null;
    static final String[] file=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.fileop = new FileOperations();
        this.file = fileop.ReadFileAsList("Installed_packages.txt");

   setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                        Toast.LENGTH_SHORT).show();
             }
        });
    }

    }


text:
Q: How to augment a class from an external library with own methods? I have some special cases that I need to test for in django. I am trying to extend the the existing django tests by writing my own test cases. Here is how I am currently doing it.
from django.tests import TestCase

# define my own method as a function
def assertOptionsEqual(self, first, second):
    # logic here
    pass

# Attach the method to the TestCase class. This feels inelegant!
TestCase.assertOptionsEqual = assertOptionsEqual

# tests go here
class KnownGoodInputs(TestCase):
    def test_good_options(self):
        self.assertOptionsEqual(...)

While this works, defining a method as a function with self as the first parameter and then attaching it to TestCase feels inelegant. Is there a better way of augmenting the TestCase class with my own methods? I can do this ...
class MyTestCase(TestCase):
    def assertOptionsEqual(self, first, second):
        ...

and use MyTestCase for all tests, but was wondering if there was a better alternative. Thanks!

A: I think you've covered both options.  You can either subclass or monkeypatch.  Typically, monkeypatching, actually changing the 3rd party class at runtime is frowned upon but depending on what change you need to make it may be the only way to work around a bug or make sure that every time that class is used it has your new method.
Since the only tests that use your method will be your tests monkeypatching is unnecessary and it's quite reasonable to subclass TestCase.  Typically you'd use monkeypatching when you needed to augment a method of a existing class.  For example, if you wanted calls to TestCase.assertEqual in your existing test cases to be augmented with logic to compare to Option objects you could monkeypatch TestCase.assertEqual to include your custom logic plus its normal logic by doing something like:
originalAssertEqual = TestCase.assertEqual
def newAssertEqual(self, first, second):
    result = originalAssertEqual(first, second)
    if isinstance(first, Option) and isinstance(second, Option):
        # do your custom comparison
    return result
TestCase.assertEqual = newAssertEqual

However, it seems that at least in this example that both subclasses and monkeypatches are unnecessary.
Assuming that the issue is that calling self.assertEqual(firstOptions, secondOptions) fails even though the Option instances are equal you don't need to write a new assertOptionsEqual method.  You probably just need your Option objects to define __eq__ properly.
So assuming that you've got:
class KnownGoodInputs(TestCase):
    def test_good_options(self):
        first, second = systemUnderTestGetOptions(...)
        self.assertOptionsEqual(first, second)

What are the classes of first and second above?
For all Python builtin types assertEqual should work.  For a custom Option class just do something like this:
class Option(object):
    def init(self):
        use_foo = False
        use_bar = True
def __eq__(self, other):
    if (self.use_foo == other.use_foo and
        self.use_bar == other.use_bar):
        return True
    return False

Then assuming that first and second are instances of Option you can write your test just as:
class KnownGoodInputs(TestCase):
    def test_good_options(self):
        first, second = systemUnderTestGetOptions(...)
        self.assertEqual(first, second)


text:
Q: regex - unrecognized escape sequence From: https://stackoverflow.com/a/959982/101055
I am trying to use:
using System.Text.RegularExpressions;

Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("goodName1", "asdf");
parameters.Add("goodName2", "qwerty");
string text = "this is my {goodName1} template {goodName2} string";
text = Regex.Replace(text, "\{(.+?)\}", m => parameters[m.Groups[1].Value]);

I get 2 build errors on \{(.+?)\}, on { and } exactly.

ERROR > Unrecognized escape sequence

What is wrong here?

A: try:
text = Regex.Replace(text, @"\{(.+?)\}", m => parameters[m.Groups[1].Value]);

A few more details.
The @ sign defines a Verbatim String Literal.  This basically says tells the compiler that the string in quotes is not escaped.  http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Optionally, you could have simply doubled up on the back slashes. e.g.:
text = Regex.Replace(text, "\\{(.+?)\\}", m => parameters[m.Groups[1].Value]);

But, IMHO, the @ sign is much more readable.

A: You need to double escape your \ characters so that they're a \ literal within the string, and not used as a string-level escape sequence.
"\\{(.+?)\\}"

Within the string, this has a value of \{(.+?)\}
Alternatively you can use the @"" literal:
@"\{(.+?)\}"

Which has an identical value.

When you need to add a newline to a string, you use an escape sequence, "\n". Strings literals use the \ as an escape character to assist in coding characters that don't exist on a standard keyboard, or are otherwise difficult to place within a string. Regular expressions require using the same \ character to escape special characters in the pattern. This means that the \ character must be escaped to be used as a literal value in the string, which is \\.

A: You can add an @ to escape an entire string, or you can put a double slash, \\ to escape each occurence.
Here is a good article on strings and escaping them from MSDN
An example from the article:
@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"


text:
Q: How to license my c# application
Possible Duplicate:
License for C# desktop application

I want to make my program lock after some days of trial use and if a user purchase a license, can use the program for some months.
I dont know a way to do this. An idea is to make a local temp key when the program is installed, and lock it after the days passed(the problem here is that user can change date and time of his computer.. the philosophy of the program is to be used online and offline, so i cant compare dates from my server to the computer).
And the other thing is, how to make a license service. I can generate lots of serial keys and then when a user pays i can give him a serial, and every time the program starts i can check if the serial is in my web service.
Am i in a good road?? Any suggestions?

A: If this application is written in C# and you want to write your own licencing functionality, you will first need to obfuscate the executable before it is deployed. This is to stop people reading your CIL code (stored in the .exe) with a disassembler.
To licence the software you will want to choose an encryption method. For such encryption a symmetric method is essentially equivalent to an asymmetric method (as you have to provide the key in any case). The encryption method can be chosen using
public enum EncryptionAlgorithm { Des = 1, Rc2, Rijndael, TripleDes };

for each of the methods and their details, see Wikipedia. The Rijndael encryption algorithm has been designed to replace the aging DES algorithm. Like DES, it is a block cipher. It uses 128-bit, 192-bit or 256-bit keys and is a good choice. In the following I will assume that you will not be storing the encryption key in the code (hard coded) but supply it in a separate file (a 'product key'); so you will supply two licence files the product key to enable decryption and the encrypted licence file.
Once you have chosen an encryption method, it is common-place to come up with a hash or algorithm to work on the product key/initialisation vector (IV); you take a 128-bit key (for example) and scramble it using some method/transform. The key (that is randomly/pseudo-randomly generated for each user you deploy the software to) is then used to generate the IV.
You then use the 'random' key, the IV and the selected encryption method to encrypt some licence text (that includes licence dates).
internal ICryptoTransform GetCryptoServiceProvider(byte[] bK, byte[] iVec){ ... }

To decrypt the file using your method you essentially perform the reverse process. One thing to note about licencing, is that you should not spend too much time worrying about people cracking the software. Make it very hard using a method like the above, but don't invest too much time coming up with an ever increasingly complex methodology because if some (admittedly very talented) hacker wants to crack your code it is likely he will. Moreover, you have to assume the user will not break the law and share licence files! I cannot comment from experience on using an external company to run the licencing of your code (I have always written my own), however it is likely to be an expensive option.
I hope this is of some help.

A: Although it highly depends on your exact requirements, target technology (Winforms, WPF, Silverlight etc...) I would suggest using a third party licensing component such as Quick License Manager, Licensing Pro dotNet.
While rolling your own solution is going to be cheaper, the possibility of it being cracked or circumvented is much higher. To use a third party solution means you have an external team or company dedicated to keeping the licensing model secure and more reliable.
Best regards,


text:
Q: How to type a Tuple with type inference in Typescript I'm trying to write the type signature of a function that replaces the values of an object with a list of changes to the object.
I'm having trouble finding the most accurate type for the function.
The function in question is:
export const patchObjFn = (
    defaultVal: any
) => <T extends object, K extends keyof T> (
    changeObj: Replacement<T>[] | Replacement<T>,
    moddingObj: T
) => {
    const moddedObj = cloned(moddingObj);
    const isSingleElement = changeObj.length !== 0
        && (changeObj.length === 1 || changeObj.length === 2)
        && !Array.isArray(changeObj[0]);
    const changes = isSingleElement
        ? [changeObj] as ([K] | [K, T[K]])[]
        : changeObj  as ([K] | [K, T[K]])[];
    for (const change of changes) {
        const [propName, val] = change.length === 1
            ? [change[0], defaultVal]
            : change;
        moddedObj[propName] = val;
    }
    return moddedObj;
};

And the type I've reached is:
export type Replacement<T extends object, K extends keyof T> = [K] | [K, T[K]];

But this doesn't really work, since if K is 'hello' | 'world' and T is { hello: string; world: number; }, we can pass in ['hello', 42].
I would like to prevent this, but am unsure how to do so.

A: I'm going to address just the typings and not the implementation. It's possible that this typing will cause some errors to appear inside your implementation; if so, it is likely that either you can change your implementation to appease the compiler or you can assert that your implementation matches the signature.  In either case, the question seems to be about how to prevent callers from passing mismatched key/value pairs, and not what's going on inside the function implementation.
I'm also going to ignore the defaultVal parameter and the curried function that takes it, because it complicates things trying to figure out just what type of object can possibly take a single default value for all its properties.   If T is { hello: string; world: number; } and I pass in [["hello"],["world"]], is defaultVal somehow both a string and a number?    As I said, I'm ignoring that.

So we'll come up with the signature of a function patch which takes an object of generic type T and a list of replacement key-value tuples appropriate to T, and returns a result also of type T:
declare function patch<T extends object>(
  t: T,
  kvTuples: Array<{ [K in keyof T]: [K, T[K]?] }[keyof T]> | []
): T;

The interesting part is the type of the kvTuples parameter.  Let's take care of that | [] at the end, there, first.  All this does is give the compiler a hint to interpret kvTuples as a tuple and not as a plain array.  If you leave that off it won't change which inputs are accepted or not accepted, but the error messages will become completely incomprehensible as the entire input array will be flagged as wrong:
patch({ a: "hey", b: 1, c: true }, [
  ["a", "okay"], // error!
  ["b", false], // error!
  ["c", true] // error!
]);
// string is not assignable to "a" | "b" | "c"

In the above, the ["b", false] is the wrong entry, as the type of the b property should be number.  What you get though is a lot of errors that don't really point you to what you should be fixing.
Anyway, kvTuples is an Array<Something> where Something is a mapped type we do a lookup into.  Let's examine that type.  {[K in keyof T]: [K, T[K]?]} takes each property of T and turns it into a pair of key-value types (with the second element being optional).
So if T is {a: string, b: number, c: boolean}, then the mapped type is {a: ["a", string?], b: ["b", number?], c: ["c", boolean?]}.  Then we use a lookup type to get the union of property value types.  So if we call the mapped type M, we are doing M[keyof T] or M["a" | "b" | "c"] or M["a"] | M["b"] | M["c"] or ["a", string?] | ["b", number?] | ["c", boolean?].  And that's the type we want for each element of the kvTuples.
Let's try it:
patch({ a: "hey", b: 1, c: true }, [
  ["a", "okay"],
  ["b", false], // error!
  ["c", true]
]);

The error shows up in a reasonable place at least.  Less reasonable is the error message you get.  The following is at least vaguely okay:
// Type '(string | boolean)[]' is not assignable to type
// '["a", (string | undefined)?] | ["b", (number | undefined)?] |
// ["c", (boolean | undefined)?]'.

Since it didn't type check, the compiler is apparently saying that ["c", 7] is of type (string | number)[], which doesn't match the union of tuples.  That's true enough, but it yields an unfortunate last-line of the error message:
// Property "0" is missing  in type '(string | boolean)[]'
// but required in type '["c", (boolean | undefined)?]'

That's not helpful, especially since it's talking about "c" for what seems like no reason to the user.  Still, at least the error shows up in the right place.  It is undoubtedly possible to make the error even more sensible, at the expense of more complexity in the signature of patch, which I fear is already complicated enough.
Okay, hope that helps.  Good luck!
Link to code


text:
Q: Magento 2 Block Template Path I'm getting this error trying to create a .phtml template.
1 exception(s):
Exception #0 (Magento\Framework\Exception\ValidatorException): Invalid template file: 'CleverSoft_Base::images_dimensions_chart.phtml' in module: '' block's name: 'magento\framework\view\element\template_0'
I don't understand the two :: after CleverSoft_Base what does those two dots stand for and what should be the path in my child theme for the overwrite?

A: If you're overwriting a template your have to set your own module
Vendor_Module::images_dimensions_chart.phtml

the base-path for frontend templates in your module is always Vendor/Module/view/frontend/templates


text:
Q: Delete Insert operation depending on the record I am inserting a record into database which updates after every 4 hours
The row has almost 30 columns and I am not sure how much columns will be changed it can be 4 to 28 columns. the only 2 columns remain the same i.e. codeand name
What I am doing at the moment is first finding the row depending on the code if row exists then delete it first and then insert it again with new data. Otherwise the new row will be inserted.
Is there a better way to execute this?

A: you can just update it if code exists so that you can do only one operation(Updating) instead of two(deleting,inserting).

A: Why don't you first check if your record exists and then update or insert accordingly ?
if exists(select * from MyTable where Code = @Code)

  update MyTable set Col1 = @Col1, Col2 = @Col2, Col3 = @Col3
  where Code = @Code;

else

  insert MyTable (Code, Col1, Col2, Col3)
         values (@Code, @Col1, @Col2, @Col3);

A: The merge statement is your friend, it can handle all three cases.
In you case, you have to handle only 2: WHEN MATCHED and WHEN NOT MATCHED BY TARGET
MERGE INTO MyTable AS DST
USING (
SELECT
    @Code AS Code
  , @Col1Value AS Col1
  , @Col2Value AS Col2
) AS SRC
  ON SRC.Code = DST.Code
WHEN MATCHED THEN
  UPDATE SET DST.Col1 = SRC.Col1, DST.Col2 = SRC.Col2
WHEN NOT MATCHED BY TARGET THEN
  INSERT (Code, Col1, Col2)
  VALUES (SRC.Code, SRC.Col1, SRC.Col2)
;

The MERGE statement is available since SQL Server 2008.
Docs: https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql


text:
Q: Smallest maximal matching in $K_{p_1,p_2,p_3,p_4,p_5}$ Suppose $0<p_1\leq p_2\leq p_3\leq p_4\leq p_5$ are integers. Find the size of a smallest maximal matching in $K_{p_1,p_2,p_3,p_4,p_5}$ in terms of $p_1,p_2,p_3,p_4,p_5$.
I have attempted to solve this but made no substantial progress.  I do know that a maximal matching must saturate 4 out of 5 of the independent sets of vertices. If $p_1+p_2+p_3\leq p_4$ then it is easy to see that there is a maximal matching of size $p_4$, and by the previous comment this is a smallest maximal matching. But I do not know about the other case, or if splitting into cases is even necessary.

A: Hint:

*

*You won't be able to discard more than $p_5$, because that would mean that you have at least one unmatched vertex in at least two different partitions.

*Beacuse of parity there might be some $+1$'s or $-1$'s or $\lceil x/2\rceil$, etc.

*In which cases you can find a way to use all (but perhaps one) vertices of $p_1, p_2, p_3, p_4$?

I hope this helps $\ddot\smile$

A: Here is the solution I just discovered. I would still like to see other solutions!
Case 1: $p_1+p_2+p_3\leq p_4$. Then $p_4$ is the size of a smallest maximal matching (see my original post).
Case 2: $p_1+p_2+p_3\geq p_4$. Then $\left \lceil{(p_1+p_2+p_3+p_4)/2}\right \rceil$ is the size of a smallest maximal matching. Every maximal matching must have size at least $\left \lceil{(p_1+p_2+p_3+p_4)/2}\right \rceil$, since at least $p_1+p_2+p_3+p_4$ vertices must be saturated. Now we show that such a maximal matching is possible. Start with a bipartition  with $p_4$ on the left and $p_1+p_2+p_3$ on the right. Since $$p_1+p_3\leq (p_1+p_2+p_3+p_4)/2,$$ it is possible to move some of $p_2$ to the left so that the right side has size $\left \lceil{(p_1+p_2+p_3+p_4)/2}\right \rceil $. I can match the part of $p_2$ that moved with part of $p_3$, and then match $p_4$ with the rest of the right side (this is easier to see if you draw a picture).  There is possibly one vertex remaining on the right side, which I can connect to something in $p_5$. Now I have a matching which saturates $p_1$ through $p_4$ (so is maximal), and has size $\left \lceil{(p_1+p_2+p_3+p_4)/2}\right \rceil$.
Note: If $p_1+p_2+p_3=p_4$ then $p_4=\left \lceil{(p_1+p_2+p_3+p_4)/2}\right \rceil$, so it seems that my answers are consistent.


text:
Q: How to Identify Publishers and Consumers using Red5 API public boolean connect(IConnection conn, IScope scope, Object[] params)
    {
            IClient client = conn.getClient();
            log.info( "app connect " + conn.getClient().getId() );
            client.setAttribute( "stamp", new Long( 0 ) );
        return true;
    }

This is the method which is being called every time Client is connected at my Custom Application in Red5 Server ,so is there a way to identify if a Client is Subscriber (Consumer ,Viewer) or Publisher (User which streams at my server).
Bests

A: To disallow or allow publish or subscribe a user, you can use those methods inside appStart callback method:

*

*registerStreamPlaybackSecurity

*registerStreamPublishSecurity

For more, look to the:
http://dl.fancycode.com/red5/api/org/red5/server/adapter/MultiThreadedApplicationAdapter.html
I'm using jRuby, and it's very easy to do so:
registerStreamPlaybackSecurity do |scope, name, start, len, flush|
  false # no playback allowed
end
registerStreamPublishSecurity do |scope, name, mode|
  rand(1) % 1 == 0 # publishing (recording) sometimes allowed, sometimes no
end


text:
Q: Firefox: Not clickable inside CSS3 cube You can click on the left, right and back side. The click effect is working fine in Chrome, Safari and Opera. But it doesn't work with Firefox. It only detects the .cube class and not .right, .left or .back.

/**
 * Click effects
 */
(function clickEffects() {
    $(".left").click(function() {
        $(this).toggleClass("left-toggle");
        $(".only-text").toggleClass("sb-thumb-colored");
    }).find("input").click(function(e) {
        return false;
    });

    $(".right").click(function() {
        $(this).toggleClass("right-toggle");
        $(this).children("div").children("div:nth-of-type(2)").toggleClass("sb-thumb-colored");
    }).find("input").click(function(e) {
        return false;
    });

    $(".back").click(function() {
        $(this).toggleClass("back-toggle");
        $(this).children("div").children("div:nth-of-type(2)").toggleClass("sb-thumb-colored");
    }).find("input").click(function(e) {
        return false;
    });
})();

/**
 * Adjust top, bottom and back
 */
(function() {
    function resize() {
        var top = document.getElementById("top");
        var bottom = document.getElementById("bottom");
        var left = document.getElementById("left");
        var back = document.getElementById("back");

        var w = parseInt(window.getComputedStyle(left, null).getPropertyValue("width"));
        var h = parseInt(window.getComputedStyle(left, null).getPropertyValue("height"));

        top.style.height = w + "px";
        bottom.style.top = h + "px";
        bottom.style.height = w + "px";
        back.style.transform = "translateZ(" + (w * (-1)) + "px" + ")";
    }

    resize();
    window.addEventListener("resize", resize);
})();
* {
    box-sizing: border-box;
}

html,
body {
    width: 100%;
    height: 100%;
    margin: 0;
}

.wrap {
    color: white;
    font-size: 18px;
    perspective: 500px;
    perspective-origin: 50% 50%;
    width: inherit;
    height: inherit;
    width: 100%;
    height: 100%;
}

.cube {
    position: relative;
    transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
    width: 100%;
    height: 100%;
}

.cube > div {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    background: darkgrey;
    border: 3px solid brown;
}

.cube > div:not(.bottom):not(.top) {
    padding: 30px 60px;
}

.cube > .front {
    display: none;
}

.back {
    transform: translateZ(-1400px);
    -webkit-transform: translateZ(-1400px);
    transition: all 0.2s ease-in;
}

.back-toggle {
    transform: translateZ(0px) !important;
    -webkit-transform: translateZ(0px) !important;
}

.left {
    transform: rotateY(90deg);
    -webkit-transform: rotateY(90deg);
    transform-origin: left center;
    -webkit-transform-origin: left center;
    transition: all 0.2s ease-in;
}

.left-toggle {
    transform: rotateY(0deg);
    -webkit-transform: rotateY(0deg);
}

.right {
    transform-origin: right top;
    -webkit-transform-origin: right top;
    transform: rotateY(-90deg);
    -webkit-transform: rotateY(-90deg);
    transition: all 0.2s ease-in;
}

.right-toggle {
    transform: rotateY(0deg);
    -webkit-transform: rotateY(0deg);
}

.bottom {
    transform: rotateX(-90deg);
    -webkit-transform: rotateX(-90deg);
    transform-origin: top;
    -webkit-transform-origin: top;
}

.top {
    transform-origin: top;
    -webkit-transform-origin: top;
    transform: rotateX(-90deg);
    -webkit-transform: rotateX(-90deg);
}

.front {
    transform: translateZ(100px);
    -webkit-transform: translateZ(100px);
    pointer-events: none;
}

front

back

bottom

top

left

right

JSFiddle
How can this be solved?


text:
Q: How do I delay creation of a text file until I actually write a line to it? (lazy creation) I have a perl script  that append text on a file :
open (EXFILE, ">>$outFile");

at the moment of the open an empty file is created, i want to avoid this. I want that the file will be created only the first time that a line is written to the file handle :
print EXFILE $line

If nothing is written to the file handle the file should not be created ...
Is it possible ? How ?

A: Create a sub that does the opening for you.
sub myappend {
    my ($fname, @args) = @_;
    open my $fh, '>>', $fname or die $!;
    print $fh @args;
    close $fh or die $!;
}

myappend($outfile, $line);

Alternatively, instead of printing, push onto an array and wait until the end to print.
while ( ... ) {
    push @print, $line;
}

if (@print) {
    open my $fh, '>>', $outfile or die $!;
    print $fh @print;
}

Or, for multiple files
while ( ... ) {
    push @{$print{$outfile}}, $line;
}

for my $key (%print) {
    open my $fh, '>>', $key or die $!;
    print $fh @{$print{$key}};
}

A: I was thinking, what would be the simplest object that would print out to the file when it was about to be destroyed.
package My::Append; use strict; use warnings;

sub new {
  my($class,$filename) = @_;
  my $self = bless {
    filename => $filename,
  }, $class;
  return $self;
}

sub append{
  my $self = shift;
  push @{ $self->{elem} }, @_;
  return scalar @_;
}

sub append_line{
  my $self = shift;
  push @{ $self->{elem} }, map { "$_\n" } @_;
  return scalar @_;
}

sub filename{
  my($self) = @_;
  return $self->{filename};
}

sub DESTROY{
  my($self) = @_;
  open my $fh, '>>', $self->filename or die $!;
  print {$fh} $_ for @{ $self->{elem} };
  close $fh or die $!;
}

Used like this:
{
  my $app = My::Append->new('test.out');
  $app->append_line(qw'one two three');
} # writes to file here

A: How about something like this:
#!/usr/bin/env perl

use strict;
use warnings;

my $fh;

sub myprint {
  unless ($fh) {
    open $fh, '>', 'filename';
  }
  print $fh @_;
}

myprint "Stuff"; # opens handle and prints
myprint "More stuff"; # prints

N.B. not tested, but should work


text:
Q: Cannot use computer after Linux mint goes to hibernate I am running Linux Mint on my Laptop (MacBook Pro 2015 dual booting with Yosemite) however when I put my lid down I have the setting set to 'Hibernate'. The issue is when I put the lid down I cannot seem to wake the computer up again, all I get is a blank screen. I have tried to click the trackpad and type random letters on the keyboard (even tried the power button) but nothing works. The only response I get when I wake the computer up is a 'click' from the ForceTouch trackpad when I press on it.
Would I need to install some drivers or something to prevent this issue? If so what do I do to install it. If not what are the steps required to prevent the 'black screen of death' when waking my computer up from hibernation mode.

Here are my Error Logs:
kern.log
pm-powersave
pm-suspend.log
syslog

A: A workaround for the problem is to disable any action which is triggered by closing the lid.  This can usually be set in the power options in your system settings interface.  You also need to make sure that the display automatically dims while idle, and that the computer does not auto-suspend after a certain period of time.
On modern computers (especially with ULV CPU) with low power consumption leaving the computer on does not take a lot of power at all.  Therefore you should be OK with this.  Exceptions are only a few websites (open web pages which make JavaScript or other computations without user interaction), you can try this out by running the command top in a terminal window (on newer systems top -o %CPU gives you better visibility of CPU-hungry processes).  There you can see whether a process like firefox is hogging a lot of CPU (like 50%) or the computer it is idling (no process over 10% or so).
This worked for myself on a similar machine, avoiding the crashes when suspend was tried and failed.