text:
Q: Is there a viable way to stream games over wifi in Linux? I have a Linux desktop PC in my basement, which I tend to use to play more recent games, as it has a reasonably powerful, dedicated NVidia GPU. However, I am wondering if there is a viable way to stream such a game in Linux over wifi from the desktop to a less-powerful laptop elsewhere in the house?
I am aware of the networking capabilities of X, which allows you to run an application on one machine, but have it display and take input from a window running on another machine (which can be done, for example, using ssh tunneling). There are also remote-desktop technologies like VNC.
However, games running at 30+ FPS with a fairly high resolution would need a lot of bandwidth. I know Steam has a 'home streaming' system, which I believe it uses video compression technology to compress the video stream to improve performance. Can anything similar be done using freely-available Linux technology?
So, I guess the question boils down to whether you can 'forward' an X application to another machine, with some sort of audio/video compression? A full remote desktop would probably not be a good solution, as it would be wasting a lot of bandwidth on unnecessary DE stuff.

A: Both X11 forwarding and VNC are ill advised for the task as they were never designed to forward fast changing full screen rich images. Please try using Steam Remote Play instead.


text:
Q: Long title flexbox/ellipsis in React Native? I am trying to have a title fit with an ellipsis if it's too long for the device width, so the priorities in red below can always show at all times:

The above is what it should look like.
It works very well with a short title, but looks like this now:

I set up a working example here: https://rnplay.org/apps/heKkoQ
Try a short title, you'll see how it looks correct, but with the long title, it does not fit the priority.
Can someone jump in with a working solution?

A: You should add flex: 1 to header container style and flexShrink: 1 to title style. Also use ellipsizeMode='tail' and  numberOfLines={1} props for title.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute redis FLUSHALL command in rails application I want to execute Redis FLUSHALL every time the Rails server starts.

A: port = 10000
$redis = Redis.new(:port => port)
$redis.flushall

http://fhwang.net/2010/09/23/Testing-Rails-against-a-running-Redis-instance-and-doing-it-with-Hydra-to-boot
To run that on start up check https://stackoverflow.com/a/7091991/643500


text:
Q: ROOT LogIn Times out / Error I'm looking at my friends server(dedi)
Server is ON no problems on host, when we contacted them, they said it is on our End. He has only XtreamCodes installed on it (paid) and it works just on panel keeps going off and on every now and then.
When I/he tries to log in via SSH sometimes it goes through with a massive lag or time out and other times it does not log in at all just times out and throws in an Error, mind you server is on and working.
What could be the culprit to tihs and how could we fix this, without Re-Installing and losing all Data.
Thank you.


text:
Q: Возможно подключить Git к серверу? Здравствуйте, поискал в интернете не нашёл что мне нужно(наверное не так вопрос формулировал).Возможно ли подключить git к серверу, и отслуживать файлы на сервере, и если нужно закачивать на github.
Заранее спасибо!


text:
Q: How to save app on iphone? If my iphone is plugged in, how do I save my app on it?
I have a developer account and certificates setup.

A: You need XCode to "install" your Application into the phone. Previously, you should have followed the steps to register your application, generate a provisioning profile for it, and a couple of other steps.
Check out Apple Documentation. It's pretty good with a lot of step by step tutorials on how to do that.
Good luck!

A: plug it in, click in the bar for device/simulator and choose device. if i'm right, you dont need to do anything else, just press build and go.


text:
Q: If the interior of $A$ is empty, must $A$ be countable? Let $X$ be a second metrizable space and $A$ is a subset of $X$. If the interior of $A$ is empty, must $A$ be countable?
Thanks!

A: This is false in every uncountable separable space; in particular, every uncountable, second countable, metrizable space.
Let $E$ be a countable dense subset (think of the rationals). Then $E^c$ is necessarily uncountable. Since every nonempty open set contains a point of $E$, $E^c$ must have empty interior.

A: Consider $\Bbb R$. Take the Cantor set, or the irrationals.


