text:
Q: Semantic search on Stack Exchange I love this website and I'd like it to be more powerful.
Tags are the closest concept to semantic search, but it's impossible to search inside tag descriptions.
For example, if you search in "Type to find tags" the keyword "reputation", you're not going to get the tags "voting", "bounty", "flair", etc. which are all relevant terms. It's like a search engine that only searches pages titles.
Tag synonyms are another semantic idea  but it would be better to create a semantic network that represents the relationships among keywords. An example is WordNet: http://wordnetweb.princeton.edu/perl/webwn


text:
Q: Is any (basis or non-basis) vector in essence always a linear combination of standard basis vectors? Is it true that the vectors in the basis of any vector space are always coordinate vectors with respect to the standard basis of the (possibly larger) vector space we are working in? And by extension is it true then that any "vector" in said vector space is in essence the coordinate vector with respect to the standard basis? And further, is the standard basis always a basis where the coordinate vector with respect to the standard basis (in this case, itself), of any vector in it, is that same coordinate-vector? (Because it seems like the coordinates of all basis-vector in a non-standard basis with respect to the standard basis will never all be the same as that vector's coordinate to its own basis, which is just a vector with one entry of one and all others zero, but I'll have to prove that another day.)
For example, take bases $ \{(1,0),(0,1)\} $ and $ \{(1,1),(0,1)\} $ (brackets aren't rendering in my preview, don't know why) for $\mathbb R^2$. The 4 vectors in both bases themselves are coordinates for $\mathbb R^2$, that tell you how to scale some other basis-vectors to find what they represent. (The question is if these "other vectors" are the standard basis vectors. I think they need to exist and be the standard basis vectors because otherwise things wouldn't make sense, but it's hard to explain that.) We all know that $(1,0)$ means "go one step to the right and zero up," or "scale your first basis vector by one and your second by zero." But if your basis vectors in essence weren't measured relative to the standard basis, we would end up in an infinite regress, because you could ask "well what is the basis of your basis-vectors?" "It could as well be anything!", right?
Suppose we take the "vector" with "coordinate-vector $(5,2)$ with respect to the second basis", then we're really talking about $5(1,1)+2(0,1)=$ $(5,7)$, where $(5,7)$ says "go five right and seven up and then you end up at the essence of that vector", right?
By further extension, is it true then that an $n$-tuple (vector) in an $n$-dimensional vector space is actually an $\infty$-tuple in an $\infty$-dimensional vector space but where we just focus on the $n$ relevant components and leave out all the $0$'s?
For clarity, what I mean by "coordinate vector" is: suppose we have basis $\beta=\{b_1,\ldots,b_n\}$ for vector space $(\mathbb F,V,+)$ with $\dim V=n$. Then there exists a function $\text{co}_\beta:$ $V\rightarrow\mathbb F^n:$ $\sum_{k=1}^n\lambda_kb_k\mapsto(\lambda_1,\ldots,\lambda_n)$ that maps a vector to an n-tuple with its coordinates with respect to $\beta$.
I've found similar questions on here but not exactly the same I think. I'm sorry that I couldn't formulate my question better, I did my best. Edit: I may have sort of answered my own question here during edits, so I'm sorry if that inappropriate as it may have switched the original post from "question" status to more of a "discussion" status. The question would still be if anyone can clear this up 100%.

A: In a general vector space, there is no "standard" / "canonical" basis.
Only in $F^n$ (as a space over F) you have such thing.

*

*Think of the space of all continuous functions, for instance.

*Or the tangent space to a sphere in a given point.

*Or all polynomial $P$ of order three such that $P(1) = 0$.

*Or a k-dimensional subspace of $F^n$,

*...

You can choose many good bases suited for your application, but not a canonical choice.

A: You say "it's hard to explain". So let's take an example to try to explain. You briefly recalled what a vector space is over a field $\mathbb F$.
Let us limit ourselves to real vector spaces $(\mathbb F=\Bbb R)$. Let's take $V=\mathcal{F}(\Bbb R,\Bbb R)$[you can add two functions and multiply a function by a scalar and all the axioms of a vector space hold]. But here no "standard basis".
Let's see what happens when we limit ourselves to the vector subspace $W$ of $V$ composed of the polynomial functions($x\mapsto \frac73x-\pi x^{942}, x\mapsto x^2+1, x\mapsto x+\sqrt2,... $ are vectors of $W$). Here we can try to talk about the basis $$(1,X,X^2,...X^n,...)$$
where, for $n \in \mathbb N, X^n$ denotes the vector $\mathbb R \to \mathbb R, x\mapsto x^n$.
For example, what you said "for clarity" applies here for the subspace $W_{n-1}(n>1)$ of polynomials of degree less than or equal to $n-1$, with $\beta=\{1,X,...X^{n-1}\}$ for example.
Consider $W_1=span(1,X)=\{f\in \mathcal{F}(\Bbb R,\mathbb R):\exists a_0,a_1 \in \Bbb R, \forall x \in \Bbb R, f(x)=a_0+a_1 x \}$
Take basis $\{1+X,X\}$. The vector whose coordinates in this second basis are $5$ and $2$, is $5(1+X)+2X=5+7X$ or more simply $x\mapsto 5+7x$.
In my view, the question is not: is this correct? The question is: what is it for?
I suggest the following illustration (there are a multitude of them):
Let $f \in W_n$ for some $n>1$. Let $\alpha \in \Bbb R$. Then there are elements $c_0,...,c_n $such that$$f(x)=c_0+c_1(x-\alpha)+...+(x-\alpha)^n$$
Let $(Y^k)_{k \in [\![0,n]\!]}$ defined by $Y^k=(X-\alpha)^k$. $(Y^k)_{k \in [\![0,n]\!]}$ is a new basis for $W_n$.
What is it for ? Note that we have $f(\alpha)=c_0$. Hence, if $f(\alpha)=0, c_0=0$ and we can write $$f(x)=(x-\alpha)h(x)$$
expression in which we can still write$$h(x)=d_1+d_2(x-\alpha)+...+d_n(x-\alpha)^{n-1}$$
And so on... The important thing is that it is useful for something in mathematics.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When to use Test="F" or Test="Chisq" when comparing regression models? I would like to understand when to use either the test="F" or test="Chisq" options when comparing regression models with the ANOVA function.
In my class, we have been using test="Chisq" on all logistic regression problems but now I have a case that is linear regression. When I try comparing the two tests with test="Chisq" I no longer get a test statistic.
Do I understand correctly that I need to use test="Chisq" for logistic regression and test="F" for linear regression?
I am comparing two models now (both linear regression models) and the output of the anova test where test="Chisq" only provides res.df, RSS, Df, Sum of Sq, and Pr(>Chi).
Does this mean I need to do test="F" when I don't see a test statistic?