text:
Q: Mips Mars braching statements I am in a Computer Assembly and Organization class at my school, and we have a piece of code in MIPS MARS that I can not figure out. Our teacher doesn't teach out of the book so there is no way for me to know how to code this in MIPS MARS. I understand how to assign the initial values into the $s registers, but have no idea how to code the if statements or how they should look. Any help would be appreciated because I can't learn from this teacher to save my life. We are supposed to code the following in MIPS MARS assembly language:
1) Use the MARS assembler submit a working program that will convert the following High level Java statement to MIPS Assembly code?  (60 pts)
Code the following branching statements. Let a = 10, b = 16, c = 16, d = 6, use register $s0 for a, $s1 for b and so forth.
    if(a==b){
        Z = a+a;
        Z=Z+b+c+d;
    }

    if(a==b){
        Z=a;
        Else{
            Z = (a+b+c)-d;
        }

    if (a != b){
    Z=a;
    Else{
        Z = (a+b+c)-d;
    }

*Go through a loop from 1 to 10 times, write out the loop counter.

*Calculate the summation of 10 numbers using a loop.  Write out the result.

A: Because your question is not specific and you only asking how write an if statement here is a code example that printing the larger of two integer from user input. I have commented where the if statement begins and you can run it on MARS.
.text

 .data
 message: .asciiz " Enter a number\n"
 message2: .asciiz "Enter another number\n"
 main:
.text

la $a0, message      #print out message
li $v0, 4
syscall

li $v0, 5       # read user input (integer)
syscall

move $t0,$v0          # t0 = user input number 1

la $a0, message2       #print out message2
li $v0,4
syscall

li $v0, 5          #read user input
syscall

move $t1,$v0       # t1 = user input number 2
#********************************************
# if statement begins her
#***************************************
bgt $t0,$t1, bigger    # branch to bigger if t0 > t1
move $t2,$t1           # t2 = t1
b   endif
bigger:
move $t2,$t0           # t2 = t0
endif:
# ************************************
# if finish here
#************************************
move $a0,$t2           # move the result in the argument a0
li $v0, 1              # print it out
syscall

li $v0,10
syscall

Her is also pseudo code for an if statement
branch $a0,$a1, lable   #in case you use `beq` means ( if a0 ==a1 jump to lable)
#branch to lable if condition is met
#if body
b   endif
lable:
#if body

endif:

Let's convert your first if statement to explain it in detail.
  if(a==b){
       Z = a+a;
       Z=Z+b+c+d;

   beq $s0,$s1,L
   add $t0,$0,$s0
   add $t1,$t0,$s1
   add $t2,$s2,$s3
   add $t0,$t1,$t2
   b   endif
L:

endif:


text:
Q: The ErrorProvider's Glyph is sometimes buggy. Why? In my WinForms' application, I use an ErrorProvider to display errors on some controls (like TextBox or CheckBox).
But the glyph (icon if you prefer) is sometimes buggy: it have some kind of aliasing. These visual glitch is random.
Example of good display:

Example of bad display:

In second picture, you notice the aliasing in the bounds! This is very ugly and I found nothing about this glitch on the web.
Have you any idea what can I do to fix it? What is the cause?
Oh, I'm working on Windows XP SP3.


text:
Q: Why is C# considered a statically-typed language, although it contains keywords such as `dynamic` and `var`? C# is considered a statically-typed language. However, it contains keywords such as:

*

*var, which infers the type at compile time, and

*dynamic, which determines the type at runtime.

Is this a contradiction?

A: C# is flexible and versatile language that is not 100% bound to a specific paradigm. At its core it is statically typed but also has dynamic features, as you have correctly noted. There is no contradiction here and no issue to solve.

A: C# has a static type system. So it is reasonable to describe it as a statically typed language. Just like any other OOP language, it also provides for some degree of dynamic typing. C# goes a lot further here than other statically typed languages by providing a dynamic static type, but this does not break its static type system.
Background:
With dynamic typing, values or objects have types. E.g. 1 is an int, and the result of evaluating new Foo() is an object of type Foo. We can think of every object being "tagged" with a type.
With static typing, expressions in our code can be assigned types. For example, x + 1 might be an int, and the variable foo might be declared to only contain Foo instances. These static types are guarantees about the values that the expression might evaluate to. This is useful because it might detect potential bugs, before running the code. Or viewed another way: a static type system allows for basic proofs of correctness. Static type systems also enable interesting features such as method overloading.
A lot of time, the static type of an expression is obvious. We don't have to manually annotate every expression with its static type. The compiler has rules to infer static types itself. When declaring a variable, we can instruct the compiler to infer its type with the var keyword.
With statically typed OOP languages, we have both static and dynamic typing, due to the use of inheritance and interfaces. Now, the static types do not describe exactly what values are possible at runtime, but only constrain them. For example, we might define a variable IFoo foo = .... This guarantees us statically that any object referred to by foo will conform with the IFoo interface, providing certain properties or methods. But we do not know which classes those objects might have exactly – we don't yet know their dynamic types.
C# has a unified inheritance hierarchy, with all objects being derived from the System.Object class. If we declare a variable with static type Object, then we can assign anything to it. However, we are only guaranteed that it will provide the methods that are part of the Object class, such as ToString(). If we want to call other methods that the object instance supports, we have to cast it to its actual type, which requires checking its dynamic type. We can do that via a cast. Casts let us write statically checked code dependent on the object's dynamic types, because casts can fail – the code can only be executed if the object really has the expected type.
A lot of code doesn't benefit that much from static type safety. As a shortcut for casting the object to the correct type before accessing a method or property, C# offers the dynamic type. This pseudy-type behaves differently from other static types, since it just defers any type checks to runtime. However, this is still perfectly safe. This cannot be used to violate the static types in other parts of the code, because the compiler will insert the suitable checks at runtime.
For example, consider a function that converts a dynamic object to an integer:
static int IntFromDynamic(dynamic o) => o;

This function is compiled roughly as if it were the following:
static int IntFromDynamic(Object o) => (int)o;

Neither variant would allow us to break the static type system, for example by trying to launder a string into an int: IntFromDynamic("foo") will fail at runtime.

A: Per the comment, "var" just means "infer the static type as if I'd written it here". It compiles as if you'd written a specific type there.
Dynamic is a little different. Let's see what it says in the documentation:

The dynamic type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation.

Look right there: "dynamic" is a static type!
That is, the precise type of the object is to be determined at runtime, but the fact that it's dynamic is recorded in the static type system.
You can even see what this gets turned into in MSIL. The method invocations against the dynamic object are done using reflection.

A: From a compiler/language theory perspective, you're confusing static/dynamic typing with implicit/explicit typing. Implicit typing is also called type inference.
In an explicitly typed language, the programmer has to explicitly declare the type of every variable. In an implicitly typed language, types can be inferred by the compiler. It is important to note that in principle implicit/explicit typing has nothing to do with static/dynamic typing. You can have the combinations: static/explicit, static/implicit, and dynamic/implicit.
The classic statically typed, explicitly typed language is C. Everything must be explicitly typed, and the compiler assumes nothing. Every variable definition looks something like:
typedef varname = r_value;

or for example:
char* x = "Hello, world";
int   y = 42;
int   z = 0; //Depends on which C standard you're using, but in general
             //0 is false and any nonzero value is true

A statically typed, implicitly typed language is Rust. The philosophy of Rust is to empower programmers, so while the static type system is strict, it also doesn't require you to be overly-explicit. Statements like:
let x = "Hello, world";
let y = 42;
let z = false;

are perfectly clear to the programmer and compiler, so they are implicitly typed. You can write them explicitly if you prefer or need to:
let x: &str = "Hello, world";
let y: u16  = 42;
let z: bool = false;

The two easy examples for dynamically typed, implicitly typed languages are Python or Javascript. In Python the principle is duck-typing - or, if it walks like a duck and quacks like a duck, it's a duck. In Python it is perfectly valid to write the following code:
x = "Hello, world";
x = 42;
x = false;

In a statically typed language, the type checker would error out on the second line, because once x is assigned a string type, it cannot hold a numeric value.
Note that there are some other topics that crop up here that can conflate the issue. Rust is statically typed, but it does allow redefinition of variables, so the result is that you can write code that looks like dynamically typed code, even though it's entirely static. In Rust, this code fails to compile with a type error:
let x = "Hello, world!";
x = 42;

However, also in Rust, this code does compile:
let x = "Hello, world!";
let x = 42;

The difference is the let keyword. This explicitly redeclares the variable x and when this happens the new version of x is allowed to have a different type from the old version. Both versions of x are statically typed at compile time, so while this isn't great coding style, it's technologically no more complex than declaring a new variable with any other name and doesn't require any special support.
Ultimately there is no clear answer about what kind of system is best. The choice can dramatically limit the kind of code you can write, and especially impacts the job of the compiler/runtime implementer. In particular, dynamically typed means that types are checked at runtime, at the point of evaluating expressions. For example, the following Python code runs without errors:
x = "five"
if isinstance(x, int):
    y = x + 1

This code runs just fine in Python, because the if statement is false and the following line never executes. (If it did execute, this program would throw a TypeError and stop running.) However, a statically typed language like Rust would choke and die at compile time on the third line at the type-checking stage, because x is a string and you can't add 1 to a string, regardless of the fact that later on a reachability analysis could show that this code never executes.
This has a lot of other knock-on effects as well. If you've ever wondered how an interpreted language could literally be 100 times slower than C or C++, typing plays a huge role. In Python, every single operation like f() + g() needs to run some code that verifies the types of the left and right operands and potentially does some dynamic typing as well. In C/C++/Rust, the static type checker already verified at runtime that f() and g() return the proper types at compile time, and could potentially implement f() + g() in as little as a single assembly instruction.
C# is very much an odd exception in that it allows both static and dynamic typing in the same language. First, note that var does not violate static typing- this is implicit typing. The type is decided by the compiler at compile time, and then that is enforced. However, dynamic definitely does violate static typing rules. However, it's is made clear that the default and standard mode is static typing, with dynamic being used to add more flexibility in certain corner cases that are expected to be less common. Writing large parts of your program with dynamic is probably a good sign that you're doing something against the intention of the language designer.

A: All C# codebases use static typing, so C# is considered a mostly statically-typed language.
It also has support for optional dynamic typing, but many codebases don't use it.


text:
Q: GAE blobstore image upload . resp.sendRedirect("somepage.jsp") not working as expected
Note : My basic Blobstore image upload works fine ! (the sample
  tutorials part) now I am customizing it for my college project and
  facing some errors

these files are generated
WEB-INF\appengine-generated :

after this I have a code
resp.sendRedirect("onetimePassword.jsp");

but it is sending the page to

...:8888/_ah/upload/onetimePassword.jsp

and giving
Error 405 HTTP method GET is not supported by this URL
and no error message on my console

without the blobstore part the redirects are working correctly ! , how do I fix this ??

more codes :
<form id="form_register" name="form_register" method="post"
        enctype="multipart/form-data"
        action="<%= blobstoreService.createUploadUrl("/RegisterServlet") %>">

<input type="file" name="myFile" accept="image/*">

<servlet>
            <servlet-name>RegisterServlet</servlet-name>
            <servlet-class>controller.RegisterServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>RegisterServlet</servlet-name>
            <url-pattern>/RegisterServlet</url-pattern>

A: UPON FURTHER CHECKING I understood this. please correct me if i have understood anthing incorrect
"<%= blobstoreService.createUploadUrl("/RegisterServlet") %>"

sends you to /_ah/upload/blobfileinfo

and resp.sendRedirect("onetimePassword.jsp")
 use the current path of /_ah/upload and append onetimepass.jsp to it

resp.sendRedirect("/onetimePassword.jsp");

FIXED THE ISSUE FOR ME


text:
Q: Misunderstanding about Laplace operator Let $\Omega$ be a bounded subset of $\mathbb{R}^n$. We know that the Laplace operator
\begin{align}
\Delta \colon H_0^1(\Omega) \to L^2(\Omega)
\end{align}
admits an inverse operator
\begin{align}
A \colon L^2(\Omega) \to H_0^1(\Omega)
\end{align}
which is bounded and then (by Poincaré inequality and Rellich embedding theorem) can be viewed as a compact operator from $L^2(\Omega)$ to $ L^2(\Omega)$.
Now I have a basic problem: since $\Delta$ is unbounded, how can $A$ be a bounded operator? Wouldn't this contradict the open mapping theorem?

A: Basically, the problem is the norm of the spaces where you define the operators.
The Laplace operator $\Delta$ has domain $H^2_0 (\Omega)$. If one endows this Sobolev space
with its norm, then $\Delta:H^2_0 (\Omega) \to L^2(\Omega)$ is bounded. So there is no
contradiction with the open mapping thm.
On the other hand, note that we cannot apply
the open mapping theorem to $A: L^2(\Omega) \to H^2_0(\Omega)$, if we consider the $L^2$ norm on $H^2(\Omega)$ (since it is not a Banach space).


text:
Q: How to set qml property from c++ My main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>

#include "BackEnd.h"
#include "Execute.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

And my main.qml
Window
{
    id: mainWindow
    visible: true
    width: 280
    height: 570
    property var prop;
}

How can i set the prop property from c++? I found only solutions to create a qml object from c++.


text:
Q: Liquid Templates: How to do counter loop? This is only to quickly prototype something Adhoc... is it possible to do this in liquid? I just want to iterate over a number I set in the template.
for var=i; i<3; i++

A: Ah, here it is:
  {% for i in (1..4) %}
    {{ i }}
  {% endfor %}

 # results in 1,2,3,4


text:
Q: Geometric explanation of $\frac{x_2-x}{x_2-x_1}\cdot x_1 + \frac{x-x_1}{x_2-x_1} \cdot x_2=x$ I'd like to know if there is a geometric interpretation involving the real number line to the following equation, under the context of $x_1 \lt x \lt x_2$:

$\frac{x_2-x}{x_2-x_1}\cdot x_1 + \frac{x-x_1}{x_2-x_1} \cdot x_2=x \quad (\dagger)$

I see that the fractions are ratios between distances (that add up to $1$), but it is not apparent to me why scaling each of those ratios by $x_1$ and $x_2$ brings us to precisely $x$. Obviously, if we work out the algebra, the statement is true - but I am lacking the intuition as to what features the algebra is describing.
This type of equation is frequently encountered in arguments involving convexity, so I assume its origin was not a random algebraic finding, but rather a geometry-guided observation.

The closest thing I have to offering geometric intuition is rewriting $x_1$ and $x_2$ as $x-(x-x_1)$ and $x+(x_2-x)$, respectively, which allows us to rewrite the left hand side of $(\dagger)$ as:

$\frac{x_2-x}{x_2-x_1}\cdot \big [x-(x-x_1) \big ]+\frac{x-x_1}{x_2-x_1} \cdot \big [x+(x_2-x) \big]$

which we can rearrange as:

$\frac{x-x_1}{x_2-x_1}(x_2-x)-\frac{x_2-x}{x_2-x_1}(x-x_1)+x\cdot \left[\frac{x-x_1}{x_2-x_1}+\frac{x_2-x}{x_2-x_1}\right]$

I'm not sure if the commutativity of fractions is a particularly 'geometric' notion, but this attempt at rewriting seems, at least to me, to reveal why $(\dagger)$ is true. Basically, $(\dagger)$ appears to be reconstructing $x$ by decomposing $x_1$ and $x_2$ into components involving $x$.
Any insights would be appreciated!

A: $$\underbrace{(x_2-x)x_1}_{\text{EFHG}}+\underbrace{(x-x_1)x_2}_{\text{ACFD}}=\underbrace{xx_2}_{\text{ACHO}}-\underbrace{xx_1}_{\text{DEGO}}$$


text:
Q: How to Compare Date and set Button to set another background resources I have two dates in String and I compare them like this:
SimpleDateFormat formatter = new SimpleDateFormat("MMMM' 'dd', 'yyyy");

Date date1 = formatter.parse(final_date.toString());
Log.e("Taggal Selected:",date1.toString());

String str2 = "March 10, 2017";
Date date2 = formatter.parse(str2);

if (date1.compareTo(date2)<0)
{
   btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
   btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
} else if(date1.compareTo(date2)==0) {
   date.setText("Tanggal 2 sama 1");
} else {
   btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
   btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
   date.setText("Tanggal 1 lebih besar dari tanggal 2");
}

but it give me error when trying to change button with setBackgroundResource the error says...

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.Button.setBackgroundResource(int)' on a null object
  reference

the code just error when trying to change button or set enabled the button.. the code normally can use when trying to use textview...
where is my mistake?
this is my complete class..
public class ProductBuyActivity extends AppCompatActivity {

    private int year;
    private int month;
    private int day;
    private int user_id;
    public String token = "",difday,diff,val;
    static TextView date;
    ImageView imgbg;
    ProgressDialog pDialog;
    public Button btn_lunch,btn_dinner;
    Context context;
    public final GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
    public String final_date;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_buy_layout);
        SharedPreferences shared = getSharedPreferences(getResources().getString(R.string.shared), MODE_PRIVATE);
        final String userdata = shared.getString("user_data", "");
        Bundle extras = getIntent().getExtras();
        try {
            JSONObject userobject = new JSONObject(userdata);
            user_id = userobject.getInt("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AssetManager am = this.getApplicationContext().getAssets();

        TextView login_title = (TextView)findViewById(R.id.title);

        TextView product_name = (TextView)findViewById(R.id.product_name);

        product_name.setText(globalvar.getProductName());
        TextView product_portion = (TextView)findViewById(R.id.product_portion);

        product_portion.setText(String.valueOf(globalvar.getQty())+" Portion");

        imgbg = (ImageView) findViewById(R.id.imagebg);
        String detailimg = extras.getString("ImageURL");

        int total_price = 0;
        total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();

        if(globalvar.getFrom().equals("main")){
            total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();
        }else{
            total_price = Integer.valueOf(globalvar.getProductPrice()) * globalvar.getQty();
        }

        TextView product_price = (TextView)findViewById(R.id.product_price);
        product_price.setTypeface(font);
        product_price.setText(HelperClass.price(String.valueOf(total_price)));
        TextView txt = (TextView)findViewById(R.id.txt1);
        txt.setTypeface(font4);
        btn_lunch = (Button) findViewById(R.id.lunch);
        btn_dinner = (Button) findViewById(R.id.dinner);
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setTypeface(font);
        Button btn2 = (Button)findViewById(R.id.btn2);
        btn2.setTypeface(font);

        date = (TextView)findViewById(R.id.date);
        date.setTypeface(font);
        request_validation();
        // Get current date by calender

        // Button listener to show date picker dialog

            final Calendar c = Calendar.getInstance();
            year  = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day   = c.get(Calendar.DAY_OF_MONTH);

            // Show current date

            StringBuilder current_date = new StringBuilder()
                    // Month is 0 based, just add 1
                    .append(month + 1).append("-").append(day).append("-")
                    .append(year).append(" ");

            SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
            Date mydate = null;
            try{
                mydate = dateFormat.parse(current_date.toString());
            }catch(ParseException e){
                e.printStackTrace();
            }

            SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd','yyyy", Locale.getDefault());
            String final_date = custome_date.format(mydate);
            globalvar.setDate(final_date);
            date.setText(final_date);

        // Button listener to show date picker dialog

        date.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                show_date_picker();

            }

        });

        ImageView back = (ImageView)findViewById(R.id.back_button);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                go_back();
            }
        });

        globalvar.setOrderTime(0);

    }

    public void setdate(){
        GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
        difday = globalvar.get_diffday();
        int adddate=0;
        String logadd = String.valueOf(adddate);

        Log.e("Logadd",logadd);
        if(difday.equals("2")){
            adddate = 2;
            logadd = String.valueOf(adddate);
            Log.e("Logadd2",logadd);
        }else {
            adddate = 1;
            logadd = String.valueOf(adddate);
            Log.e("Logadd1",logadd);
        }
        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);

        // Show current date

        StringBuilder current_date = new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day+adddate).append("-")
                .append(year).append(" ");

        SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
        Date mydate = null;
        try{
            mydate = dateFormat.parse(current_date.toString());
        }catch(ParseException e){
            e.printStackTrace();
        }

        SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd','yyyy", Locale.getDefault());
        String final_date = custome_date.format(mydate);
        globalvar.setDate(final_date);
        date.setText(final_date);

    }

    public void go_checkout(View v){

        DatabaseHandler db = new DatabaseHandler(this);

        ShoppingCartList cartlist = new ShoppingCartList();
        cartlist.setProductId(globalvar.getProductId());
        cartlist.setProductName(globalvar.getProductName());
        cartlist.setProductPrice(globalvar.getProductPrice());
        cartlist.setImage(globalvar.getImage());
        cartlist.setQty(globalvar.getQty());
        cartlist.setDate(globalvar.getDate());
        cartlist.setOrderTime(globalvar.getOrderTime());
        cartlist.setProductSellingPrice(globalvar.getProductSellingPrice());
        cartlist.setuserID(user_id);
        //db.addCart(cartlist);
        if(globalvar.getFrom().equals("main")){
            if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(), user_id)){
                ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(), user_id);
            }

//        if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate())){
//
//            ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate());
//
//            cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());
//
//            db.updateChart(cart_detail);

        }else{
            db.addCart(cartlist);
        }

        if(globalvar.getFrom().equals("main")){
            if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){

                ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);

                cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());

                db.updateChart(cart_detail);

            }else{
                db.addCart(cartlist);
            }
        }
        else{
            if(db.Cart_ExistsPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){

                ShoppingCartList cart_detail = db.getCartPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);

                cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());

                db.updateChartPaket(cart_detail);

            }else{
                db.addCartPaket(cartlist);
            }
        }

        db.close();

        Toast.makeText(ProductBuyActivity.this, "Added To Shopping Cart", Toast.LENGTH_LONG).show();

        if(globalvar.getFrom().equals("main")){
            this.finish();
            Intent intent = new Intent(this, ShoppingCartActivity.class);
            startActivity(intent);
        }else{
//            this.finish();
//            Intent intent = new Intent(this, OrderPacketActivity.class);
//            startActivity(intent);
        }
    }

    public void go_addchart(View v){

        DatabaseHandler db = new DatabaseHandler(this);

        ShoppingCartList cartlist = new ShoppingCartList();
        cartlist.setProductId(globalvar.getProductId());
        cartlist.setProductName(globalvar.getProductName());
        cartlist.setProductPrice(globalvar.getProductPrice());
        cartlist.setImage(globalvar.getImage());
        cartlist.setQty(globalvar.getQty());
        cartlist.setDate(globalvar.getDate());
        cartlist.setOrderTime(globalvar.getOrderTime());
        cartlist.setProductSellingPrice(globalvar.getProductSellingPrice());
        cartlist.setuserID(user_id);
        if(globalvar.getFrom().equals("main")){

            if(db.Cart_Exists(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){

                ShoppingCartList cart_detail = db.getCart(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);

                cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());

                db.updateChart(cart_detail);

            }else{
                db.addCart(cartlist);
            }
        }else{
            if(db.Cart_ExistsPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id)){

                ShoppingCartList cart_detail = db.getCartPaket(globalvar.getProductId(), globalvar.getOrderTime(), globalvar.getDate(),user_id);

                cart_detail.setQty(cart_detail.getQty() + globalvar.getQty());

                db.updateChartPaket(cart_detail);

            }else{
                db.addCartPaket(cartlist);
            }
        }

        db.close();

        Toast.makeText(ProductBuyActivity.this, "Added To Shopping Cart", Toast.LENGTH_LONG).show();
        if(globalvar.getFrom().equals("main")){

            this.finish();
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    public void selectlunch(View v){

        btn_lunch.setBackgroundResource(R.drawable.lunch_active);

        btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);

        globalvar.setOrderTime(0);

    }

    public void selectdinner(View v){

        btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);

        btn_dinner.setBackgroundResource(R.drawable.dinner_active);

        globalvar.setOrderTime(1);

    }

    private void show_date_picker(){
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener,DatePicker.OnDateChangedListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();
            String difdays = globalvar.get_diffday();
            int adddate=0;
            String logadd = String.valueOf(adddate);
            Log.e("Logadd",logadd);
            if(difdays.equals("2")){
                adddate = 2;
                logadd = String.valueOf(adddate);
                Log.e("Logadd2",logadd);
            }else {
                adddate = 1;
                logadd = String.valueOf(adddate);
                Log.e("Logadd1",logadd);
            }
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH)+adddate;

            DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, this, year, month, day+adddate);

            //dpd.setInverseBackgroundForced(false);
            dpd.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dpd.getDatePicker().setMinDate(System.currentTimeMillis() - 1000 );
            dpd.setTitle("Select Day"); // Uncomment this line to activate it

            // Create a new instance of DatePickerDialog and return it
            return dpd;
        }
        @Override
        public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
            Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);

        }
        public void onDateSet(DatePicker view, int year, int month, int day) {
            GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();

            StringBuilder current_date = new StringBuilder()
                    // Month is 0 based, just add 1
                    .append(month + 1).append("-").append(day).append("-")
                    .append(year).append(" ");

            SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
            Date mydate = null;
            try{
                mydate = dateFormat.parse(current_date.toString());
            }catch(ParseException e){
                e.printStackTrace();
            }

            SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd', 'yyyy", Locale.getDefault());
            String final_date = custome_date.format(mydate);

            globalvar.setDate(final_date);
            date.setText(final_date);
            ProductBuyActivity product = new ProductBuyActivity();
            product.compareDate(final_date);
//            product.differenDate(final_date,"0");
        }

    }
    public void enabled_button(){
        btn_lunch.setBackgroundResource(R.drawable.lunch_active);
        btn_lunch.setEnabled(true);
        btn_dinner.setBackgroundResource(R.drawable.dinner_active);
        btn_dinner.setEnabled(true);
//                Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();

    }

    public void disabled_button(){
        btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
        btn_lunch.setEnabled(false);
        btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
        btn_dinner.setEnabled(false);
//                Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();

    }

    public void compareDate(String final_date) {
        try{
            Context context;
            SimpleDateFormat formatter = new SimpleDateFormat("MMMM' 'dd', 'yyyy");

            Date date1 = formatter.parse(final_date.toString());
            Log.e("Taggal Selected:",date1.toString());

            String str2 = "March 10, 2017";
            Date date2 = formatter.parse(str2);

            if (date1.compareTo(date2)<0)
            {
                System.out.print("Date2 is Greater than mydate1");
                date.setText("Tanggal 2 lebih besar dari tanggal 1");
////                btn_lunch.setBackgroundResource(R.drawable.lunch_inactive);
//                btn_lunch.setEnabled(false);
////                btn_dinner.setBackgroundResource(R.drawable.dinner_inactive);
//                btn_dinner.setEnabled(false);
                    enabled_button();
//                Toast.makeText(getBaseContext(), "date2 is Greater than my date1", Toast.LENGTH_LONG).show();
            }
            else if(date1.compareTo(date2)==0){
//                Toast.makeText(getBaseContext(), "Same Date", Toast.LENGTH_SHORT).show();
                System.out.print("Same Date");
                date.setText("Tanggal 2 sama 1");
            }
            else{
//                disabled_button();

                System.out.print("Date1 is Greater than mydate2");
                date.setText("Tanggal 1 lebih besar dari tanggal 2");
            }

        }catch (ParseException e1){
            e1.printStackTrace();
        }
    }

    public void request_token() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.API) + "oauth/token",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("respon token", response);

                        //Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();

                        //String token = "";

                        try {

                            JSONObject return_val = new JSONObject(response);
                            token = return_val.getString("access_token");

                        } catch (JSONException e) {
                            e.printStackTrace();
                            //Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }

                        SharedPreferences.Editor editor = getSharedPreferences(getResources().getString(R.string.shared), MODE_PRIVATE).edit();
                        editor.putString("token", token);
                        editor.commit();

                        request_validation();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(ProductBuyActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("grant_type", getResources().getString(R.string.grant_type));
                map.put("username", getResources().getString(R.string.username));
                map.put("password", getResources().getString(R.string.password));
                map.put("client_id", getResources().getString(R.string.client_id));
                map.put("client_secret", getResources().getString(R.string.client_secret));
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(15000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    private void go_back(){
        this.finish();
    }
    private void showPDialog() {
        pDialog = new ProgressDialog(ProductBuyActivity.this, R.style.MyTheme);
        //pDialog.setTitle("Loading... Please Wait");
        pDialog.setCancelable(false);
        pDialog.setProgressStyle(android.R.style.Widget_Material_ProgressBar_Large);
        pDialog.show();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public void onBackPressed() {

        go_back();

    }

}

A: Use below to get different and achieve your goal..
public static void differenDate(String startDate, String endDate) {
    Log.d("S D", "--->   S D = " + startDate);
    Log.d("E D", "--->   E D = " + endDate);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.sss");
    Date sDate = null;
    Date eDate = null;
    try {
        sDate = format.parse(startDate);
        eDate = format.parse(endDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // final int MILLI_TO_HOUR = 1000 * 60 * 60;
    // int diff = (int) ( (eDate.getTime() - sDate.getTime()) / MILLI_TO_HOUR );
    System.out.println("DIFF = " + (eDate.getTime() - sDate.getTime()));

    int calcDiff = (int) (eDate.getTime() - sDate.getTime());

}

A: ProductBuyActivity product = new ProductBuyActivity();

You instantiate your activity without any intent. Thus, onCreate would not be called.
This makes your compareDate method getting confused by trying to use product's btn_lunch and btn_dinner, which will be uninitialized - therefore, is null
compareDate() is a public method, you can simply call compareDate(final_date); you can try to use
ProductBuyActivity.this.compareDate(final_date);

There is no need to instantiate a new Activity Project.
EDIT:
If fully refactoring your code is not an option, then you need to have a Listener callback for your DatePickerDialog.
Leave your DatePickerDialog static.
Do not implement OnDateSetListener interface on your fragment.
Instead, implement it on your Activity
public static class DatePickerFragment extends DialogFragment implements DatePicker.OnDateChangedListener

public class ProductBuyActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener

Move your onDataSet to Activity, overriding the Interface
public class ProductBuyActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{

    .....

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        GlobalVar globalvar = (GlobalVar)GlobalVar.getAppContex();

        StringBuilder current_date = new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" ");

        SimpleDateFormat dateFormat = new SimpleDateFormat("M-dd-yyyy", Locale.getDefault());
        Date mydate = null;
        try{
            mydate = dateFormat.parse(current_date.toString());
        }catch(ParseException e){
            e.printStackTrace();
        }

        SimpleDateFormat custome_date = new SimpleDateFormat("MMMM' 'dd', 'yyyy", Locale.getDefault());
        String final_date = custome_date.format(mydate);

        globalvar.setDate(final_date);
        date.setText(final_date);
        //ProductBuyActivity product = new ProductBuyActivity();
        //product.compareDate(final_date);
        compareDate(final_date);
    }
}

EDIT 2:
Change your DatePickerDialog instantiation:
DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog, (ProductBuyActivity)getActivity(), year, month, day+adddate);


text:
Q: Convert String into special - splitting an NSString I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?

A: the following gives you the desired result:
NSString *_inputString = @"\"mocktail, wine, beer\"";
NSLog(@"input string : %@", _inputString);
NSLog(@"output string : %@", [_inputString stringByReplacingOccurrencesOfString:@", " withString:@"\", \""]);

the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"

A: You need to use:
NSArray * components = [myString componentsSeparatedByString: @", "];

A: NSString *string = @"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:@","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];

for (NSString *trimmedString in array) {
    NSString *newString = [NSMutableString stringWithFormat:@"'%@'", trimmedString];
    [newArray addObject:newString];
}

//merge new strings
NSString *finalString = [NSString stringWithFormat:@"%@", [newArray objectAtIndex:0]];

for (NSInteger i = 1; i < [newArray count]; i++) {
        finalString = [NSString stringWithFormat:@"%@, %@", finalString, [newArray objectAtIndex:i]];
}

A: Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D


text:
Q: SPSS Python Error Getting the following error when trying to run SPSS from an external Python IDE.
import spss

yields the following error
Traceback (most recent call last):
  File "C:\Documents and Settings\USER\workspace\SPSS\src\NE ASQ 2010.py", line 6, in <module>
    import spss
  File "C:\Python26\Lib\site-packages\spss180\spss\spss.py", line 16, in <module>
    error = errCode()
  File "C:\Python26\Lib\site-packages\spss180\spss\errMsg.py", line 24, in __init__
    self.errMsg = errTable['okay'][str(0)]
KeyError: 'okay'

Ran the Python essentials plug-in with no errors.  Funny thing is that I dont get an error when I run this in a syntax
BEGIN PROGRAM PYTHON.
import spss
num = spss.GetVariableCount()
print num
END PROGRAM.

Any help will be much appreciated.
Brock

A: I believe I figured out the issue. I needed to configure Eclipse to see the external python modules that are created when you install the SPSS/Python plugin.  I had to set a reference to the modules when configuring the project.
Once I did that, it looks like I am up and running!


text:
Q: Combine tables with pivot I have three different table with values, I got an output of first image but I want output as second Image.
Query
select HREmpParamValues.EmpParamID,HREmpParamValues.EmployeeId,HREmpParamValues.EntityTypeParamID,HREmpParamValues.ParamValue,
ORG_EntityTypeParam.ParamValueEntityID,ORG_EntityTypeParam.EntityTypeParamID,ORG_EntityTypeParam.Description,ORG_EntityTypeParam.DataTypeEntityID,ORG_EntityMaster.EntityId,ORG_EntityMaster.EntityTypeId,ORG_EntityMaster.Description
 from HREmpParamValues
Left Join ORG_EntityTypeParam on ORG_EntityTypeParam.EntityTypeParamID =  HREmpParamValues .EntityTypeParamID
Left Join ORG_EntityMaster on ORG_EntityMaster.EntityId = HREmpParamValues.ParamValueEntityID
where HREmpParamValues.EmployeeId=31

Output

Desired Output


text:
Q: Cron Scheduler - every quarter end third Sunday @ 3:30 AM CST Actually I am trying to schedule an application , which has to be run at

Cron expression to run application job for every end of quarter on 3rd Sunday at 3:30 AM CST

currently am using 0 */10 * ? * * - which runs for every ten minutes.
when I search on online ,this link https://crontab.guru/every-quarter
0 0 1 */3 * this would run for every quarter I guess.
But for my requirement , which I stated above, am not sure actually.
but , i referred some of the previous questions and some trial and error , I reached something like this 30 3 15-21 */3 SUN but am not sure. Please give your thoughts

A: OK .. for spring scheduler cron expression, below is my best bet
0 30 03 15-21 3,6,9,12 SUN
should work i think. tested partially. since, the above expression will run only on june.


text:
Q: Getting jq output in single line for JSON output using Bash I'm calling the TestRail API through a Bash script and getting below output using curl and jq, later I'm parsing it and putting into file. It gives me result fine but keys in different lines, I expect one block should give result in one line. How can I get output in single line using jq and bash?
I tried jq -c and it works but only thorugh CLI, via Bash script file it fails. Not sure what is the wrong when running different way and obviously we need to run through Bash file only.
Code:
jsonOutput=`curl -u $user:$key -X GET -H 'Content-Type: application/json' --insecure --silent $url/index.php?/api/v2/get_results_for_run/$runID | jq -r`

for runDetails in ${jsonOutput}; do
    IFS=","

    if [[ "${runDetails}" = "id" ]] || [[ "${runDetails}" = "status_id" ]]; then
        runDetails=$(echo "${runDetails}" | sed 's/\"//g' | sed 's/{//g' | sed 's/}//g')

        testcaseID=$(echo "${id}")
        testcaseResult=$(echo "${test_id}")
        echo -e "${testcaseID}\t${testcaseResult}" >> ${reportsFile}
    fi
done

Actual:
"id": 425179,
"test_id": 4713650

"id": 425178,
"test_id": 4713649

Expected:
425179, 4713650
425178, 4713649

jq output:
[
  {
    "id": 425179,
    "test_id": 4713650,
    "status_id": 5,
    "created_by": 41,
    "created_on": 1510161282,
    "assignedto_id": null,
    "comment": null,
    "version": null,
    "elapsed": null,
    "defects": null,
    "custom_step_results": [
      {
    "expected": "",
    "actual": "",
    "status_id": 3
      }
    ],
    "custom_severity": null
  },
  {
    "id": 425178,
    "test_id": 4713649,
    "status_id": 1,
    "created_by": 41,
    "created_on": 1510161195,
    "assignedto_id": null,
    "comment": null,
    "version": null,
    "elapsed": "10s",
    "defects": null,
    "custom_step_results": [
      {
    "expected": "",
    "actual": "",
    "status_id": 3
      }
    ],
    "custom_severity": null
  }
]

A: jq can alone parse the JSON to the desired format:
curl ... | jq -r '.[] | (.id | tostring) + ", " + (.test_id | tostring)'


text:
Q: How do you hide generated .js files VS Code? I have the following settings.json
{
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.js": { "when": "$(basename).tsx" }
    }
}

I would like to exclude generated .js files produced by .ts and .tsx files. Is there a syntax to specify both .ts and .tsx in the when?


text:
Q: I'm facing problem in retriving cookies.get() value in reactjs, it shows me undefine When I try to retrive cookie value from localhost.
cookies.set('token', payload.token, {maxAge: 3600_000,secure:true, domain:'http://localhost:3001' })

cookies.set("user", JSON.stringify(payload.user),{maxAge: 3600_000,secure:true, domain: 'http://localhost:3001' })

//get cookie value undefine
console.log("Login success token",  cookies.get('token'))

My cookies storage output

what is happening with my code I don't understand it.

A: In the image you can see the cookie has a field HttpOnly: true. When this field is set to true it is not possible to retrieve cookies in the frontend using JS. Here you can read a bit more about this field https://owasp.org/www-community/HttpOnly
This field is useful as it protects your site against XSS attacks


text:
Q: Is it possible to use the interface on a remote machine which I can SSH into? I can SSH into a machine which has a wifi adapter connected, with interface wlan0. Can I use its interface (wlan0) on my client machine ?
As an example, if I want to run iwconfig (or any tool which can use wlan0) on the interface without it being installed on the server, but is installed on the client machine.
Both the server and client are running linux.

A: If the wifi card is actually a USB adapter, then yes, you can do it.
The solution to this is the use of a technique called USB over IP. There is one Open Source solution, plus 2 commercial ones.
The OS solution is usbip. You will have to download the server-side package on the remote machine, and the client side-package on your own machine. It is very easy to use, and the page above has all the details you wish.
After the final command,
  sudo usbip -a <server-ip> device_to_be_attached

the USB device will apear as if it were on your pc. Careful when you try to bring it up as a network interface, because, if you let network manager configure your routing table, it will completely mess it up. It is wiser to turn network-manager off before staring the usbip connection, and do it all by hand. But it can be done.
The commercial solutions I know are
Fabula-Tech USB-over-Network:
http://www.fabulatech.com/usb-over-network.html
Eltima Software USB Network Gate:
http://www.eltima.com/products/usb-over-ethernet
There may be others, cannot say for sure.

A: Why not proxy your local requests through that box?
$ ssh -ND 8080 your.machine

This will act as a SOCKS server on your local machine and any requests will be forwarded to your.machine.  Of course, this assumes that on the remote machine the wifi is set up and the default route is through that wlan0 device.  You can do that with iwconfig on the remote machine.
What you imply to ask, whether you can forward the actual wlan0 device to your machine, that's not possible currently.
Edit:
Forgot to mention that routing traffic through that SOCKS proxy to the other machine requires client support, e.g. in firefox you'd have to adjust your network settings.  It's not a transparent tunnel.
In case you wanted a local device that will route traffic through the other machine (where in turn it would route the traffic through wlan0) you could use a simple tunnel or a VPN.
$ ip tunnel add tuntowlan0 mode gre remote <remote-address>

but this will require some fiddling with the routing table on the local machine if you didn't want all traffic to go through there, and make sure ip forwarding is enabled on the remote box.


text:
Q: Java to AIDL utility I have an existing Java interface I'd like to expose via AIDL.
Is there a way to auto generate the AIDL from the Java?
I am aware of Java2IDL for Corba code, so this would be something
similar to that.

A: I think it's hard to do it this way as both Java and AIDL are different languages. Also, it might happen that you are sending and receiving user defined types through AIDL interfaces and that requires additional handling in AIDL. You need to create a separate AIDL file for each parsable type.

A: To my knowledge there is no such tool. However, so as aidl differs from java interfaces some decisions should be made by programmers. That's why it's more likely that these tools will not appear.


text:
Q: Java - Which types of classes are these; which is the anonymous inner class? I've read several online articles which contradict each other. I thought this would be an example of an anonymous inner class:
button.addActionListener(new ActionListener() {
    public void actionPerfored(ActionEvent e) {
       // do something.
    }
});

However, I've also seen this described as an anonymous inner class:
ActionListener myListener = new ActionListener() {
    public void actionPerformed(ActionEvent event) {
          // do something.
    }
};
button.addActionListener(myListener);

Which is which, and why? Thank you!

A: Both of them are. The second one is just assigned to a variable before being added as an action listener.
This is the same as the difference between
myList.add(new String("myString"));

and
String s = new String("myString");
myList.add(s);

it has nothing to do with anonymous classes.

A: Both are anonymous inner classes. In the second case you are storing a reference to the anonymous class just so that you can call some methods on it later.

A: Like Richante said, they both are.
Think about it, they both are unnamed and are defined inside another class.

A: Both are actually examples of Anonymous inner class. In First example, anonymous inner class is provided when passing an argument to addActionListener() method. In second example a reference to anonymous inner class is created.


text:
Q: nlohmann json parse error at memory location I'm making a C++ program that will (eventually) take some information from each page on an api endpoint and then add each page to an array. I'm using cpr as my requests library which is fetching the pages correctly as I need them and then I'm using nlohmann's json library to parse the json page result and then use it later on.
My code:
#include <iostream>
#include <cpr/cpr.h>
#include <nlohmann/json.hpp>
#include <Windows.h>
int main()
{
    using namespace nlohmann;
    auto response = cpr::Get(cpr::Url{ "https://api.hypixel.net/skyblock/auctions" });  // |
    json res = json::parse(response.text);                                              // | These 3 lines will get the number of pages
    int iNumPages = res["totalPages"];                                                  // |
    json* arrPages = new json[iNumPages];            //Define the array with the number of pages
    for (int x = 0; x < iNumPages; x++) {
        std::cout << x; //Just to see which page the program gets to
        auto pageRes = cpr::Get(cpr::Url{ "https://api.hypixel.net/skyblock/auctions?page="+x });  // | These two lines should take the json response from the
        arrPages[x] = json::parse(pageRes.text);                                                   // | api and put it into the array in the place of the page no
    }
}

My issue is that in the for loop the program is able to get up to page 1 or 2 (the pages start at 0, so it can do around 2-3 pages) before crashing and throwing the following error:
Unhandled exception at 0x7627E7B2 in xxxxxxxxxx.exe: Microsoft C++ exception: nlohmann::detail::parse_error at memory location 0x0021F450.

Admittedly, I'm not great at debugging and have sort of self-taught myself C++ so there are definitely many gaps in my knowledge of how it all works, however I have tried different ways of putting the data into the array like defining the array as json arrPages[99] in case it was an issue with the array but this issue still persists.
I really hope someone could share any knowledge on how to fix this issue, and I thank you in advance. Have a nice day!

A: Your code:
"https://api.hypixel.net/skyblock/auctions?page=" + x;

will produce a sequence of strings:
"https://api.hypixel.net/skyblock/auctions?page="
"ttps://api.hypixel.net/skyblock/auctions?page="
"tps://api.hypixel.net/skyblock/auctions?page="
"ps://api.hypixel.net/skyblock/auctions?page="
"s://api.hypixel.net/skyblock/auctions?page="

That's NOT a concatenation! Try using std::string
std::string("https://api.hypixel.net/skyblock/auctions?page=") + std::to_string(x)


text:
Q: angularjs filter object by key and ng-model for firebase i have data like this in my firebase:
rootNode:{
    "key1":value1,
    "key2":value2,

  }

i am doing an ng-repeat when i get the data from async call
  <input type="text" ng-model="searchText"/>

{{key}}

The list does show up fine but it is not filtering the serachText.
i want the list to show key1,key2,etc and the filter should work on the keys.
Is something wrong with my data structure?
I can use array of objects but firebase does not link arrays so i am looking for a object based solution


text:
Q: Does anyone know where I can find "proof" that SQL's Fiber mode is barely faster than regular thread mode on Win 2008 R2 I remember seeing a PDC presentation on the Windows Kernel regarding Threads vs Fibers and in it Mark R. mentioned that this caused SQL's Thread mode to run almost as fast as Fiber mode, but with added stability.
Does anyone have a link to this? Or similar?
I'll use this as a motivation to push people to 2008R2

A: I don't know of anybody using Fiber mode for SQL after all these years and I cannot ever recall anyone ever telling me its a good idea. I know the following is rather old, but take a quick peek at this
http://msdn.microsoft.com/en-us/library/aa175385%28v=sql.80%29.aspx
However this article from Linchi gives a more positive spin
http://sqlblog.com/blogs/linchi_shea/archive/2009/05/04/performance-impact-thread-mode-vs-fiber-mode.aspx

A: Some of the more interesting comments I have found on StackOverflow:
https://stackoverflow.com/questions/2946111/currentthread-processthread-objects/2946266#2946266
https://stackoverflow.com/questions/796217/what-is-the-difference-between-a-thread-and-a-fiber


text:
Q: "Encrypted" html code for google search? When I view the page source of google search, for example http://www.google.com/search?q=test,

the html code looks messy and I can't understand a thing from it (see below).
Is it on purpose?
 What is this "encryption" called and how do I create it for normal html?
Thanks!
function _tvn(a,b){var c=parseInt(a,10);
return isNaN(c)?b:c}function _tvf(a,b){var c=parseFloat(a);
return isNaN(c)?b:c}function _tvb(a,b){return a=="true"?e:a=="false"?k:b}function _tvv(a)
{return!!a}function n(a,b,c){(c||m) aa=function(){return m.bv.m==1};n("sb",aa);

A: This is not HTML, it's javascript.
And it's not "Encrypted", it's compressed (minified), they change all the function names to be as short as possible, all the variable names to be as short as possible, and just compress it as much as possible by removing lines spaces and everything that is not useful...
There are many internet applications and methods to do that...
It's done to reduce the page size and to reduce loading time... there are many applications that reverse that compression...

A: The HTML isn't encrypted, it's just minified, or in fact, its just the JS that is minified. The HTML is there, in normal format, just need to look for it in the right place. Direct copy of the html from that page, from the source code.

A: Google has a library called Closure Compiler that it uses to optimize ("minify") JavaScript. This has the side effect of making it difficult to read ("obfuscated") and to copy. The library is free, so you can use it with your code, and alternatives are also available (see the other answers).

A: Google run their JS through an optimiser to increase speed of download and execution.

A: The JavaScript has been compressed and obfuscated, which makes it difficult to read and understand, while decreasing the file size to optimise loading times.
If you'd like to do something similar with your JavaScript have a look at YUI Compressor.

A: jsbeautifier at http://jsbeautifier.org can unminify, unpack, and unobfuscate.


text:
Q: Bootstrap angular datepicker ngbDatepicker doesnot overflow on the ngbPanelContent I have use the ngbDatepicker in the form as below
<ngb-panel>
              <ng-template ngbPanelTitle>

                  <ui-switch (change)="onChange($event,2)" [checked]="professionalLearningEvent.sportsPractive" size="small"></ui-switch>
                  Will your sports practice be
                    affected ?

              </ng-template>
              <ng-template ngbPanelContent>

  <input class="form-control" [formControl]="control" ngbDatepicker [dayTemplate]="getDayTemplate()" #d="ngbDatepicker" [ngClass]="{ 'is-invalid': isFieldInvalid(control) }">

    <button class="btn btn-sm btn-outline-secondary" (click)="d.toggle()" type="button">

    </button>

              </ng-template>
            </ngb-panel>

The datepicker UI is not overflow. Try to find some solution but not able to.

A: add container='body' to input element.
Example:
<input type="text" autocomplete="off" name="dp" ngbDatepicker container="body">

Github Link

A: The issue was the overflow from the accordian card
Here is the solution just add the below css to override the bootstrap css
 .accordion .card {
      overflow: visible !important;
    }


text:
Q: repository validation What's the best way to validate a model when using mvc with repository?
I look for examples but I didn't find any that is exactly what I need.
Assuming I have a model with 5 properties.. 3 of them with dataannotations.. and I have some validations that I need to check in database before insert.
I need something like 'User.IsValidToInsert' to check if its valid. But I want to use 'ModelState.IsValid' too, cause I dont want to check manually all properties with dataannotations in 'IsValidToInsert'.
How can I do this? Should I set validations that access database in 'IsValidToInsert'? Should I pass 'User' and 'ModelState' like parameters to repository class?

A: You should be using a View Model that is specific to the view. If you have a Create action to create a Product, create a ProductCreate view model. You can put the data annotations (or Fluent Validation, etc.) that is specific to creating a product. This will be the model for your View/Controller. If you have an Edit page, then create a ProductEdit view model.
Now if you have additional logic (such as validating if a user already exists, then you should put that in a service layer. Your controller should be as simple as possible. You post your view model, convert it to a domain model and pass it to the service layer if necessary.
[HttpPost]
public ActionResult Create(ProductCreate model)
{
    // simple validations
    if( !ModelState.IsValid )
    {
        return View(model);
    }

    // Domain Model / Entity
    Product product = // create a product from your model here

    // service layer
    ProductService.Add(product);

    return RedirectToAction("Index");
}


text:
Q: Can't send a correct POST request in Java (Android Studio) I'm creating an app for asking/answering questions.
I have a problem with POST request when I ask questions.
I've tried to use something like this in terminal
curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "support@mlab.com"}' http://your-app-name.herokuapp.com/contacts

and it worked good.
But when I try to send a POST request in AndroidStudio my parameters (such as name, lastname, email and etc) won't send.
I tried to use https://github.com/kevinsawicki/http-request. The request is send (I know that because it shows the date of the request) but without any parameters.
What should be changed in my code so it would work correctly?
Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");

A: Try like this..
Map<String, Object> params = new LinkedHashMap<>();
params.put("firstName", "Gena");
params.put("lastName", "Bukin");

JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params);
    /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param serverURL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&also=another
         * returns response as a JSON object
         */
        public JSONObject POST(String serverURL, Map<String, Object> params) {
            JSONObject jsonObject = null;
            try {
                URL url = new URL(serverURL);

                Log.e(TAG, params.toString());
                StringBuilder postData = new StringBuilder();

                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                Log.e("POST", serverURL + ":" + params.toString());
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();

                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }
                jsonObject = new JSONObject(sb.toString());
            } catch (Exception e) {
                //e.printStackTrace();
            }
            return jsonObject;
        }