text:
Q: Rails undefined method 'full_name' I have this error, when I'am testing my controller
ActionView::Template::Error: undefined method `full_name' for nil:NilClass

My tests:
class PostsControllerTest < ActionController::TestCase
include Devise::TestHelpers

setup do
    @post = Post.create!(title: "my title", content: "bla bla bla")
    user = User.create!(email: "example@mail.com", first_name: "name", last_name: "surename",
                    password: "password", password_confirmation: "password")
    sign_in user
end

test "should show post" do
    get :show, id: @post
    assert_response :success
end

full_name method in model:
def full_name
  "#{first_name} #{last_name}"
end

and my view:
Wrote by
  = @post.user.full_name

Thanks for help

A: As per your requirement, each post must be associate with user so you must belongs_to association in post model. something like:
belongs_to :user

And in User model, like:
has_many :posts

Then your code should like:
setup do
  user = User.create!(email: "example@mail.com",
         first_name: "name", last_name: "surename",
         password: "password", password_confirmation: "password")
  @post = user.posts.create!(title: "my title", content: "bla bla bla")
  sign_in user
end


text:
Q: Augmenting the title of a JqxDocking window I was looking at the documentation for the JqxDocking Angular component, located here: https://www.jqwidgets.com/angular-components-documentation/documentation/jqxdocking/angular-docking-api.htm?search=
I was trying to find a means to dynamically edit containers in a JqxDocking Component
The issue I currently have is that a window cannot have a title assigned a property.

{{title}}

which creates issues when it comes to localization.  I cant abstract away the string to say:

{{ title | translate }}

Below is a sample I was working with.
<jqxDocking #docking [orientation]='"horizontal"' [width]="'100%'" [mode]="'docked'" [theme]="'dark'">

My Title!

Sample Content!

</jqxDocking>

The above works to display a little container.  The issue I have run into like i said was localization.  So it i wanted do either assign it to a property, OR translate it with a pipe, it will not work.
class MyComponent implements OnInit {
    title: string = "My Title"
    @ViewChild('docking') jqxDocking: jqxDockingComponent;
    constructor(private translate: TranslationService){}
    ngOnInit(){}
}

and in the markup, would update from
My Title!
 to
{{title}}

It seems that what may be happening is the the Docking Component uses the information on load but never subscribes to anything, so once it is set, it is set.
This does not work for me as I need to have it be more dynamic.
I was hoping there was a property I could leverage, or a method such that I could look up and augment the Windows currently leveraged JqxDocking.
Has anyone encountered similar and how did you resolve it?

A: Since the Dom structure is required, you wont be able to add components, as much as add directives, since a component will adjust the dom.
On a per component basis though, I created a setter/getter for the input title string.
@Input() set title (value : string){
  this._title = value;
  this._setText();
}
get title () { return this._title; }
_title: string = "";

private _setText() {
  this.host.nativeElement.children[0].textContent = this.translate.instant(this._title);
}

constructor(private host: ElementRef, private translate: TranslateService) { }

That way, the correct location is updated, and it happens whenever the title changes.


text:
Q: Host vs Origin header for CORS preflight request with Spring Boot & Zuul I'm using Zuul with Spring Cloud Camden SR5 and Spring Boot 1.4.4.RELEASE
My frontend is React.js application served by a Node Express server. My API is behind zuul.
The frontend can be accessed via https://test.mydomain.com and the API (Zuul) via https://api-test.mydomain.com
In Zuul I do have a CORS filter that sets the CORS header (properly ?):
if(corsAllowedOrigin.contains(host)){
        log.debug("{} is allowed", origin);
        response.setHeader("Access-Control-Allow-Origin", origin);
    }
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
chain.doFilter(req, res);

With React.js I use Fetch to make HTTP calls to the API.
Before each GET or POST request, the browser does an OPTIONS request with the following headers:

*

*Host: api-test.mydomain.com

*Origin: https://test.mydomain.com
When I was using Spring Cloud Brixton.SR6 and Spring Boot 1.3.4.RELEASE that worked fine.
Now however I'm getting a 403 and the error message is Invalid CORS request.
Using a REST client I noticed that if I change the headers so that Host == Origin then I'm getting a 200 OK
From the CORS spec I could find:

In addition to checking the Origin header, resource authors are strongly encouraged to also check the Host header. That is, make sure that the host name provided by that header matches the host name of the server on which the resource resides. This will provide protection against DNS rebinding attacks.

Is that the reason why I'm now getting a 403? How can I my API running on a different host without failing the OPTIONS requests?
Update
It seems I can solve the problem if I add CORS filter to each individual service behind the edge service. That is if I make sure the Access-Control-Allow-Origin header is populated by each service.
Before the update I only had a CORS filter on my edge service (Zuul) and I thought it was the way to go. Surely it seems wasteful if I need to configure CORS for each service? Is that the way to go?

A: For some reason it seems to work if I use the CORS filter offered by Spring (org.springframework.web.filter.CorsFilter.CorsFilter):
@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}


text:
Q: ClassNotFoundException while using Google Map V2 in Android Log Cat
03-11 09:43:55.428: E/dalvikvm(1518): Could not find class 'com.google.android.gms.maps.MapFragment', referenced from method com.example.mapdemo2.MapDemo2.onCreate
03-11 09:43:55.428: W/dalvikvm(1518): VFY: unable to resolve check-cast 696 (Lcom/google/android/gms/maps/MapFragment;) in Lcom/example/mapdemo2/MapDemo2;
03-11 09:43:55.498: D/dalvikvm(1518): VFY: replacing opcode 0x1f at 0x0013
03-11 09:43:55.908: D/AndroidRuntime(1518): Shutting down VM
03-11 09:43:55.908: W/dalvikvm(1518): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-11 09:43:55.958: E/AndroidRuntime(1518): FATAL EXCEPTION: main
03-11 09:43:55.958: E/AndroidRuntime(1518): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mapdemo2/com.example.mapdemo2.MapDemo2}: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.os.Looper.loop(Looper.java:137)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at java.lang.reflect.Method.invokeNative(Native Method)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at java.lang.reflect.Method.invoke(Method.java:525)
03-11 09:43:55.958: E/AndroidRuntime(1518):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mapdemo2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.google.android.maps" >
        </uses-library>

        <activity
            android:name="com.example.mapdemo2.MapDemo2"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAfdExXel00usxddAR-WtSJ0FMcXzSMERA" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" >
        </meta-data>
    </application>

</manifest>

Activity XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MapDemo2" >

    <fragment

        android:id="@+id/fragment1"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Java Code
package com.example.mapdemo2;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

public class MapDemo2 extends FragmentActivity {

    GoogleMap maps;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_demo2);
        SupportMapFragment mapFrag = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment1));
        maps = mapFrag.getMap();
        maps.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map_demo2, menu);
        return true;
    }

}

A: XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MapDemo2" >

<fragment

    android:id="@+id/fragment1"
    class="com.google.android.gms.maps.MapFragment"   <--- use MapFragment
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

Java Code
    MapFragment mapFrag = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1));
    maps = mapFrag.getMap();

A: Google introduced Google Play Services which has GoogleApiClient() to access maps and a lot of other features it support recently. I would recommend you to add a reference to the Google Play Services library project to your app project. Please see the following documentation to see how to make use of the Google Play Services using GoogleapiClient to access maps.
Please see this official documentation for code implementation.
Refer to this tutorial if you want to access Google Maps through Google Play Services.
Hope that Helps!!


text:
Q: How do I clear Bootstrap remote modal content on close? I am launching a modal with remote content (on the same domain, however). The modal can be opened several times with different content on the same page, so when it closes, I need it to clear the .modal-body part.
I tried to do it like this:
function close_modal()

{

    $('.modal').modal('hide');

    $('body').on('hidden.bs.modal', '.modal', function () {
        $(this).removeData('bs.modal');
    });

}

But for some reason the previous content is still visible for a split second when I open another modal target. I also checked the source code and the content loaded previously is still there. How do I fix this? Here is my markup:
$('a[rel=modal]').on('click', function(evt) {
    evt.preventDefault();
    var modal = $('#modal').modal();
    modal
        .find('.modal-body')
        .load($(this).attr('href'), function (responseText, textStatus) {
            if ( textStatus === 'success' ||
                 textStatus === 'notmodified')
            {
                modal.show();
            }
    });
});

and the HTML:

                <button type="button" class="close"
                  data-dismiss="modal" aria-hidden="true">

                </button>

A: You should be able to use jQuery's empty method to remove all child nodes from .modal-body:
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).find('.modal-body').empty();
});

A: One issue is that you aren't listening for the close until after you have already closed it. You have:
// Hide the modal
$('.modal').modal('hide');

// Start listening for the hide event, if the modal closes remove the data
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

Instead move either move the hide listener so it runs before the hide event (probably outside the function because it only needs to start listening once) or remove it and simply have $('.modal').removeData('bs.modal');

A: Assuming your modals aren't doing anything special, you might find it easier to use something like Bootbox.js, which generates your Bootstrap modal on the fly. Your code would look something like:
$('a[rel=modal]').on('click', function(evt) {
    evt.preventDefault();

    var url = $(this).attr('href');

    $.get(url)
        .done(function (response, status, jqxhr) {
            // store a reference to the bootbox object
            var dialog = bootbox.dialog({
                message: response
            });
        })
        .fail(function(jqxhr, status, error){
            /* Do something when the form can't be loaded */
        });
});


text:
Q: laravel @json automatically convert time from IST to GMT In my laravel project i have an array of created_at
    $dates = Lead::where('created_at', '>', now()->subDays(30)->endOfDay())
        ->orderby('created_at', 'desc')
        ->select('created_at')
        ->get()->toArray();

when i convert that array with @json($dates) in blade it automatically get converted from  IST to GMT. why is this happening? how do i prevent this ?


text:
Q: Compare based on values of previous compared variables? I want to implement Comparable for one of my class.
My test-Array: A1, A2, A3, B1, B2, B3
I want so sort like this:
-sorting by letter
-if A then ascending number
-if B then descending number
Outcome expected: A1, A2, A3, B3, B2, B1
The following code would always give me letter and numbers ascending, like A1, A2, A3, B1, B2, B3.
How can I switch the order of numbers based on which letter Foo has?
class Foo implements Comparable {
    String letter, int number;

    int compareTo(Foo f) {
        int x = letter.compareTo(f.letter);
        return x != 0 ? x : number.compareTo(f.number);
    }
}

A: You could do something like this:
int compareTo(Foo f) {
    int x = letter.compareTo(f.letter);
    return x != 0 ? x
         : letter.equals("A") ? number.compareTo(f.number)
                              : f.number.compareTo(number);
}

(That's assuming you want to treat all non-A values as descending, of course...)


text:
Q: Jquery copy to clipboard - how to ignore special css & jquery characters I am using ajax to request a unique string from my DB. This string must be copyed as it is, because an other tool can validate it.
The problem is I get an:
Error: Syntax error, unrecognized expression

Probably because there are symbols in this string which are recognized as css selectors or jquery operators.
Here is the code which I use to copy to clipboard:
function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

Here is my ajax code:
$.ajax({
    url : "/copy/pob-source/" + build_id,
    type : "get",
    contentType: 'application/json;charset=UTF-8',
    //data : {'data':$.trim($("#stats-string").text())},
    success : function(response) {
        copyToClipboard(response)
        console.log("success, data updated");
    },
    error : function(xhr) {
        console.log("updating data failed");
    }
});

In my ajax request I get the response which triggers the error:
copyToClipboard(response)

Here is the error output in the console:

So basically I am trying to find a solution, so the response is handled as a raw string.

A: Your copyToClipboard function expects to receive a DOM element as input. It wraps it as a jquery object, and tries to send its text() contents on the way to execCommand('copy').
What you're passing that function is not a DOM element, it's a raw AJAX response.  Here's a slightly modified demonstration of your code -- I changed it to a jsonp request so that the ajax call would work within a stack snippet:

function copyToClipboard(element) {
  //$(element).text() will be empty, because you're not passing it a DOM element, it's the full AJAX response:
  console.log($(element).text());
  console.log(element);
  var $temp = $("<input>");
  $("body").append($temp);

  //$temp.val($(element).text()).select(); // won't work
  $temp.val(element.query.results.channel.title).select(); // this will work, for this example JSON
  document.execCommand("copy");
  $temp.remove();
}

// random JSON url just so we can demo an ajax call
var apiUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"

$.ajax({
  url: apiUrl,
  dataType: "jsonp", // <-- changed from "get" just for demo
  contentType: 'application/json;charset=UTF-8',
  success: function(response) {
    copyToClipboard(response)
    console.log("success, data updated");
  },
  error: function(xhr) {
    console.log("updating data failed");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I'm not sure how you're getting that specific syntax error, but you should definitely doublecheck to see what you're passing to copyToClipboard, and modify the AJAX success() function to pass along only the data you actually want, instead of the full response object; and  modify copyToClipboard to expect to receive the desired data in the param instead of a DOM object as input.


text:
Q: Webdav Client on iOS caching I am working on a webdav client for iOS device, will NSURLConnection or ASIHTTPRequest help with caching directory listing of webdav, or will we have to load from the server everytime?
Thank for your help guys.

A: MKNetworkKit is an up and coming network kit for iOS 4+ that has built in caching for requests.


text:
Q: Querying by Key in Google App Engine? I need to get entity by user key that is setted as Id for User entity. Now I want to query all entities that have same key that user has. How can I do that?

A: Okey, now I found solution myself:
Query query = pm.newQuery(Entity.class, "user == userParam");
            query.declareParameters("com.google.appengine.api.datastore.Key userParam");


text:
Q: mysql exception when synchronizing db with django's manage.py script I am relatively new to django. I have defined my db schema and validated it  with no errors (manage.py validate reports 0 errors found).
Yet when I run ./manage.py syncdb
I get the following stack trace:
Creating table demo_foobar_one
Creating table demo_foobar_two
<snip>...</snip>
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 218, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 347, in handle
    return self.handle_noargs(**options)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/commands/syncdb.py", line 103, in handle_noargs
    emit_post_sync_signal(created_models, verbosity, interactive, db)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/sql.py", line 185, in emit_post_sync_signal
    interactive=interactive, db=db)
  File "/usr/local/lib/python2.6/dist-packages/django/dispatch/dispatcher.py", line 162, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/management/__init__.py", line 28, in create_permissions
    defaults={'name': name, 'content_type': ctype})
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 135, in get_or_create
    return self.get_query_set().get_or_create(**kwargs)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 373, in get_or_create
    obj.save(force_insert=True, using=self.db)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 435, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 528, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1479, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 783, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/mysql/base.py", line 86, in execute
    return self.cursor.execute(query, args)
  File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg/MySQLdb/cursors.py", line 176, in execute
    if not self._defer_warnings: self._warning_check()
  File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg/MySQLdb/cursors.py", line 92, in _warning_check
    warn(w[-1], self.Warning, 3)
_mysql_exceptions.Warning: Data truncated for column 'name' at row 1

I have checked (and double checked) my table schema. All name field are CharField type with maximum length = 64. The backend db I am using is MySQL, so I am sure that indexes can be created for strings of length 64.
What could be causing this error (I suspect it is a misleading error message - even though its coming from the db itself)...

A: The traceback is happening during the creation of a django.contrib.auth.Permission: some of these get created for your models automatically as part of syncdb.
Permission.name has max_length=50, so you probably have an application and/or model class with a really long name?
Try the following query in manage.py dbshell:
SELECT * FROM auth_permission WHERE LENGTH(name) = 50;

If you cannot change your model name, then you can fix this problem by reducing the length of the generated Permission.name by specifying verbose_name in the model Meta class (see here for more details):
class MyVeryLongModelNameThatIsBreakingMyMigration(models.Model):
    class Meta:
        verbose_name = 'my long model'

Update
There's an open (as of 2013) Django ticket to fix this:

*

*#8162 (Increase Permission.name max_length)

A: As Piet Delport noted, the problem is that your model name is too long.
You're certainly going to have to shorten your model name, and then clean up your database.  How you do that depends upon where you are in the development process.

*

*If this is a brand new application, with a dedicated database, and no actual data, the simple answer is to drop and recreate the database, and then re-run python manage.py syncdb.

*If you have other tables in the database that need to be left alone, but the tables for your Django have no 'real' data, and can thus be dropped without damage, then you can use manage.py sqlclear to generate SQL DDL to drop all of the Django-generated tables, constraints, and indexes.
Do the following:
apps="auth contenttypes sessions sites messages admin <myapp1> <myapp2>"
python manage.py sqlclear ${apps} > clear.sql

You can feed the generated script to mysql or python manage.py dbshell.  Once that's done, you can re-run python manage.py syncdb.

*If you have actual data in your database tables that can't be dropped or deleted: Slap yourself and repeat 100 times "I will never do development against a production database again.  I will always back up my databases before changing them."  Now you're going to have to hand-code SQL to change the affected table name, as well as anything else that references it and any references in the auth_permissions table and any other Django system tables.  Your actual steps will depend entirely upon the state of your database and tables.

A: I also got error like this one using postgresql django 1.2, but the problem was not the length, but using ugettext_lazy for translating the names. ('can_purge', _("Can purge")) is evidently unacceptable, since the name is stored in the database as text


text:
Q: Change the view element property based on ViewModel property change I would like to change the color of my Label in the view based on a type in my ViewModel. For ex:
My class in ViewModel has a bool property like following:
MyViewModel
{
public bool IsBlueColor {get; set;} //Here I will raise the `PropertyChanged`
}

How can I wrap a trigger for this value to update Foreground property of my label. All I could figure out was changing the property of UI element based on its on property using DataTrigger. But not based on viewmodel.
How can I achieve this in xaml?
Right now I am doing this:
<Label.Style>
    <Style TargetType="Label" BasedOn="{StaticResource LabelStyle}">
        <Style.Triggers>
            <DataTrigger   Binding="{Binding Path=IsBlueColor, RelativeSource={RelativeSource AncestorType={x:Type local2:MyViewModel}}}" Value="True">
                <Setter Property="Foreground" Value="RoyalBlue"/>
            </DataTrigger>
            <DataTrigger  Binding="{Binding Path=IsBlueColor, RelativeSource={RelativeSource AncestorType={x:Type local2:MyViewModel}}}" Value="False">
                <Setter Property="Foreground" Value="White"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Label.Style>

A: Change the style triggers to:
<Style.Triggers>
           <DataTrigger Binding="{Binding Path=IsBlueColor}" Value="True">
               <Setter Property="Foreground" Value="RoyalBlue"/>
           </DataTrigger>
           <DataTrigger  Binding="{Binding Path=IsBlueColor}" Value="False">
                <Setter Property="Foreground" Value="White"/>
           </DataTrigger>
</Style.Triggers>

Check implementation of INotifyPropertyChanged in ViewModel.
this works in a sample for me.
Sample :
class LabelViewModel:INPC
{
 public event PropertyChangedEventHandler PropertyChanged=new delegate{};
 bool _isBlueColor;
 public bool IsBlueColor
 {
  get
  {
    return _isBlueColor;
  }
  set
  {
    _isBlueColor=value;
    OnPropertyChange();
  }
}
public OnPropertyChange([CallerMemberName] string propname="")
{
  PropertyChanged.Invoke(this,ew PropertyChangedEventArgs(propname));
}

}

Create an instance of LabelViewModel(labelVM) & assign to label1.DataContext=labelVM;


text:
Q: run jasmine.js test as part of Maven 'test' goal I have the following jasmine tests configuration in my project pom.xml:
<pluginManagement>
      <plugins>
        <plugin>
        <groupId>com.github.searls</groupId>
        <artifactId>jasmine-maven-plugin</artifactId>
        <version>1.1.0</version>
        <executions>
          <execution>
            <goals>
              <goal>test</goal>
              <goal>jasmine</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <jsSrcDir>${basedir}/src/main/js</jsSrcDir>
           <sourceIncludes>
            <include>myCode.js</include>
          </sourceIncludes>
          <jsTestSrcDir>${basedir}src/test/js/specs</jsTestSrcDir>
          <specIncludes>
            <include>mySpec.js</include>
          </specIncludes>
        </configuration>
      </plugin>
...

with this configuraton I can run jsamine:test and the test wil run.
I want to run the tests as part of the goal test, but Maven won't run them.
I even tried removing the line <goal>jasmine</goal> but Maven still won't run the jasmine tests.
What am I doing wrong?

A: You must also add the execution of the plugin like this into you project:
<project>
  <build>
     <plugins>
        <plugin>
          <groupId>com.github.searls</groupId>
          <artifactId>jasmine-maven-plugin</artifactId>
        </plugin>
     </plugins>
  </build>
</project>

cause the one you've defined in pluginManagement does not really execute the plugin.


text:
Q: Flink KafkaSource read all messages from the topic My goal is reading all messages from Kafka topic using Flink KafkaSource. I tried to execute with batch and streaming modes. The problem is the following :
I have to use a Sink which contains bug when I set env.setParallelism higher than 2. Thus, I set for example:
streamExecutionEnvironment.setParallelism(1);
The Kafka topic that I want to consume contains 3 partitions.
This is a code snippet that I have:
KafkaSourceBuilder<Request> builder = KafkaSource.builder();
    builder.setBootstrapServers(kafkaBrokers);
    builder.setProperty("partition.discovery.interval.ms", "10000");
    builder.setTopics(topic);
    builder.setGroupId(groupId);
    builder.setBounded(OffsetsInitializer.latest());
    builder.setStartingOffsets(OffsetsInitializer.earliest());
    builder.setDeserializer(KafkaRecordDeserializationSchema.of(deserializer));

DataStreamSource<Request> streamSource = streamExecutionEnvironment.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");
    streamSource.map(new MyMapper())
            .addSink(new Sink(props)).setParallelism(3) //by this setting I expected to have exactly 3 consumers - per partition/split, but it doesn't work when I do not set anything as well
            .name("Flink " + context.getJobDetail().getKey());

This code is supposed to run within Spring Boot application that will be dockerized, I configured a quartz job that periodically will be executed and streamExecutionEnvironment is local environment :
 StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
At this point there are already messages within the topic, more than 10M.
When the job is executed I can see in the log:
    [ -> Map (1/1)#0] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=rrequest_consumer_test-0, groupId=request_consumer_test] Seeking to EARLIEST offset of partition request-2
INFO 7748 --- [ -> Map (1/1)#0] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=request_consumer_test-0, groupId=request_consumer_test] Seeking to EARLIEST offset of partition request-0
INFO 7748 --- [ -> Map (1/1)#0] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=request_consumer_test-0, groupId=request_consumer_test] Seeking to EARLIEST offset of partition request-1

Then they consume about 1M messages in total and stop consumption and for all of 3 I can see:
[ -> Map (1/1)#0] o.a.f.c.b.s.reader.fetcher.SplitFetcher  : Finished reading from splits [request-1]

Thus, they do not fully consume the topic, only part of it.
When quartz job is re-triggered, it again starts reading from OffsetsInitializer.earliest() , they consume duplicate messages but also new messages, not only newly added to the topic, but also some messages which weren't consumed during previous execution.
I have tried also renaming consumer groups in order to eliminate the problem with offsets in case if consumer committed after previous consumption.
My question is - how can I configure the data stream in order to fully read the topic. How my problem is related to setParallelism(1) setting or parallelism in general, consumer group configuration or anything else ?
Please give me any suggestion on troubleshooting the problem.

A: The problem is related to
builder.setBounded(OffsetsInitializer.latest());

This line tells Kafka to read messages to the last offset seen at the start of the job. It will then stop consuming more messages.


text:
Q: Converting strings Series to numeric one I'm doing
X = data['x'].apply(lambda h: [int(h[i:i + 2], 16) for i in (0, 2 ,4)])

Where x has strings of hex colors, and I'd like to map them to RGB arrays (3 values each). After that, X hasdtype='object, and X.values is a numpy array of numpy arrays.
My final goal is making it an 3 * n numpy array and use it with sklearn.cluster.KMeans. What is the best way to achieving this?

A: After creating X, you can split up the data into 3 columns like this
X = data['x'].apply(lambda h: [int(h[i:i + 2], 16) for i in (0, 2 ,4)])
data[['R','G','B']] = pd.DataFrame(X.values.tolist(), index=X.index)

so that
data[['R','G','B']]

has the result in three columns for further processing


text:
Q: PyOpengl without PyGame I see that all tutorials about the pyopengl implements pygame, is posible use PyOpengl without pygame?. and if is so, then, is most faster without pygame or not?

A: When using pygame with opengl, pygame will handle crossplatform: window creation, key input, sound output, image loading, etc..., but pyOpenGL does the actual rendering.
Pyglet has crossplatform window creation + opengl as well: http://www.pyglet.org/
I don't believe there's much of a speed difference, in using pygame vs other solutions. But the difference will be in how you do things, that will have the biggest effect. Using numpy vs not, calling expensive functions repeatedly, like: opengl's begin/end, etc.

A: PyGame's only relation to PyOpenGL is that PyGame can provide a window for PyOpenGL to render on.
Your question now is whether PyGame's windowing environment is faster than another.
In my experience, GLUT can be very slightly faster than PyGame for windowing (by comparing GLUT and SDL).  wxWidgets I think is a bit slower.  PyGlet isn't PyOpenGL (although it is a Python OpenGL implementation).
My recommendation: PyGame is easiest to use and provides helpful utilities besides.  Use it instead of anything else; any performance differences are negligible.
When you need better windowing support, go for Qt or wxWidgets, in that order.


text:
Q: Add wordpress post id to div I'm trying to add the post's id with the following

<?php the_ID(); ?>>

But its returning the following without the

Any ideas welcome

A: use this if you want to add id:
<div class="project-tile" id="post-<?php the_ID(); ?>">

result is:

A: You have a typo in your code. If your intention was to display the ID in the div it should be rather:

<?php the_ID(); ?>


text:
Q: How to wrap Zend_Form error message in custom html? I need to wrap zend form error messages in custom html.

            %ZEND_FORM_ERROR_MESSAGE%

Now I get errors in format:

Error message

I need:

Error message

Thank you!
I have following code:
        $element->clearDecorators();
        $element->removeDecorator('DtDdWrapper');
        $element->addDecorator('ViewHelper');
        $element->addDecorator('Description', array('tag' => 'p', 'class' => 'description'));
        $element->addDecorator('Label', array('tag' => null));
        $element->addDecorator(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'form-line'));

How to wrap errors in 3 div tags? Thank!

A:     $element->clearDecorators();
    $element->addDecorator('Errors');
    $element->addDecorator(array('div1' => 'HtmlTag'), array('tag' => 'div',
                    'class' => 'cerror', 'id' => 'EMAIL-error'));
    $element->addDecorator(array('div2' => 'HtmlTag'), array('tag' => 'div',
                    'class' => 'ui-widget'));
    $element->addDecorator(array('div3' => 'HtmlTag'), array('tag' => 'div',
                    'class' => 'ui-state-error ui-corner-all',
                    'id' => 'EMAIL-error-msg'));
    $element->addDecorator('ViewHelper');
    $element->addDecorator('Description', array('tag' => 'p', 'class' => 'description'));
    $element->addDecorator('Label', array('tag' => null));
    $element->addDecorator(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'form-line'));


text:
Q: Rspec/capybara - simulate switch from Online to offline within a test (webkit driver) I have a ruby on Rails 4 app.
A user loads a page (called deal_page) then he clicks on  a button which loads a Rails UJS modal message.
If he is online WHEN he clicks the button, I show a message using javascript offline status recognition (inside the Rails UJS ajax event).
on('ajax:error',function(event,xhr, status, error){
            var isOnLine = navigator.onLine;
            event.preventDefault();
            if (isOnLine) {
              //do stuff }
            else {
              // for disconnected users WHEN triggering call to server, invite to reconnect
              var msg;
              msg = Messenger().post({
                message:            "You lost internet,You need to be connected"
              });
            }

          });

I want to test in rspec/capybara (I use webkit driver) that the right content ("You need to be connected. Please connect and try again") is displayed in that case in my feature test.
context "As signed-in visitor who is OFFLINE line when he clicks on the area triggering the modal" do

it "displays the right message " do
        visit deal_page_path(deal)
        # HOW TO ASSERT THAT THE USER LOSES HIS INTERNET CONNECTION
        # USER GOES OFFLINE
        first("a#button").click
        within('ul.messenger') do
          expect(page).to have_content('You lost internet,You need to be connected')
        end
      end

  end

The complexity is that I can't disconnect him from the beginning of the test as he needs to be connected to load the page visit deal_page_path(deal) but then I want to simulate that he loses the internet connection.
How to achieve this ?

A: Assuming you're just checking window.naviagtor.onLine to determine whether or not it is on/offline (not depending on any events or anything) and because you're using capybara-webkit (won't work in selenium since FF won't let you overwrite navigator, not sure about poltergeist) you can just overwrite window.navigator  with the result you want to get. You'll also need to generate an error response for your ajax request, which you can do with puffing-billy
page.execute_script "window.navigator = { onLine: false }"


text:
Q: Whats the correct way to format X and Y from binnary dataframe to use on Stratified K-Fold cross-validation My data is an dataframe of a table of 25 columns and 2737 rows containg binnary data.
The goal is to train using each row as an INPUT and get as an OUTPUT a probabilistic prediction of what the next sequence could be.
Data on this scenario is always 10 number 0 and 15 number 1, or 10 False and 15 True.
First 5 rows from my dataframe is:
[[0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 0 1 0 0 1 1 1]
 [1 0 0 1 1 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 1 0]
 [1 0 0 1 0 1 1 1 1 1 1 1 0 1 0 1 1 0 0 1 0 0 1 1 0]
 [1 1 0 1 1 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 1 1]
 [1 1 0 1 0 0 0 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 1 1]]

I'm stuck on row to format it for use with Stratified K-Fold cross-validation.
The best approach I get its this:
X = np.array(df)  # Input features
y = np.roll(X, -1, axis=1)  # Output targets

But when I try to train using:
for fold, (train_index, test_index) in enumerate(skf.split(X, y)):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    # train the model
    history = model.fit(X_train,
                        y_train,
                        epochs=10000,
                        batch_size=24,
                        callbacks=callbacks_list,
                        verbose=1,
                        validation_data=(X_test, y_test)
                       )

I get this error:
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'multilabel-indicator' instead.

My model is:
# Initialising the FFNN

model = Sequential()

# Input Layer
model.add(InputLayer(input_shape=(25,)))

# First Hidden Layer
model.add(Dense(250, activation='relu'))

# First Dropout layer
model.add(Dropout(0.2))

# Second Hidden Layer
model.add(Dense(50, activation='relu'))

# Output Layer
model.add(Dense(25, activation=tf.nn.sigmoid))

I'm compiling the model with:
# Compile the model
model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
    optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.01),
    metrics=[tf.keras.metrics.AUC(name='auc',from_logits=False)]
)

Have tried other approachs, where errors like below occours:
ValueError: logits and labels must have the same shape ((24, 25) vs (24, 1))


text:
Q: Matrix Combination Logic NOTE: **Please read all other related questions:**
Here is my first and second attempts at asking this question:

*

*Efficient way to determine the outcome of test matrix

*Would cartesian product be the best approach for this
Here is the problem:

*

*I have several ( like 20 ) Boolean validations ( true / false )

*All Boolean validations as a whole also have a validation Result

I'm trying to find the best solution to test all the validations and also the validation result. I was looking into a Matrix to hold all possible combinations but that might be an overkill.
Here is an example ( 1 - 20 ):

*

*test_1 = Has 30 Kills

*test_2 = Has Found Map 1

*test_3 = Has Mastered Level 1

*test_4 = Has Achieved Grunt Status

*test_5 = Has Assault weapon

*test_6 = Has Knife

*test_7 = Has Grenade

*test_x = Etc...

So when the Player has all these validations as TRUE I can then give a level result

*

*if test_1, test_2, test_3 ( any combination of the three ): level = green

All combinations are ( 15 ):

*

*test_1

*test_2

*test_3

*test_1, test_2

*test_1, test_3

*test_2, test_1 ( duplicate can skip this )

*test_2, test_3

*test_3, test_1 ( duplicate can skip this )

*test_3, test_2 ( duplicate can skip this )

*test_1, test_2, test_3

*test_1, test_3, test_2 ( duplicate can skip this )

*test_2, test_1, test_3 ( duplicate can skip this )

*test_2, test_3, test_1 ( duplicate can skip this )

*test_3, test_1, test_2 ( duplicate can skip this )

*test_3, test_2, test_1 ( duplicate can skip this )

So unique combinations are ( 7 instead of 15 ):

*

*test_1

*test_2

*test_3

*test_1, test_2

*test_1, test_3

*test_2, test_3

*test_1, test_2, test_3

Now I'm trying to find the best possible solution to find unique combinations for all 20 validations and come up with a level validation from that matrix.
UPDATE:
Also I need to find only TRUE Combinations so you might read the Unique Combinations like this:

*

*test_1

*test_2

*test_3

*test_1, test_2

*test_1, test_3

*test_2, test_3

*test_1, test_2, test_3

Boolean Value Results from Validation Tests

*

*TRUE, FALSE, FALSE

*FALSE, TRUE, FALSE

*FALSE, FALSE, TRUE

*TRUE, TRUE, FALSE

*TRUE, FALSE, TRUE

*FALSE, TRUE, TRUE

*TRUE, TRUE, TRUE

So any of these combinations would be a GREEN level.
Also I need to know the order of the test validations as well as the matrix order to compare for level assignment. So for GREEN level I only need the validation result combination matrix for test 1, 2 and 3. So I could ignore tests 4 - 20
UPDATE #2:
I know this looks like a simple OR condition but I wanted to take out the combination logic to set the level into a matrix. I could use the matrix of combinations to determine the level logic without having to code additional or modify current logic in the code itself. I wanted to just compare the validations results for a given set of tests and assign a level to those results. Different permutations of the validation combinations would result in different level assignments.
I understand that I could add the combination logic in the code itself, but as this logic looks to be very volatile and thought this might offer a more flexible solution.
Suggestions?

A: (removed my two previous answers for clarity)
After your last edit, instead of answering directly, I would like first to be sure to 100% understand the "level detection algorithm" you want.
If I understand well, you would like to define/maintain a simple configuration structure telling which tests give which level.
e.g. with an associative array:
array(
  'green' => array('test1', 'test2', 'test3'),
  'orange' => array('test2', 'test3', 'test5')
  ...
  );

With the meaning: if one or more of the tests in the list are satisfied, assign that level (array key) to the player. Such logic could easily cover quite a lot of combinations, and would avoid handling a huge matrix.
Maybe you want to extend the logic to tell, for example, that at least N tests among the test list are satisfied.
array(
  'green' => array(
      'tests' => array('test1', 'test2', 'test3'),
      'nb_required' => 2
    ),
  ...
  );

Is that what you want?
BTW, why don't you use a classic XP/level up system? :-p

A: Introduction
You can easy get combinations like this :
echo "<pre>";
$test = ["test_1","test_2","test_3"];

// Get Combination
$return = uniqueCombination($test);

//Sort
sort($return);

//Pretty Print
print_r(array_map(function($v){ return implode(",", $v); }, $return));

function uniqueCombination($in, $minLength = 1, $max = 10) {
    $count = count($in);
    $members = pow(2, $count);
    $return = array();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf("%0" . $count . "b", $i);
        $out = array();
        for($j = 0; $j < $count; $j ++)
            $b{$j} == '1' and $out[] = $in[$j];

        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
    }
    return $return;
}

Output
Array
(
    [0] => test_1
    [1] => test_2
    [2] => test_3
    [3] => test_1,test_2
    [4] => test_1,test_3
    [5] => test_2,test_3
    [6] => test_1,test_2,test_3
)

The Problem
They are about 1,048,576 combination and i believe this is not the kind of array you want i would suggest a condition based combination rather than all possible combination
Example
// Game Conditions
$game = new Game();
$game->addCondition(new Condition(new Level(1), new Kill(30)));
$game->addCondition(new Condition(new Level(2), new Map(1), new Kill(10)));
$game->addCondition(new Condition(new Level(3), new Grunt(10)));
$game->addCondition(new Condition(new Level(4), new Knife(1), new Ak47(1)));
$game->addCondition(new Condition(new Level(5), new Grenade(1), new Combo(7)));
$game->addCondition(new Condition(new Level(6), new Kill(100), new Blow(10), new Stab(10)));
$game->addCondition(new Condition(new Level(7), new Herb(10), new Medipack(1), new Map(1), new Artwork(1)));
$game->addCondition(new Condition(new Level(8), new Grenade(20),new Artwork(5)));

// User Starts Game
$user = new User($game);

$user->task(new Map(1));
$user->task(new Herb(5));
$user->task(new Kill(10));
$user->task(new Kill(10));
$user->task(new Herb(10));
$user->task(new Kill(10));
$user->task(new Kill(10));
$user->task(new Ak47(1));
$user->task(new Knife(1));
$user->task(new Map(1));
$user->task(new Grunt(17));
$user->task(new Kill(60));
$user->task(new Combo(1));
$user->task(new Kill(40));
$user->task(new Medipack(1));
$user->task(new Artwork(1));
$user->task(new Grenade(1));
$user->task(new Combo(10));
$user->task(new Blow(10));
$user->task(new Stab(5));
$user->task(new Blow(10));
$user->task(new Stab(5));
$user->task(new Stab(5));

printf("\n<b>Total Point %s",number_format($user->getPoint(),0));

Output
+Task Map   Added  (1)
+Task Herb  Added  (5)
+Task Kill  Added  (10)
^Task Kill  Updated (20)
^Task Herb  Updated (15)
^Task Kill  Updated (30)

*Level 1 Completed*

*Level 2 Completed*

^Task Kill  Updated (40)
+Task Ak47  Added  (1)
+Task Knife     Added  (1)
^Task Map   Updated (2)
+Task Grunt     Added  (17)

*Level 3 Completed*

*Level 4 Completed*

^Task Kill  Updated (100)
+Task Combo     Added  (1)
^Task Kill  Updated (140)
+Task Medipack  Added  (1)
+Task Artwork   Added  (1)
+Task Grenade   Added  (1)
^Task Combo     Updated (11)

*Level 5 Completed*

+Task Blow  Added  (10)
+Task Stab  Added  (5)
^Task Blow  Updated (20)
^Task Stab  Updated (10)

*Level 6 Completed*

*Level 7 Completed*

^Task Stab  Updated (15)

<b>Total Point 1,280</b>

Classes Used
class Task {
    private $no;

    function __construct($no = 1) {
        $this->no = $no;
    }

    function getNo() {
        return $this->no;
    }

    function getName() {
        return get_called_class();
    }

    function merge(Task $task) {
        $this->no += $task->getNo();
        return $this;
    }
}
class User {
    private $game;
    private $point;
    private $tasks = array();

    function __construct(Game $game) {
        $this->game = $game;
    }

    function getPoint() {
        return $this->point;
    }

    function getTask() {
        return $this->tasks;
    }

    function task(Task $task) {
        if (isset($this->tasks[$task->getName()])) {
            $this->tasks[$task->getName()]->merge($task);
            printf("^Task %s \tUpdated (%s)\n", $this->tasks[$task->getName()]->getName(), $this->tasks[$task->getName()]->getNo());
        } else {
            printf("+Task %s \tAdded  (%s)\n", $task->getName(), $task->getNo());
            $this->tasks[$task->getName()] = $task;
        }

        $this->point += $task->getNo() * $task->d;
        $this->game->notify($this);
    }
}
class Condition {
    private $task = array();
    private $status = false;

    function __construct(Level $level) {
        $this->level = $level;
        $tasks = func_get_args();
        array_shift($tasks);
        $this->task = new SplObjectStorage($tasks);
        foreach ( $tasks as $task )
            $this->task->attach($task);
    }

    function update(Game $game, User $user) {
        if ($this->status)
            return;
        $n = 0;
        foreach ( $this->task as $cTask ) {
            foreach ( $user->getTask() as $task ) {
                if ($cTask->getName() == $task->getName()) {
                    if ($task->getNo() >= $cTask->getNo())
                        $n ++;
                }
            }
        }
        if ($n === count($this->task) && ($game->getLevel()->getNo() + 1) == $this->level->getNo()) {
            $this->status = true;
            $game->setLevel($this->level);
            printf("\n*Level %d Completed* \n\n", $this->level->getNo());
        }
    }

    function getStatus() {
        return $this->status;
    }
}
class Game {
    private $taskCondition;
    private $level;

    public function __construct() {
        $this->taskCondition = new SplObjectStorage();
        $this->level = new Level(0);
    }

    function setLevel(Level $level) {
        $this->level = $level;
    }

    function getLevel() {
        return $this->level;
    }

    function addCondition($condition) {
        $this->taskCondition->attach($condition);
    }

    public function notify($user) {
        foreach ( $this->taskCondition as $conditions ) {
            if ($conditions->getStatus() === true) {
                // detached completed condition
                $this->taskCondition->detach($conditions);
                continue;
            }
            $conditions->update($this, $user);
        }
    }

    public function hasCondition() {
        return count($this->taskCondition);
    }
}

class Level extends Task{}
class Action extends Task{};
class Weporn extends Task{};
class Skill extends Task{};
class Tresure extends Task{};
class Medicine extends Task{};

class Kill extends Action{public $d = 5 ;};
class Blow extends Action{public $d = 7 ;};
class Stab extends Action{public $d = 10 ;};

class Map extends Tresure{public $d = 10 ;};
class Artwork extends Tresure{public $d = 20 ;};

class Knife extends Weporn{public $d = 5 ;};
class Grenade extends Weporn{public $d = 10 ;};
class Ak47 extends Weporn{public $d = 10 ;};

class Jump extends Skill{public $d = 2 ;};
class Grunt  extends Skill{public $d = 4 ;};
class Combo extends Skill{public $d = 7 ;};

class Medipack extends Medicine{public $d = 5 ;};
class Herb extends Medicine{public $d = 5 ;};

Simple Online Demo

A: Not quite to answer your question, but it seems you're missing something.
Lets say you have twenty tests, labeled 1 though n.  Decide for test n whether you want to validate for it, or not.   Either you include the test for validation, or you don't. That's two choices for every test. Proceed through (n-1) until you have no more tests.    For n=20, that's 2^20 = 1048576 possible combinations of tests (including one combination where you don't select any tests), which means 1048576 results. Now I still don't understand what you mean by "level of validation", but I have to wonder why you'd need that many combinations of tests in the first place.
Edit:  Well, a test matrix  (so to speak) could work.... but you'd still have to generate the matrix.  You're likely not going to hand code all 1048576 combinations.  But supposing you've already created the mapping, you just have a zero indexed array as a look up table with 1048576 values that you desire and you're done!  All you would need to map the test results to the matrix would be assigning each test a binary digit (test1 would be the one's place, test2 would be the 2's place, etc.)
What I suspect you really want is a quick way to generate the mapping given some broader rules you might encode in php... but here's funny part about that.  If you had some code that generated the matrix for any and every set of tests, the matrix is then superfluous;  Your code is essentially a compressed representation for the matrix.  The only point in using one over the other is whether or not one would be faster than the other.
It also seems you really don't care about all 1048576 combinations.  I suspect it might benefit you to partition your tests into their own set of tests  (one for red, one for blue, etc). For instance, if you partition tests into groups of 5,  and there is, oh, 3 different possibilities (instead of 16) for each group, you're only working with  (3 different results per group)^(4 groups) = 81 unique results.  Eighty one unique results is much more manageable than over a million.
It seems you may also need different partitions for different independent things. It also may not matter even which tests result in true as long as a certain number of them are true, that is "goal: 3 out of 5 blue objectives met"  "goal: 7 out of 10 red and blue objectives met" or whatever.  Those tests would have to be accessed independently and they wouldn't necessarily be multiplicative with the results of the other tests-- there will never be 7 out of 10 red and blue objectives met if none of your blue objectives are met (I'll admit, this is hard to explain further without an example).
So, really, there's no quick answer.  Either you deal with all and every one of the 1048576  combinations individually, or you create and encode some sort of generic grouping scheme for your tests to drastically cut down on combinations.  You can certainly create your full matrix scheme by said scheme, and maybe even dynamically generate your full 1048576  element matrix for a given set of combinations. But you cannot burn a whole candle by only burning half of it.
Edit II (and III):
I'm going to make one more guess.  The levels you've proposed seem to be related to the number of objectives completed per each (and previous batch).  So encode your results in to a string of ("T", and "F") and count the "F"s for each batch and determine from there.  If the count of Fs is the number of characters in the string, no objective of the batch is completed, if the number of Fs is zero, all objectives of the batch are completed.
Lets say the batch after blue is purple.  Could somebody achieve a goal in purple without completing all the green batch? If so, you have another color to assign for that possibility; if not, then, I would assume that these levels are ordered (orange between green and blue, maybe "brown" or something between blue and purple--you can tell I pulled this out of thin air-- and it should be fairly simple to cascade through these counts to determine the current "level".
If there is no ordering, then it's quite analogous to the situation I mentioned above:  Each group has a result { "no objectives completed", "some objectives completed", "all objectives completed"}.  There are x groups which means 3^x possible results. You should be basing your level matrix on these results, not the results of the tests previously mentioned.

A: I  have found the graphic display of your question as you mentioned.
|0|1|2|3|4|5|6|7|8|9|
|1|T|T|T|T|T|T|T|T|T|
|2|F|T|T|T|T|T|T|T|T|
|3|F|F|T|T|T|T|T|T|T|
|4|F|F|F|T|T|T|T|T|T|
|5|F|F|F|F|T|T|T|T|T|
|6|F|F|F|F|F|T|T|T|T|
|7|F|F|F|F|F|F|T|T|T|=>[7,9] if this is the answer
|8|F|F|F|F|F|F|F|T|T|
|9|F|F|F|F|F|F|F|F|T|

In my opinion you should check the conditions in reverse diagonal order, then left to right.
That means
first check [9,9]
if it fails check [8,8]
if this fails check [7,7]
if it  gives true check [7,8]
if this gives false check [7,9] this must be the answer and the simple shortcut,
This method will reduce over all process time.


text:
Q: Problems with integrated vuforia with 64 bit Unity Basically, I am having trouble playing my augmented reality app in the Unity. I have done all the right things but the app just won't play. It is a very basic app that adds a spinning cube on some real life  it sees in the real world. I know that vuforia can't handle the 64 bit Unity but i was hoping that there was either a hack or some emulator that I can use to open the unity scene with or something epic that I can't even conceive of. These are my first steps into augmented reality programming and it would help to actually see it work on my pc.

A: As far as I know, you cannot use 64 bit Unity with Vuforia. It may work for some features of Vuforia but you definitely will not be able to use the full functionality of Vuforia--there will always be problems.
One solution is obviously to just uninstall your current version of unity and install a 32 bit version (I would suggest Unity 5.1.3 (32 bit) as this is the one I know to support almost 100% of Vuforia). A note: this will NOT delete any Unity projects you have created, you will just need to reopen them in your new version of Unity.
Another solution is like what tim mentioned in his comment--to just have both 64bit and 32bit Unity installed of your computer. Just make sure that you stay as consistent as possible (i.e. make sure you don't accidentally open a Vuforia project with the 64bit Unity) as this will likely cause problems.
Best of luck.

A: If you want to use Unity 64 bit , you can try the newest version of Vuforia , vuforia-unity-6-0-112.It was recently released to be more compatible for unity 64 bit.You can give it a try by downloading on this link https://developer.vuforia.com/downloads/sdk. Right now im using Unity 5.4.0f3 (64-bit) and its working perfectly until now.


text:
Q: Uploading an image using jquery, instant uploading how can i upload an image using jQuery so it wont have to refresh the page?
so i can use the uploaded image. i have no idea how to submit a file through jQuery :/
if i have the following form
<form action = "myCurrentPage" method = "POST" enctype = "multipart/form-data">
    <input type = "file" name = "LogoImage" id = "LogoImage">
</form>

A: HTML:
<form id='myForm' onsubmit='doUpload()' action = "javascript:void(0)" method = "POST" enctype = "multipart/form-data">
    <input type = "file" name = "LogoImage" id = "LogoImage">
</form>

Javascript:
function doUpload() {

var formData = new FormData(document.getElementById("myForm"));

$.ajax({
   url:            "/admin/scripts/addpet.php",
   dataType:       "xml",
   type:           "POST",
   processData:    false,
   contentType:    false,
   data:           formData
}).done(function(xmlDoc) {
});

}

On your php side you grab the file like you normally would. $_FILES['fileName']['tmp_name']


text:
Q: C++: Getting hex unexpectedly when printing array I am declaring an array using new
int *a = NULL;
a = new int[10];

a[0] = 23;
a[1] = 43;
a[2] = 45;
a[3] = 76;
a[4] = 34;
a[5] = 85;
a[6] = 34;
a[7] = 97;
a[8] = 45;
a[9] = 22;

PrintElements(a, 10);

void PrintElements(int * array, int size){
    for (int i=0; i<size; i++) {
        cout << endl << array[i];
    }
}

Now when I print the values I am getting these values

17
2b
2d
4c
22
55
22
61
2d
16

Can somebody tell me what am I doing wrong...?
On the other hand when I dont use new & initialize array without it everything works fine.

A: You may have written a std::hex to the cout at some point; that will remain in effect until overridden.

A: It doesnt have anything to do with the static or dynamic allocation of the array.
The numbers are printed as Hexadecimal values and not decimal values.

A: Try:
std::cout << dec << //all your stuff here

It's still set in hex mode.

A:
17 2b 2d 4c 22 55 22 61 2d 16

These are obviously hexadecimal numbers. If you print them as decimals you get 23, 43, etc. IOW, exactly the numbers that you have put into the array. Some piece of your code executed prior to your PrintElements() apparently changes the formatting to output hexadecimal numbers.


text:
Q: Receive video from a source, preprocess and stream live preview to the client | ASP.NET Core I need to implement a server that gets video from some source for example IPCamera
then preprocess the image and streams it down to the client (if requested).
I already implemented the part with processing, it accepts a single frame (bitmap) and returns the processed bitmap. What I'm struggling with is the part of receiving video from the camera and then streaming it to the client.
What would be the right way to do it?
What libraries do you recommend using?
I use ASP.NET Core for the Server part, and Angular/React for the Client.
I tried to implement gRPC but a gRPC-Web client for typescript seems to be a pain in the ass.
Edit: 02.08.2022
What I achieved so far:
I figured out how to receive image output from the camera.
I found out RTSP Client for C#. Source: C# RTSP Client for .NET
It works pretty fine. I can receive output with small to no delay, and I use my phone to emulate the RTSP camera/server.
So RTSP Client receives raw frames (in my case H.264 IFrame/PFrame). The problem is I need to decode those frames preferably to Bitmap because I use YoloV4 ONXX Model for object detection.
Here's how I set up YoloV4 with ML.Net. Source: Machine Learning with ML.NET – Object detection with YOLO
To decode raw frames I use FFMpeg (sadly I didn't find any working FFMpeg package that would work with .NET Core, I tried AForge.Net, Accord but in both packages, the FFMPEG namespace is missing after installing for some reason, so I dug through Github and took this project FrameDecoderCore). It's not the best solution but it works. Now I can receive the output and decode it to Bitmap.
Now I'm facing three major issues:

*

*How to detect objects without delaying the process of receiving camera output. And how to properly build an onnx model just to predict without training.

*How to convert processed bitmaps back to a video stream. I also need to be able to save part of it as a video file on disk (video format doesn't matter) whenever the desired object was detected.

*How to stream processed or unprocessed output to the client when the client wants to see the camera output. - I'm thinking of gRPC here and sending bitmaps and then displaying it on HTML Canvas.

Here's how my service looks at the moment:
public class CCTVService : BackgroundService
    {
        private readonly RtspClient _rtspClient;
        private readonly ILogger<CCTVService> _logger;

        private const int streamWidth = 480;
        private const int streamHeight = 640;

        private static readonly FrameDecoder FrameDecoder = new FrameDecoder();
        private static readonly FrameTransformer FrameTransformer = new FrameTransformer(streamWidth, streamHeight);

        public CCTVService(ILogger<CCTVService> logger)
        {
            _logger = logger;
            _rtspClient = new RtspClient(new ConnectionParameters(new Uri("rtsp://192.168.0.99:5540/ch0")));
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
         {
            using (_rtspClient)
            {
                try
                {
                    await _rtspClient.ConnectAsync(stoppingToken);
                    _logger.LogInformation("Connecting to RTSP");
                }
                catch(RtspClientException clientException)
                {
                    _logger.LogError(clientException.Message);
                    //throw;
                }

                _rtspClient.FrameReceived += (obj, rawFrame) =>
                {
                    if (rawFrame is not RawVideoFrame rawVideoFrame)
                        return;

                    var decodedFrame = FrameDecoder.TryDecode(rawVideoFrame);

                    if (decodedFrame == null)
                        return;

                    using var bitmap = FrameTransformer.TransformToBitmap(decodedFrame);

                    _logger.LogInformation($"Timestamp: {new DateTimeOffset(rawFrame.Timestamp).ToUnixTimeSeconds()} Timestamp-diff: {new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds() - new DateTimeOffset(rawFrame.Timestamp).ToUnixTimeSeconds()}");

                    // save bitmaps | Test
                    //var t = new Thread(() =>
                    //{
                    //    using var bitmap = FrameTransformer.TransformToBitmap(decodedFrame);
                    //    var name = "./test/" + new DateTimeOffset(rawFrame.Timestamp).ToUnixTimeMilliseconds().ToString() + " - " + new Random().NextInt64().ToString() + ".bmp";
                    //    bitmap.Save(name);
                    //});
                    //t.Priority = ThreadPriority.Highest;
                    //t.Start();
                };

                try
                {
                    await _rtspClient.ReceiveAsync(stoppingToken);
                }
                catch
                {
                    // swallow
                }
            }
        }
    }

A: So I can't really help with part 2 and 3 of your question but with ML.NET, one of the things you might consider is batching the predictions. Instead of preprocessing them one at a time, you could collect 10-20 frames and then instead of using PredictionEngine, use the Transform passing it in an IDataView instead of a Bitmap.
Here are some samples of using ONNX models inside applications. The WPF sample might be of interest since it uses a webcam to capture inputs. I believe it uses the native Windows APIs, so different than how you'd do it for web but it might be worth looking at anyway.
https://github.com/dotnet/machinelearning-samples/tree/main/samples/csharp/end-to-end-apps/ObjectDetection-Onnx


text:
Q: How do I undo this splitting of text into columns? I've received an ODT file, where the text, intended to have usual page-wide layout appears to be split in two columns. If I copy the text and paste as plain text, I get this:
1
2
3
4
5
6
7
8

But in LibreOffice Writer it looks instead like this:

I've tried looking into Format->Page->Columns, but there I have Columns spinbox read 1, so there the setting is single-column layout. Apparently, there's more than one way to have two columns.
What is the feature this document is using? How do I turn it off so that the document became single-column?

A: OK, there appears to indeed be two ways to double the number of columns:

*

*Format->Page->Columns

*Format->Columns

Set 2 in one, you'll get two columns. Set 2 in both, and you have four(!).
Well. Not so simple. In this particular file it was this way: Format->Page->Columns dialog had 1 column set, while Format->Columns had 2. When I changed the former to 2, I got 4 columns in the document. When I made both 1, I got what I wanted.
But if I create a new document, these dialogs appear to be synchronized and don't have such strange behavior.


text:
Q: ajax call vulnerable to xss attack I have a simple web application in which I make a call to a java servlet using ajax from a jsp page (via post). In the servlet I take data from the database and formulate a JSON and retreive in the jsp page . I then use eval function to parse the json and display the data in the division using the innerHTML property . Somehow, this approach seems to be vulnerable to xss attacks . Can someone provide some pointers on how XSS attck can be prevented in this use case?

A: This sounds like DOM Based XSS.  There are a few ways of preventing DOM Based XSS.  Either you have to html encode the data on the server or the client.  HTML encoding data in the database should always be avoided because it changes the value of the data and will affect how the data is sorted, ect.  XSS is an output problem so it should be solved by the code that is building the HTML,  which in your case is JavaScript.

A: Newer browsers support JSON.parse().For older browsers use json2.js.
You should also properly encode the JSON so values cannot break out of quotes etc. Find a decent json encoder and use that on the server side.


text:
Q: How to delete an attachment on outlook 365 when deleting fails I'm getting the following error message:
The following attachments couldn't be deleted: my_document.docx. Please try again later.
This appears to be happening for all my attached documents (currently all docx files).
I'm on Windows 10 using Chrome. I tried logging out, clearing all related cookies and data, and logging in, but the problem has persisted. What's causing this problem and how do I delete the attachments?


text:
Q: Is there a way to get this "send to printer" Java method to work? public static void sendPdfToPrinter(String epsilon)
{
    FileInputStream psStream = null;
    try {
        psStream = new FileInputStream(epsilon);
        } catch (FileNotFoundException ffne) {
          ffne.printStackTrace();
        }
        if (psStream == null) {
            return;
        }
    DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);

    // this step is necessary because I have several printers configured
    PrintService myPrinter = null;
    for (int i = 0; i < services.length; i++)
    {
        String svcName = services[i].toString();
        System.out.println("service found: "+ svcName);
        if (svcName.contains("series"))
        {
            myPrinter = services[i];
            System.out.println("my printer found: "+svcName);
            break;
        }
    }

    if (myPrinter != null) {
        DocPrintJob job = myPrinter.createPrintJob();
        try {
        job.print(myDoc, aset);

        } catch (Exception pe) {pe.printStackTrace();}
    } else {
        System.out.println("no printer services found");
    }
}

public static void main(String[] args) throws IOException
{
    //@SuppressWarnings("unused")
    //Testing t = new Testing();
    String DEST = ("C:/Users/Brian/Desktop/SO046201R-17/TestingAlpha/6FS-2m.pdf");
    sendPdfToPrinter(DEST);
}

I'm currently writing a program that'll write text to a series of PDF files and then send them to a printer. I've got the writing to the PDF part done, but whenever I try passing the file to the "sendPdfToPrinter" method I encounter problems. So far I've tested a HP Deskjet printer and a Canon Inkjet printer with no success (former gave a "Java Document error" message and latter wouldn't add file to the queue). I suppose my question boils down to this:
Is the problem with the code or with the printers I'm using? Is there a workaround?
Using Mark's edit:
public static void sendPdfToPrinter(String epsilon) throws
InvalidPasswordException, IOException
{
    FileInputStream psStream = null;
    try {
        psStream = new FileInputStream(epsilon);
        } catch (FileNotFoundException ffne) {
          ffne.printStackTrace();
        }
        if (psStream == null) {
            return;
        }
    DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PDDocument myDoc = PDDocument.load(new File(epsilon));
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    PrintService[] services =
    PrintServiceLookup.lookupPrintServices(psInFormat, aset);

    // this step is necessary because I have several printers configured
    PrintService myPrinter = null;
    for (int i = 0; i < services.length; i++)
    {
        String svcName = services[i].toString();
        System.out.println("service found: "+ svcName);
        if (svcName.contains("series"))
        {
            myPrinter = services[i];
            System.out.println("my printer found: "+svcName);
            break;
        }
    }

    if (myPrinter != null) {
        PrinterJob job = PrinterJob.getPrinterJob();

        try {
            job.setPrintService(myPrinter);
            job.setPageable(new PDFPageable(myDoc));
            job.print();
        } catch (PrinterException e) {
            // Handle the exception.
        }
    } else {
        System.out.println("no printer services found");
    }

}

A: This may be because your printers don't natively support PDFs. I actually managed to print a PDF with your code, but it printed it as it would look if a PDF file was opened as a text file.
One solution is to use Apache's PDF library for Java: PDFBox. The file can be loaded like so:

PDDocument myDoc = PDDocument.load(new File(epsilon));

To print the file, use PrinterJob instead of DocPrintJob:

PrinterJob job = PrinterJob.getPrinterJob();

try {
    job.setPrintService(myPrinter);
    job.setPageable(new PDFPageable(myDoc));
    job.print();
} catch (PrinterException e) {
    // Handle the exception.
}


text:
Q: getting and editing css class of an element using javascript In JavaScript, the className property gives the class name of an HTML element, but how to get the contents of the class.

A: first you need to get the cssRules array but since it is not cross platform you should use a code like this:
if ( document.styleSheets[0].cssRules ) {
    var cssRules = document.styleSheets[0].cssRules;
} else if ( document.styleSheets[0].rules ) {
    var cssRules = document.styleSheets[0].rules;
}

now cssRules is an array of selectors in your stylesheet you can go through it like this:
for( var i = 0; i < cssRules.length; ++i ) {
     if( cssRules[i].selectorText == '.myClass' ) {
         alert( cssRules[i].style.color );
     }
}

A: The actual style rules are stored in the style property.
Also, jQuery has some really nice methods for working with style. If you want to explore that route, check out the css method.
EDIT: Just re-read the question and realized that the OP was asking about the style rules for the class, not the style rules for the element. However, because the context isn't exactly clear, I'll let this answer stand for now, as it may still be helpful.


text:
Q: Magento not sending order emails despite cron being set up correctly Having some real trouble getting my Magento installation to send out order emails.
Before you say it, I've set up a cron, and yes it's running (I've even tested it with a basic php echo to be sure).
I've currently got the cron set up as
 /usr/bin/php -f /home/username/public_html/cron.php

But I've also tried
www-data /bin/sh /home/username/cron.sh cron.php -m=always
php -f /home/username/public_html/cron.php

All scheduled between 1 and 15 minutes per cycle.
I've also set up the AOE scheduler AND ran the core_email_queue_send_all task and all emails send as expected. On the AOE, I get a heartbeat task error, but then again I have the same on another site where I'm having no issue.
Could this be a server thing? I believe the IT guy changed some permissions to allow me shell access, but I can't see why that would be a problem.
Thanks in advance.


text:
Q: Scrolling fixed header displays farther down then desired I am having some difficulties with a scrolling fixed header I am creating. I found a good example of it on here and now I am trying to make it work with my changes to it and I am trying to adapt it.
I put additional divs than what were in the example and now whenever I scroll past the yellow bar, the red bar(my header) displays way lower than I want.
I created a fiddle to show what it is doing.
https://jsfiddle.net/zoue6gv7/
This worked until I added my top margin to my div id join_login. It now is that far away from the top.
#join_login {
position: absolute;
right: 15%;
top: 27px;
font-size: 1em;
color: #383838;
}

How can I get this header to stay fixed at the top after I get to my scroll point?

A: Is this what you want? https://jsfiddle.net/zoue6gv7/1/
I just removed the margin-top -50px and replaced it with
top: 0;

A: This should do the trick! You can just eliminate the space above #logo by adding margin-top: -15px
#logo {
    position: absolute;
    left: 15%;
    top: 22px;
    font-size: 2em;
    margin-top: -15px;
}

A: Just kidding! I think I misunderstood what you're trying to do, if you want the red Header to stick to the top of the page even when you scroll down:

*

*Use position: fixed; to tell the header to stay in the same location regardless of scrolling

*Use top: 0px; to tell the header, that the location you'd like it to be fixed to is the very top of the page
header {
position: fixed;
top: 0px;
width: 100%;
height: 75px;
background: red;
z-index: 100;
border-bottom: 1px solid #888888;

}


text:
Q: LoaderManager within FragmentActivity shares context Thread name may seem ambigous so I'll explain:
I have a main activity MainActivity which uses SupportLoaderManager and implements it's callbacks:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, InTimeResultReciever.Receiver, Thread.UncaughtExceptionHandler {
...
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
...
loadermanager = getSupportLoaderManager();

loadermanager.initLoader(0, null, this);
...
locationList.setAdapter(locationGeofenceArrayAdapter);
}

@Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] projection = {GeofenceTTBLTable.COLUMN_ID, GeofenceTTBLTable.COLUMN_NAME, GeofenceTTBLTable.COLUMN_ACTIVE};

        cursorLoader = new CursorLoader(this, InTimeContentProvider.CONTENT_URI_GEOFENCES, projection, null, null, null);
        return cursorLoader;
    }

@Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        locationGeofenceArrayAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        locationGeofenceArrayAdapter.swapCursor(null);
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        locationGeofenceArrayAdapter.notifyDataSetChanged();
    }
}

All good, ListView on this activity is populated as expected.
On a listview's row long click I have listener which which brings up DialogFragment with two options each firing an intent that starts another FragmentActivity:
Intent editIntent = new Intent(getActivity(), EditDialog.class);
                        editIntent.setAction("editEntry");
                        editIntent.putExtra("geoId", String.valueOf(rowId));

                        getActivity().startActivity(editIntent);

This FragmentActivity should serve as advanced dialog with it's own LoaderManager filling ListView able to remove/add rows into it. It is SuportLoaderManager just like in main activity and it implements the same callbacks.
Still working until now, but when I try to manipulate (update) rows of it's cursor/data set returned from onLoadFinished things are getting worse.
The error looks like this (stack trace abreviated):
11-23 16:36:13.977 25945-25945/com.tepo.InTime E/AndroidRuntime: java.lang.RuntimeException: Unable to resume activity {com.tepo.InTime/com.tepo.InTime.MainActivity}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT _id, Name, Active FROM Location
...
11-23 16:36:13.977 25945-25945/com.tepo.InTime E/AndroidRuntime:  Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT _id, Name, Active FROM Location

It is the same when I use different loader id's upon loader manager initialization.
Can't simulate right now (don't know why) but it happend to me yesterday, that when I was manipulating list called/started fragmentActivity onLoadFinished was called, but the one in MainActivity!!
All this brings me to the conclusion that EditDialog being FragmentActivity is somehow connected with MainActivity's cotnext even through I am starting it as activity with intent.
So my questions are: What exactly is happening? What should I do in order to have two separate loader managers onw in MainActivity and the other in FragmentActivity dialog?
Thank you!


text:
Q: Javascript not redirecting page I have the following html code:
<html>
    <head>
        <script type="text/javascript" src="buttonClicked.js"></script>
    </head>
    <body>
        <form id="confirmChangeId" name="selectionForm" method="POST">
            <input id="btnChange" type="submit" value="Change">
        </form>
    </body>
</html>

using the following javascript:
window.onload = function() {
    initFunc();
}

var initFunc = function() {
    var change = document.getElementById("btnChange");
    change.onclick=function() {
        window.location.href='http://stackoverflow.com';
        //alert("change button clicked"); // If this line is uncommented, then the page re-direction does occur
    }
}

Using Firefox, when the alert is uncommented in the JS file then the redirection does occur. To throw a further spanner in the works, no redirection occurs whatsoever when using Chrome or Opera. I'm clearly missing something small here, but can't find what it is. Suggestions?

A: If you want the redirection to reliably work, you must add return false; at the end of your onlick function.
Note: You should really attach event listeners to the objects instead of using the outdated onclick property.
var change = document.getElementById("btnChange");
change.addEventListener('click', function(event) {
    event.preventDefault(); // stops the click from completing
    window.location.href='http://stackoverflow.com';
}, false);

A: Add return false; in your function.otherwaise form being submited before redirect
 var initFunc = function() {
 var change = document.getElementById("btnChange");
 change.onclick=function() {
    window.location.href='http://stackoverflow.com';
    return false;
    //alert("change button clicked"); // If this line is uncommented, then the page re-         direction does occur
  }
 }

A: The code below should work. It is imperative that you add the return false to your onlcik function. You need event listeners.
See below:
<script>
window.onload = function() {
    initFunc();
}

var initFunc = function() {
    var change = document.getElementById("btnChange");
change.addEventListener('click', function(event) {
    event.preventDefault(); // stops the click from completing
    window.location.href='http://stackoverflow.com';
}, false);
}
</script>

<html>
    <head>

    </head>
    <body>
        <form id="confirmChangeId" name="selectionForm" method="POST">
            <input id="btnChange" type="submit" value="Change">
        </form>
    </body>
</html>


text:
Q: How can I apply an ACF field to a single custom post if it refers to the taxomy of that post type in the rules? need to hide a div inside custom posts in a given category. I created an ACF True/False field and applied it to the category taxonomy for this post type. But this True/false should work on internal records that refer to the selected category to which ACF True/false is applied. I understand that there must be something like this ... but what exactly, I do not know) :
$terms= something here that I don't know..) ;
<?php if ( 'yes' == get_field('name_field',$terms)): ?>

....
PS: Perhaps I'm not entirely competent of the above. The logic is this: I check the box, inside the category, that I need to hide the div, in all case records associated with this category, the div is hidden.


text:
Q: Get the Last Access date for all BigQuery tables in a BigQuery Project I know how to get the date a table was last modified, but not accessed. Is it possible to get the last time a table was read ? Is there query or an API to get this ?

A: If you have audit logs in BigQuery, you can write a query like this:
WITH tables AS (
  SELECT FORMAT("%s.%s.%s", table.projectId, table.datasetId, table.tableId) table
    , MAX(timestamp) last_access
  FROM (
    SELECT timestamp
      , protopayload_auditlog.servicedata_v1_bigquery.jobCompletedEvent.job.jobStatistics.referencedTables
    FROM `fh-bigquery.audit.cloudaudit_googleapis_com_data_access_201811*`
  ), UNNEST(referencedTables) table
  GROUP BY 1
)

SELECT *
FROM tables


text:
Q: Programmatically redirect to URL without react-router I'm running an SPA without the help of a 3rd party router. I want to redirect to an external URL within a function.
Obviously href and installing routers do not solve my problem.

A: If you want to redirect to an external URL and not something internal, then it's easier. You get hold of the window.location object and you can make it possible. I can understand why  will not be a right choice to do it programmatically.
The below works perfectly fine. I used a setTimeout to simulate a programmatic redirect.

class App extends React.Component {
  componentDidMount() {
    setTimeout(() => {
      window.location.href = 'https://praveen.science/';
    }, 1000);
  }
  render() {
    return (

Hello CodeSandbox

Start editing to see some magic happen!

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: PDO::MYSQL_ATTR_USE_BUFFERED_QUERY error occuring while calling stored procedure in zf2 when calling a stored procedure in zend framework 2 , it throwing an error message, how can i solve this issue ,
$dbAdapter = $e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
    $results = $dbAdapter->query("CALL PROCEDURE_NAME('PARAM1')");
    $DataSource = $results->execute();
    $Statement = $DataSource->getResource();
    $Result = $Statement->fetchAll(\PDO::FETCH_OBJ);

the above code is using to get stored procedure information
getting below error
Statement could not be executed (HY000 - 2014 - Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.)

A: Solved my problem , i just put closeCursor after fetching result
$dbAdapter = $e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
$results = $dbAdapter->query("CALL PROCEDURE_NAME('PARAM1')");
$DataSource = $results->execute();
$Statement = $DataSource->getResource();
$Result = $Statement->fetch(\PDO::FETCH_OBJ);
$Statement->closeCursor();

Thank you  Ukuser32 for supporting me to find solution