A: Basically your curl requests sends the user data in JSON format in the request body. Your Java code tries to send the data in the request as form data which is something different and probably not accepted by the server.
You might need to change your code to use the HttpRequest.send(...) method instead of form:
JSONObject json = new JSONObject();
json.put("firstName", "Gena");
json.put("lastName", "Bukin");
json.put("email", "support@mlab.com");

HttpRequest
    .post("https://safe-citadel-91138.herokuapp.com/questions")
    .contentType("application/json")
    .send(json.toString());

Furthermore in the curl call you are using accesses a different url than in the Java snippet http://your-app-name.herokuapp.com/contacts vs https://safe-citadel-91138.herokuapp.com/questions maybe you are talking to the wrong endpoint as well?
You might want to take a look at some Java to JSON mapping library like gson for the transformation of your Java objects to proper JSON or use Android's JSONObject class.
UPDATE:

*

*Added link to gson for JSON mapping

*Updated code snippet to use JSONObject for the JSON mapping

A: try this hope it'll work
public JSONObject getJSONFromUrl(String url_, JSONObject jsonObject) {

    try {
        URLConnection urlConn;
        DataOutputStream printout;

        URL url = new URL(url_);
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setConnectTimeout(30000);
        urlConn.setReadTimeout(30000);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("Accept", "application/json");

        urlConn.setRequestProperty("Authorization", "token"); // If Applicable
        urlConn.connect();
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.writeBytes(jsonObject.toString());
        printout.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        printout.close();
        reader.close();
        json = sb.toString();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Applog.e("response", jObj + "");
    return jObj;

}

A: I have just tried to create an User and it worked. You can refresh the link u have shared to check the created User.
This is what I have tried
String endPoint= "https://safe-citadel-91138.herokuapp.com/questions";
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(endPoint);
            post.addHeader("Content-Type", "application/json");
            JSONObject obj = new JSONObject();

            obj.put("firstName", "TESTF");
            obj.put("lastName", "TESTL");
            obj.put("email", "support@mlab.com");

            StringEntity entity = new StringEntity(obj.toString());
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
}catch (Exception e){

        }

UPDATE
BTW I have used json jar from this link


text:
Q: How to float left content and fix right content? I am working on a structure to have a top navigation fixed, a left nav to be scrollable and a right nav to be fixed.
I have created a fiddle here. just need help with the css.
http://jsfiddle.net/PxbX9/
#header {
    position:fixed;
    background:red;
    width:700px;
    height:30px;
}
#left-block {
    float:left;
    width:350px;
    background:blue;
    height:1000px;
    margin-top:30px;
}
#right-block {
    float:left;
    width:350px;
    height:1000px;
    background:pink;
    margin-top:30px;
    .fixed-block {
        postion:fixed;
        height:1000px;
    }

A: This can be achieved by restructuring your CSS to this:
#header {
    position:fixed;
    background:red;
    width:700px;
    height:30px;
}
#left-block {
    float:left;
    width:350px;
    background:blue;
    height:1000px;
    margin-top:30px;
}
#right-block {
    display: inline-block;
    float:right;
    width:350px;
    height:1000px;
    background:pink;
    margin-top:30px;
    position:fixed;
}

I've only made CSS changes to the #right-block selector.

*

*Removed the class .fixed-block, which had a typo in the form of postion (should be position).

*position: fixed; has been added to the #right-block selector.

*display: inline-block; and float: right; have been added also.

DEMO
Hope this helps.

A: Take a look at that Working Fiddle
Pure CSS solution, Very Dynamic, Totally responsive.
HTML:

CSS:
*
{
    margin: 0;
    padding: 0;
}
html, body, .Container
{
    height: 100%;
}
    .Container:before
    {
        content: '';
        height: 100%;
        float: left;
    }
.HeightTaker
{
    position: relative;
    z-index: 1;
}
    .HeightTaker:after
    {
        content: '';
        clear: both;
        display: block;
    }
.Wrapper
{
    position: absolute;
    width: 100%;
    height: 100%;
}

.Header
{
    /*for demonstration only*/
    background-color: #bf5b5b;
}
.Wrapper > div
{
    height: 100%;
    overflow: auto;
}

.LeftContent
{
    /*for demonstration only*/
    background-color: #90adc1;
}
.RightContent
{
    float: right;
    width: 500px;
    /*for demonstration only*/
    background-color: #77578a;
}


text:
Q: Why do I get this error ' at=error code=H10 desc="App crashed" ' on Heroku? I have deployed my application written with Go to Heroku. As soon as I open app it gives me error. I check logs it shows this error.
PS. I am listening by calling http.ListenAndServe(":"+os.Getenv("PORT"), nil). I have set PORT environment variable to :80.


text:
Q: How to clear search input field with javascript when using Google Maps v3 Autocomplete Form I am using Google maps v3 api to autocomplete an address form but I do not want to use a general search field like in the example (https://google-developers.appspot.com/maps/documentation/javascript/examples/full/places-autocomplete-addressform).
I am trying to make the street address field the search field as well as the street number and street name field only. I found this example on JS fiddle (https://jsfiddle.net/smartystreets/0c9fy73v/) I cannot replicate it.
I tried turning autocomplete=off but does not work on chrome (for elementId('autocomplete'))
I tried hiding the route and street input elements and setting the input id value to empty.
document.getElementById('autocomplete').value = '';

Then using the hidden input fields to rebuild that form input w/
document.getElementById('autocomplete').value = document.getElementById('street_number') + ' ' + document.getElementById('route');

Any ideas what I am doing wrong? Why wont the search field clear?
This is my HTML for my search/address field:

      address:
      <input type="text"   id="autocomplete"
         name="street" placeholder="Street address, PO Box, etc.">
      <input type="hidden" id="route" disabled="false">
      <input type="hidden" id="street_number" disabled="false">
      <input type="text"  name="address1" placeholder="(Optional) Apartment, Suite, Floor, etc.">

This is my inline JS

  var placeSearch, autocomplete;
  var componentForm = {
     street_number: 'short_name',
     route: 'long_name',
     locality: 'long_name',
     administrative_area_level_1: 'short_name',
     postal_code: 'short_name'
  };

  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {types: ['geocode']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {

    document.getElementById('street_number').value = '';
    document.getElementById('route').value = '';
    document.getElementById('locality').value = '';
    document.getElementById('administrative_area_level_1').value = '';
//  document.getElementById('country').value = '';
    document.getElementById('postal_code').value = '';

    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
   for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
       var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
      }
    }
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
</script>

A: If you really want to clear the search input field after the user clicks on the address from autocomplete, try setting the input (id=autocomplete) value to empty after you get the place.
function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    /* Your other code */

    document.getElementById('autocomplete').value = '';
}

I just made a demonstration for you to check the behavior. You can see it here http://jsbin.com/mugasav/1/edit?html,js,output


text:
Q: Autofilter excel using java poi I am trying to filter an excel sheet using POI class and to set the filter when i used this :
CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();
CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);
got below mentioned error on "CTFilterColumn".
Multiple markers at this line
    - The method insertNewFilterColumn(int) from the type CTAutoFilter refers to the
     missing type CTFilterColumn
    - The type org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFilterColumn
     cannot be resolved. It is indirectly referenced from required .class files
    - CTFilterColumn cannot be resolved to a type
Entire code :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.ComparisonOperator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;

public class Test1 {

    public static void main(String[] args) {
        try {
            //To read values and enable auto filter
            FileInputStream fileIn = new FileInputStream("./XMLs/Test001.xlsx");

            XSSFWorkbook my_workbook = new XSSFWorkbook(fileIn);

            XSSFSheet my_sheet = my_workbook.getSheet("Sheet1");
            CTAutoFilter sheetFilter = my_sheet.getCTWorksheet().getAutoFilter();

            CTFilterColumn myFilterColumn = sheetFilter.insertNewFilterColumn(0);

Instead of this "import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTAutoFilter;" i tried import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
But CTFilterColumn is not even listed in suggestions. Please help.
Is it because of some missing jar files, please help.

A: Promoting a comment to an answer
This is covered in this Apache POI FAQ Entry -  I'm using the poi-ooxml-schemas jar, but my code is failing with "java.lang.NoClassDefFoundError: org/openxmlformats/schemas/something". The key section is:

There are two jar files available, as described in the components overview section. The full jar of all of the schemas is ooxml-schemas-1.3.jar, and it is currently around 15mb. The smaller poi-ooxml-schemas jar is only about 4mb. This latter jar file only contains the typically used parts though.
Many users choose to use the smaller poi-ooxml-schemas jar to save space. However, the poi-ooxml-schemas jar only contains the XSDs and classes that are typically used, as identified by the unit tests. Every so often, you may try to use part of the file format which isn't included in the minimal poi-ooxml-schemas jar. In this case, you should switch to the full ooxml-schemas-1.3.jar. Longer term, you may also wish to submit a new unit test which uses the extra parts of the XSDs, so that a future poi-ooxml-schemas jar will include them.

So, short term you need to swap out your small poi-ooxml-schemas jar for the full ooxml-schemas-1.3 jar. Longer term, if you submit a unit test to Apache POI which uses these extra classes, it'll be included in a future small schema jar.
Maven artifact details for the full schema are covered here on the Apache POI site


text:
Q: Multilabel classification using ResNet - loading sample using the dataloader takes a long time I need to implement a ResNet-based multiclass classifier, and I am using this notebook as a starting point. At the moment, I am just going through the notebook, checking that all steps work fine. When I try to load a sample with the dataloader (command: sample = next(iter(train_loader))), I get no results even after waiting for more than an hour. Why is that?
The dataloader is defined in this cell:
#Pre-processing transformations
data_transforms = transforms.Compose([
        transforms.Resize((224,224)),
        transforms.ToTensor(),
        transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))
    ])

#Getting the data
cardata = CarDataset("./content/content/carimages/car_ims", transform=data_transforms,translation_dict=translation_dict)

#Split the data in training and testing
train_len = int(cardata.__len__()*0.8)
test_len = int(cardata.__len__()*0.2)
train_set, val_set = torch.utils.data.random_split(cardata, [train_len, test_len])

#Create the dataloader for each dataset
train_loader = DataLoader(train_set, batch_size=16, shuffle=True,
                                num_workers=4, drop_last=True)
test_loader = DataLoader(val_set, batch_size=16, shuffle=False,
                               num_workers=4, drop_last=True)

If I try loading the data on the GPU using
train_set.cardata.to(torch.device("cuda:0"))  # put data into GPU entirely
train_set.to(torch.device("cuda:0"))

I get the error 'Subset' object has no attribute 'cardata'. Am I doing something wrong? Is it just normal that the dataloader takes so long to load the dataset images? Thanks!

A: It seems there is no error at calling train/val set and loader of provided code. There might be an error inside of CarDataset() class, or maybe setting num_workers=0 could help.
Also, please avoid acquiring a sample via next(iter(train_loader)). This creates a new loader every time it is called. Use train_iter = iter(train_loader) and inputs, labels = train_iter.next() instead.
Additionally, as far as I know, putting the entire dataset to a GPU or GPUs is not supported. You can load a mini-batch data (pytorch tensor) to it: inputs = inputs.to(torch.device("cuda"))
Any advise or correcting a wrong answer is welcomed.


text:
Q: MAC OS Perforce delete changelist I have a pending changelist that I want to delete. I use p4v client. I know that on Windows I can right click on it and I have delete option, but on Mac this option is missing. Is there other way to delete it? Thanks!
Edit: I'm interested to delete all files from the changelist also if is possible to do this.

A: I think the easiest way, assuming you want to revert the files on the changelist also is:

*

*right click on changelist, select revert- will get rid of all changes to those files.

*now you should be able to right click and delete the changelist.


text:
Q: Splash Screen Size in PhoneGap App I am trying to set a width and a height for my splash screen in my config.xml.
I am using PhoneGap Build and the PhoneGap version is 3.7.0, and the target is Andoird.
The splash screen always shows up very distorted (i.e. it will always be resized so it fits the entire screen).
The following has no effect:
<gap:splash src="./assets/img/logos/appLogo.png" width='200' height='100' />

And the following does not make the splash screen show at all:
<gap:splash src="./assets/img/logos/appLogo.png" gap:platform="android"  width='200' height='100' />

A: You should provide different splashscreens for different screen sizes.
According to the phonegap wiki ( https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes ) the sizes should be:
LDPI:
Portrait: 200x320px
Landscape: 320x200px
MDPI:
Portrait: 320x480px
Landscape: 480x320px
HDPI:
Portrait: 480x800px
Landscape: 800x480px
XHDPI:
Portrait: 720px1280px
Landscape: 1280x720px
XXHDPI:
Portrait: 960px1600px
Landscape: 1600x960px
XXXHDPI:
Portrait: 1280px1920px
Landscape: 1920x1280px

You can point in your config.xml to the splashscreens you provide, for example:
<gap:splash src="res/screen/splash_ldpi.png"       gap:platform="android" gap:qualifier="port-ldpi" />
<gap:splash src="res/screen/splash_mdpi.png"       gap:platform="android" gap:qualifier="port-mdpi" />
<gap:splash src="res/screen/splash_hdpi.png"       gap:platform="android" gap:qualifier="port-hdpi" />
<gap:splash src="res/screen/splash_xhdpi.png"       gap:platform="android" gap:qualifier="port-xhdpi" />


text:
Q: Container Won't Contain Everything I cannot get my .container{} to encompass all the content on my web page. My lower navigation buttons are sitting outside the container (marked by a 1px black border) and I can't figure out why. I'm not sure where I've went wrong in my CSS or HTML code! Thanks in advance for your help. Here is a link to my CodePen: https://codepen.io/IDCoder/pen/rGWeEE?editors=0100
Here are my code snippets:

    <title>Ms.Jane Equities Management Corp</title>

LOG IN

BUY A HOME

SELL A HOME

CONTACT US

MY LISTINGS

COMMUNITIES SERVED

PROPERTIES

CSS:
.container-fluid{
border: 1px solid #000000;
max-width: 1600px;
/*overflow: hidden;*/
}

.wrap{
background-color: yellow;
display: inline: flex;
/*overflow: hidden;*/
}

.Logos{
  width: 55%;
    display: inline-block;
    background-color: blue;

}

.nav.wrap{
    display: inline-block;
    background-color: green;
  float: right;
  margin-top: 25px;
}

 ul.navigation{
 font: bold 11px "Helvetica Neue", Helvetica, Arial, sans-serif;

 /*text-align center;*/
 /*border: 1px solid green;*/
 /*overflow: hidden;*/
}

.navigation li {
  display: inline-block;

}

.navigation a {
  background: #395870;
  background: linear-gradient(#49708f, #293f50);
  border-right: 1px solid rgba(0, 0, 0, .3);
  color: #fff;
  padding: 12px 20px;
  text-decoration: none;
}
.navigation a:hover {
  background: #314b0;
  box-shadow: inset 0 0 10px 1px rgba(0, 0, 0, .3);
}
.navigation li:first-child a {
  border-radius: 4px 0 0 4px;
}
.navigation li:last-child a {
  border-right: 0;
  border-radius: 0 4px 4px 0;
}

.row.two{
background-image: url(https://s1.postimg.org/5gvbly4hin/East_Hyde_Park_Chicago_aerial_0470.jpg);
    background-position: absolute;
    background-size:cover;
    background-repeat: no-repeat;
    max-width: 1600px;
  height: 550px;
        margin: auto;
}

 .floater.box{
    background-color: white;
    border-radius: 10px;
    opacity: .45;
    max-width: 75%;
    height: 200px;
    position: absolute;
    top:50%;
    left: 0;
    right: 0;
    margin: auto;
}

/*.search {
  width: 50%;
  position: relative
}

.searchTerm {
  float: left;
  width: 100%;
  border: 3px solid #00B4CC;
  padding: 5px;
  height: 20px;
  border-radius: 5px;
  outline: none;
  color: #9DBFAF;
}

.searchTerm:focus{
  color: #00B4CC;
}

.searchButton {
  position: absolute;
  right: -50px;
  width: 40px;
  height: 36px;
  border: 1px solid #00B4CC;
  background: #00B4CC;
  text-align: center;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 20px;
}

.search.box.wrap{
  width: 30%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
*/

A: I think your div.nav.wrap is getting pushed down because it's floated and there's no room for it in the container and because it's floated the container doesn't adjust for it. If you remove the float, you'll see the container start to contain it. That's normal float behaviour - elements with float are out of the 'flow' of the document so other elements aren't affected by them.
I'd just add a negative top margin to push it back up. I'd usually do this in rem or depending on how you size the nav height. So your existing .nav.wrap rule would become:
.nav.wrap{
  display: inline-block;
  background-color: green;
  float: right;
  margin-top: -35px;
}


text:
Q: access scope of variable in for loop I have searched the SO before I post this question here and hopefully
this is not a duplicated one.
def print_me():
    a_list = range(1, 10)
    for idx, aa in enumerate(a_list):
        pass
    print(idx)

if __name__ == '__main__' : print_me()

Output is as follows:

8

I came from C++ world and could not figure out why idx is still in the scope when
the code is out side of for loop?
Thank you

A: for loop doesn't create any scope. This is the reason.
In this particular code idx is a local variable of the print_me function.
From the docs:
The following are blocks:

*

*a module

*a function body

*a class definition

Update
Generator expressions have their own scopes too.
As of Python 3.0 list comprehensions also have their own scopes.


text:
Q: How can I correctly quote Paths with spaces in them? The below example does not execute as expected in Powershell:
Path := """C:\Temp\Test 1.svg"""
Run, C:\Program Files\PowerShell\7-preview\pwsh.exe -NoProfile -NoExit -Command Set-MetaData -Path %Path% -Notes "Hello" ,,

It will instead create a new file in Temp folder called Test
But if the Path being provided by the Path variable does not have any spaces in it, it runs as expected:
Path := """C:\Temp\Test1.svg"""
Run, C:\Program Files\PowerShell\7-preview\pwsh.exe -NoProfile -NoExit -Command Set-MetaData -Path %Path% -Notes "Hello" ,,

I've tried all sorts of things such as  expression syntax of -Path "Path"" -Notes "Hello"  I did not get positive results. Expression syntax always throws me of because of the double quotes , so am not sure if am doing it right.

A: You're not escaping quotes enough.
You get into a real escape hell here and you actually seem to need quintuple quotes ("""""test test""""") around the argument passed into pwsh.exe.
So in AHK you'd want
path := """""""""test test"""""""""
run, % "pwsh.exe -NoProfile -NoExit -Command echo " path

(Tested simply with the echo command because I don't have whatever Set-MetaData is)
To avoid this headache, you can use single quotes:
path := "'test test'"
run, % "pwsh.exe -NoProfile -NoExit -Command echo " path


text:
Q: fgets splits input string when I dont want it to I'm using fgets to read in a line from a file, but it splits up the input line into multiple lines which is not what I want it to do.
This is the code that I'm using:
    char string[LMAX];
FILE *fp;
fp = fopen("input.txt","r");

while(fgets (string, LMAX, fp) != NULL) {    //Reading the file, line by line
    printf("%s", string);
}

For example if my input file had 1,2;0,5;7,8;0,6;; the output in the console splits it up at the 0's.
i.e
1,2;
0,5;7,8;
0,6;;
I want it to print in one single line
EDIT: Indeed it was an issue with my input file.
tldr: never use notepad

A: Try fgetc() or use fread() to read one byte at a time

A: #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
    int LMAX = 1024;
    char foo[LMAX];
    FILE *fp;
    fp = fopen("input.txt","r");
    while(fgets (foo, LMAX, fp) != NULL) {
    //Reading the file, line by line
        printf("%s", foo);
    }
}

Everything works fine on my system (though I'm running osx).
1,2;0,5;7,8;0,6;;

Coding wise, your logic and modifiers are sound. I expect the error in output is due to something inherent within Visual studios. Or there may be an issue with your input file.


text:
Q: color pixel count with GraphicsMagick I need to count pixels in an image that are not background color.
I am calling this from PHP (it's from ImageMagick):
gm convert test.png -fill black +opaque "rgb(255,255,255)" -fill white -opaque "rgb(255,255,255)" -print "pixels = %[fx:w*h*mean]\n"

But it does not give any result, nothing.
I tried using histogram instead:
gm convert test.png -define histogram:unique-colors=true -format %c histogram:info.txt

That works, but gives values for every color and more details, I just need a single number please.

A: You have got a couple of issues here. You seem to be trying to mix GraphicsMagick with ImageMagick when they are not the same thing.
Firstly, GraphicsMagick does not have the +opaque operator that ImageMagick has.
Secondly, it doesn't have the -fx operator that ImageMagick has for doing maths.
I would suggest you move to, the more powerful, ImageMagick. Then it will work as you expect:
# Create a test image
convert -size 200x200 xc:black xc:white xc:red +append image.png

# Count the white pixels
convert image.png -fill black +opaque "rgb(255,255,255)" -print "pixels = %[fx:w*h*mean]\n" nul:
pixels = 40000

If you really, really must do it with GraphicsMagick, I can only suggest the following - which is heavily based on @GlennRanders-Pehrson answer here:
gm convert image.png +matte -matte -transparent white -operator matte negate 1 result.png

gm identify -verbose result.png | grep -EA5 "Opacity:|Geometry:" | grep -E "Mean|Geometry"
  Geometry: 600x200
  Mean:                    43690.00 (0.6667)
  Mean:                    43690.00 (0.6667)

And your answer will be:
600 * 200 * (1 - 0.667)