text:
Q: Operator less than between a non-null raw pointer and nullptr Are the operations nullptr < ptr and ptr < nullptr well defined for a non-null raw pointer ptr != nullptr? Quotes from the C++ standard are welcome.

A: Such a comparison is well-formed, but its result is unspecified.

[expr.rel]/3 Comparing pointers to objects is defined as follows:
— If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript compares greater.
— If one pointer points to an element of an array, or to a subobject thereof, and another pointer points one past the last element of the array, the latter pointer compares greater.
— If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.
[expr.rel]/4 If two operands p and q compare equal (5.10), p<=q and p>=q both yield true and p<q and p>q both yield false. Otherwise, if a pointer p compares greater than a pointer q, p>=q, p>q, q<=p, and q<p all yield true and p<=q, p<q, q>=p, and q>p all yield false. Otherwise, the result of each of the operators is unspecified.

A null pointer doesn't fall into any of the three clauses of [expr.rel]/3, and so it compares neither greater nor less than a non-null pointer. This case then falls into the "otherwise" clause of [expr.rel]/4.


text:
Q: Output everything between specified XML tag in C# I need to get the everything between two Xml tags in C#, here is what i got so far{
XmlTextReader reader = new XmlTextReader(textBox1.Text);
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element:
                Console.Write("<" + reader.Name);
                Console.WriteLine(">");
                break;
            case XmlNodeType.Text: //Display the text in each element.
                Console.WriteLine(reader.Value);
                break;
            case XmlNodeType.EndElement: //Display the end of the element.
                Console.Write("</" + reader.Name);
                Console.WriteLine(">");
                break;
        }
    }
}

As you can see i have the file read in, and i can output all the tags to the console, how can i output everything between the tag i want to the console.
I need to be able to go into many tags, like open

A: I think you might have overcomplicated this slightly.  It's probably just a matter of finding the node that you want and using the InnerXml property:
XmlDocument doc = new XmlDocument();

doc.LoadXml("<root>"+
            "<elem>test 1<child/>test 2</elem>" +
            "</root>");

XmlNode elem = doc.DocumentElement.FirstChild;

Console.WriteLine("Display the InnerXml of the element...");
Console.WriteLine(elem.InnerXml);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple HTML DOM Parser. Remove first row in table and then remove second column of each I am trying to parse an HTML string which is a table. I managed to remove the first row of the table. How can I then remove the second column in the table?
I remove the first row like this:
$preparsed = "

                      Type
                      Date
                      Details
                      Instructor
                      Student / Client
                      Comment

                    Training
                    2016-10-05
(16:00:00-18:00:00)
                    Zara
                    Gary
                    Alfred

                    Training
                    2016-10-05
(12:00:00-15:00:00)
                    Zara
                    Gary
                    shawn

";

$html = new simple_html_dom();
$html->load($preparsed);
$rows = array_slice($html->find('tr'), 1);
foreach ( $rows as $element ) {
echo '
'. $element->plaintext . '
';

This removes the first row. How can I either a)First remove every second column in each row (the date), or b) remove the first row first and then remove all the second columns in each row?

A: Like this:
$html = new simple_html_dom();
$html->load($preparsed);
$rows = array_slice($html->find('tr'), 1);
foreach ( $rows as $element ) {
    echo '
'. $element->plaintext . '
';
    $cols = array_slice($element->find('td'), 2);
    foreach ( $cols as $col ) {
        echo '
The second col os the row values '. $col->plaintext . '
';
    }
}


text:
Q: How can I evaluate the following involving dirac delta functions? \begin{align}
\delta(x)\delta(x) = ?
\end{align}
\begin{align}
\delta(x)\delta(x-a) = ?
\end{align}
\begin{align}
\delta(x)/x = ?
\end{align}
In the above problems, a is a real number and a $\ne$ 0,  My solutions are below, but I am not sure of them.
\begin{align}
\delta(x)\delta(x) = \delta(x=0) \delta(x)=\delta(x)
\end{align}
\begin{align}
\delta(x)\delta(x-a) = \delta(x=a) \delta(x-a)=0
\end{align}
since the $\delta$(x=a)=0
\begin{align}
\delta(x)/x = ?
\end{align}
I am not sure of this.
Thanks for your feedback.


text:
Q: Making Theme Config Fields multilang? I know you can make non editable config values multilang in via src/Resources/config/config.xml but is it also possible for fields defined in src/Resources/theme.json?

A: This does not seem to be possible as in the admin panel you cannot switch the language at that point.


text:
Q: Linq Query with double sub queries I am struggling converting the following SQL query I wrote into Linq. I think I'm on the right track, but I must be missing something.
The error I'm getting right now is:

System.Linq.IQueryable does not contain a definition for .Contains

Which is confusing to me because it should right?
SQL
select Users.*
from Users
where UserID in (select distinct(UserID)
                        from UserPermission
                        where SupplierID in (select SupplierID
                                             from UserPermission
                                             where UserID = 6))

LINQ
var Users = (from u in _db.Users
             where (from up in _db.UserPermissions select up.UserID)
               .Distinct()
               .Contains((from up2 in _db.UserPermissions
                          where up2.UserID == 6
                          select up2.SupplierID))
             select u);

EDIT: I ended up going back to SqlCommand objects as this was something I had to get done today and couldn't waste too much time trying to figure out how to do it the right way with Linq and EF. I hate code hacks :(

A: I think there is no need to do a distinct here (maybe I am wrong). But here is a simpler version (assuming you have all the navigational properties defined correctly)
var lstUsers = DBContext.Users.Where(
                    x => x.UserPermissions.Any(
                                    y => y.Suppliers.Any(z => z.UserID == 6)
                                            )
                                    ).ToList();

Above if you have UserID field in Supplier entity, if it is NOT you can again use the navigational property as,
var lstUsers = DBContext.Users.Where(
                    x => x.UserPermissions.Any(
                                    y => y.Suppliers.Any(z => z.User.UserID == 6)
                                            )
                                    ).ToList();

A: Contains() only expects a single element, so it won't work as you have it written.  Try this as an alternate:
var Users = _db.Users
            .Where(u => _db.UserPermissions
                .Select(x => UserID)
                .Distinct()
                .Where(x => _db.UserPermissions
                    .Where(y => y.UserID == 6)
                    .Select(y => y.SupplierID)
                    .Contains(x))
                );

A: I didn't try on my side but you can try using the let keyword:
var Users = (from u in _db.Users
             let distinctUsers = (from up in _db.UserPermissions select up).Distinct()
             let subQuery = (from up2 in _db.UserPermissions
                          where up2.UserID == 6
                          select up2)
             where
             distinctUsers.SupplierID== subQuery.SupplierID &&
             u.UserID==distinctUsers.UserID
             select u);


text:
Q: How to find if users exist in Firebase? I am using Firebase Web SDK and know methods to check whether a child in a collection exists or not. However I can't find a concise example checking the existence of a user, without trying to sign him/her in.
export class Email extends Component {
  constructor (props) {
    super(props)
    this.state = { email: '' }
  }

  checkEmail () {
    const { email } = this.state
    FirebaseApp.auth()
    .createUserWithEmailAndPassword(email, uuid.v4())
    .then((User) => Actions.Password({ User }))
    .catch((error) => {
      // Handle Errors here.
      console.log('firebase', {error})
      this.setState({error})
      // ...
    })
    // Actions.password()
  }

  render () {
    return (
      <View style={{ ...styles.onboarding, backgroundColor: 'purple' }}>
        <View style={{ borderBottomWidth: 3, borderColor: 'black', padding: 10 }}>
          <TextInput ref='email'
            style={styles.input}
            keyboardType='email-address'
            placeholder='Your email'
            value={this.state.email}
            onChangeText={(email) => this.setState({email: email.toLowerCase()})} />
        </View>
        {!this.state.error ? null
          : <Text>
            {this.state.error.message}
          </Text>
        }
        <TouchableOpacity onPress={() => this.checkEmail()} style={{ ...styles.button, margin: 20, borderColor: 'black' }}>
          <Text style={styles.buttonText}>Next</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

Do you have any piece of code we could reuse?

A: For the moment, and because it complies with my app security policy and setup, I created an email collection indexed precisely by ids.
firebase.ref(`emails/${user.email}`).set(true)


text:
Q: Equally divide area under a curve I have a y = sin(x) curve and x is between 0 and pi (first quadrant - no negative values). Something like this:

I want to equally divide area under the curve to n pieces and get the (biggest) x value for each piece.
Any ideas would be appreciated for an algorithm.

A: The area under the curve is its integral. The integral of sin(x) from 0 to u is 1-cos(u), so the integral from 0 to πis 2. Inverting that formula finds the points t for which u gets a certain value. So, we're looking for the values t=acos(1-u) for the values of u that divide [0, 2] into n equal parts.
In code:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-0.2, 3.3, 500)
y = np.sin(x)
plt.plot(x, y)

n = 7
u = np.linspace(0, 2, n + 1, endpoint=True)
t = np.arccos(1 - u)
print("The limits of the areas are:", list(t))

colors = plt.cm.Set2.colors
for i in range(n):
    filter = (x > t[i]) & (x <= t[i + 1])
    plt.fill_between(x[filter], 0, y[filter], color=colors[i])
plt.xticks(t)
plt.gca().spines['bottom'].set_position('zero')
plt.gca().spines['top'].set_color('none')
plt.gca().spines['right'].set_color('none')
plt.tight_layout()
plt.show()

A: Though it is not entirely consequent answer, maybe it would be interesting.
Deviding the area in question into three equal parts.
On the basis OA, as on the hypotenuse, build a right angled triangle with the ratio of the legs OC:AC= 4:5. Raise the vertical from the point C. Shift that vertical symmetrically also to the righy side. Division completed. Error about 1%.
Now on the merits/ One must use a recurrent formulae: X0= 0, X(i+1)= X(i)+Δ(i+1); Δ(i+1)= arccossqrt((p(i))^2-q(i))-p(i)), where p(i)= cos(X(i))(2/n-cos(X(i)); q(i)= cos(2X(i))+4/n(1/n-cos(X(i))


text:
Q: Controller Namespaces and Routing issue I created a routing test rails3 app with one model 'User':
rails new routing_test_app
rails generate model User name:string
rails generate scaffold_controller admin/user
rake db:migrate

Added to routes.db:
namespace :admin do
  resources :users
end

rake routes
admin_users GET    /admin/users(.:format)          {:action=>"index", :controller=>"admin/users"}
admin_users POST   /admin/users(.:format)          {:action=>"create", :controller=>"admin/users"}
new_admin_user GET    /admin/users/new(.:format)      {:action=>"new", :controller=>"admin/users"}
edit_admin_user GET    /admin/users/:id/edit(.:format) {:action=>"edit", :controller=>"admin/users"}
admin_user GET    /admin/users/:id(.:format)      {:action=>"show", :controller=>"admin/users"}
admin_user PUT    /admin/users/:id(.:format)      {:action=>"update", :controller=>"admin/users"}
admin_user DELETE /admin/users/:id(.:format)      {:action=>"destroy", :controller=>"admin/users"}

views/admin/users/_form.html.erb
<%= form_for(@admin_user) do |f| %>
  <% if @admin_user.errors.any? %>

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

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

<%= msg %>

      <% end %>

  <% end %>
    <%= f.text_field :name %>

    <%= f.submit %>

<% end %>

When I go to 'http://localhost:3000/admin/users/new' rails throws an error:
undefined method `users_path' for #<#<Class:0x0000010116ca90>:0x000001011588d8>

Extracted source (around line #1):
1: <%= form_for(@admin_user) do |f| %>
2:   <% if @admin_user.errors.any? %>
3:

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

A: That's because @admin_user is a User object, so Rails guesses the URL helper to be users_path. It's a simple fix. Just replace @admin_user form_for param with [:admin, @admin_user]. You might also want to rename the instance variable @user for less repitition. Having to use the array is a drawback of using namespaces, so one should always take that into consideration.

A: The form_for method will not guess nested routes. Try this:
form_for [:admin, @admin_user] do |f|


text:
Q: wrap anonymous function with another call I have this code in which I am trying to wrap an anonymous function by another call so when it is actually the wrapper's value that is returned and not the original function's.
In the code below however I get a NullPointerException in the last call. I am sure I am not doing something right, but beats me what it is.
class Program
{
    public class MyClass
    {
        public int MyProp { get; set; }
    }

    private static List<Func<MyClass, object>> Calls;

    private static object ExtraCall(int obj)
    {
        var returnVal = 8;

        //do some stuff

        return returnVal;
    }

    static void Main(string[] args)
    {
        Calls = new List<Func<MyClass, object>>();

        Calls.Add(c => c.MyProp);

        Func<MyClass, object> func = c => c.MyProp;
        Calls.Add(c => ExtraCall((int)func(func.Target as MyClass)));

        var obj = new MyClass(){ MyProp = 7 };
        var test1 = Calls[0](obj);
        var test2 = Calls[1](obj);
    }
}

A: func.Target is null because this delegate doesn't have any instance which it is invoked on. You can try following code:
    Calls.Add(c => ExtraCall((int)func(c)));


text:
Q: Errors when passing array or parameters to hstore scope in Rails I'm trying to create a scope on an hstore column in my Rails app.  Product is a model and features is an attribute of type hstore (using Postgresql 9.2). My class with scope is defined below:
class Product < ActiveRecord::Base
    scope :with_features, lambda {|features| where("foo_id in (?)", features)

The above scope only works if you pass single values in as features.  Arrays throw errors.  This is illustrated below:
Product.with_features('api')
  => [#<Product id: 1, name: "Sample">]
     # so great success

# now with an array
Product.with_features(['api','mobile'])
  => ActiveRecord::StatementInvalid: PG::Error: ERROR:  argument of WHERE must be type boolean, not type record
    # so no good, this query will work as usual if features isn't of type hstore

In Rails 3.2, it seems support for postgres hstore type is limited when arrays are involved (I'm using https://github.com/softa/activerecord-postgres-hstore).  I've been trying some solutions with a each loop to append AND queries together, not much luck.  Any ideas?

A: Here's one solution I came up with that works well:
scope :with_features, lambda { |features|

  #store the composed scope in local variable to build on
  composed_scope = self.scoped

  # if array, then loop through each
  if features.instance_of?(Array)
    features.each do |feature|
      composed_scope = composed_scope.where("features ? :key", :key => feature)
    end

  # otherwise, it's a single string parameter, parse as normal
  else
    composed_scope = composed_scope.where("features ? :key", :key => features)
  end

  # return the newly built composed scope
  composed_scope
}

Now both example queries above return expected results.


text:
Q: Recommended Nginx Configuration for High Traffic Website on Wordpress We have a Wordpress based website that gets about 1.5 million pageviews per day. Maximum concurrent sessions reach up to 5000 users per minute at times.
We have one web and one database server. Specs for both machines are as follows:
CPU: 2 x Intel(R) Xeon(R) CPU X5650 @ 2.66GHz
12M Cache / 6 Cores / 12 Threads (x2)
Memory: 24GB
Drive(s)(size/GB) - 4x240gb SSDs RAID 10

We run on Nginx, use FastCGI, and also use APC for caching, along with simple page caching with WP Super Cache.
Current Nginx configuration is as follows:
worker_processes  24;
worker_rlimit_nofile 200000;
worker_connections  4000;

FastCGI settings are as follows:
FcgidMaxProcesses 200
FcgidProcessLifeTime 3600
MaxProcessCount 100
FcgidIOTimeout 400
FcgidIdleTimeout 600
FcgidIdleScanInterval 90
FcgidBusyTimeout 400
FcgidBusyScanInterval 80
ErrorScanInterval 3
ZombieScanInterval 3

Server fails and we get Nginx errors (502-504) during high traffic. I am wondering if this is related to a bad configuration.
Your assistance is much appreciated.

A: "...it makes sense for us to run multiple workers, usually 1 worker per CPU core. Though, anything above 2-4 workers is overkill as nginx will hit other bottlenecks before the CPU becomes an issue and usually you'll just have idle processes"
Check out this blog: http://blog.martinfjordvald.com/2011/04/optimizing-nginx-for-high-traffic-loads/
This post might be helpful as well: Tuning nginx worker_process to obtain 100k hits per min


text:
Q: How can I use fork style edges with explicitely positioned TikZ tree nodes? As part of a graphical export facility, I try to render a tree in TikZ were all the node positions are exactly given and were the edges are fork-style.
Doing that without the trees package demands that I calculate the edge 'corners' by myself, based on the given node coordinates, which I would like to avoid.
Adding explicitly positioned nodes to a TikZ tree is messing up the layout, since (according to the manual), TikZ is changing the coordinate system for each child node.
Without trees:
\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{figure}
\begin{tikzpicture}
\node at (10, 10) (root) {root} ;
\node at (10, 7) (lvl1middle) {lvl1middle} ;
\node at (8, 6) (lvl2left) {lvl2left} ;
\node at (13, 5) (lvl2right) {lvl2right} ;
\node at (10, 5) (lvl2middle) {lvl2middle} ;
\draw (root) -- (lvl1middle);
\draw (lvl1middle) -- (lvl2left);
\draw (lvl1middle) -- (lvl2middle);
\draw (lvl1middle) -- (lvl2right);
\end{tikzpicture}
\end{figure}
\end{document}

With trees:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees}
\begin{document}

\begin{figure}
\begin{tikzpicture}
\node at (10, 10) (root) {root}
    [edge from parent fork down]
    child { node at (10, 7) (lvl1middle) {lvl1middle}
        child { node at (8, 6) (lvl2left) {lvl2left} }
        child { node at (13, 5) (lvl2right) {lvl2right} }
        child { node at (10, 5) (lvl2middle) {lvl2middle} }
    };
\end{tikzpicture}
\end{figure}
\end{document}

A: The edge from parent fork down simply installs a special edge from parent path that we can use for a to path. The original definition is
\tikzset{edge from parent fork down/.style={
  edge from parent path={(\tikzparentnode\tikzparentanchor) -- +(0pt,-.5\tikzleveldistance)
                                                      -| (\tikzchildnode\tikzchildanchor)}}}

The default \tikzleveldistance is 15mm.
One solution with a to path would be
\tikzset{
  edge down and up again/.style={
    to path={
       |- ([shift={(\tikztotarget.south)}] +0pt,+-2.5mm) -- (\tikztotarget) }}}

In your example, I had to switch back to the default line to (i.e. --) path as the edge would have to go around the target node in that way.
Code
\documentclass[tikz,convert=false]{standalone}
\tikzset{
  edge down and up again/.style={
    to path={
       |- ([shift={(\tikztotarget.south)}] +0pt,+-2.5mm) -- (\tikztotarget) }}}
\begin{document}
\begin{tikzpicture}
\node at (10, 10) (root) {root} ;
\node at (10, 7) (lvl1middle) {lvl1middle} ;
\node at (8, 6) (lvl2left) {lvl2left} ;
\node at (13, 5) (lvl2right) {lvl2right} ;
\node at (10, 5) (lvl2middle) {lvl2middle} ;

\path[edge down and up again] (root) edge [line to] (lvl1middle)
                        (lvl1middle) edge           (lvl2left)
                                     edge [line to] (lvl2middle)
                        (lvl2middle) edge           (lvl2right);
\end{tikzpicture}
\end{document}

Output


text:
Q: What is the type of 'const val num = 1' of Kotlin? And how are they able to define it? Mostly, I use Int, Double and String, Char. Recently, I got interested in saving memory and I realized even small amount of bytes can be much larger and it affects the program and even the mobile speed and battery life.(Especially, data resources of its memory)
So, I am trying to use Byte, Short when the data doesn't need to store big numbers. For example, byte for -128 ~ 127, Short for -32,768 ~ 32,767.
Is it a good idea?
And My main question is I want to know the data type of const val in Kotlin since it automatically defines the datatype.
const val THIS_IS_STRING = "HelloWorld"
const val THIS_IS_CHAR = 'C'
const val NUMBER_1 = -124
const val NUMBER_2 = 31000
const val NUMBER_3 = 1000000
const val NUMBER_4 = 1232188777777344444
const val NUMBER_5 = 29128812312732881231273712
const val NUMBER_6 = 0.423
const val NUMBER_7 = 0.2121222222441
const val NUMBER_8 = 0.813881281237123991827312324
const val NUMBER_9 = 0.5123090982307037412398190092340239423094803820432423423209823092342342348209384023984023480923840923840009930923094029848901

What are the data types of them(The numbers)?
Or should I define like these for saving the resources? Or I don't need to?
const val MIN:Byte = -124
const val MID:Short = 31000
const val MAX:Int = 1000000
...
``

A: It is dependent on you whether you want to provide data type allocation to kotlin or self. If your saving the values by providing resource type. You can save data or you can depend on the kotlin.
But if your saving the data i will advice you to provide the data type :
Let's take this as an example for you :
fun main() {
    var b: Any = 124
    println(b)
    if(b is Float) {
        println("Float")
    }
    else if(b is Double) {
        println("Double")
    }else if(b is Byte){
        println("byte")
    }else if(b is Int){
        println("int")
    }else if(b is Short){
        println("short")
    }
}

It will provide the output as Int.
So i suggest provide data type.

A: Kotlin Type inference  -  In Kotlin most of the time, you won't need to specify the type of the objects you are working with, as long as the compiler can infer it.
So, we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly as well. Say, for instance, you define val REQUEST_CODE = 100. Behind the scenes, REQUEST_CODE initializes with the Int datatype since the value of REQUEST_CODE is of type Int, the compiler infers that REQUEST_CODE is also a Int. Note that Kotlin is a statically-typed language. This means that the type is resolved at compile time and never changes.
Although Kotlin uses Type Inference ( automatically identify something ), which means we also have the option to specify the data type when we initialize the variable like below:
val REQUEST_CODE: Int = 100

Both act the same while converting it to byte code.

What the heck, How do Kotlin determine the data type of numbers if we
use implicit declaration?

Good question, Kotlin provides a set of built-in types that represent numbers. For integer numbers, there are four types with different sizes and, hence, value ranges.

All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int. If the initial value exceeds this value, then the type is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for data types like Byte & Short as mentioned by Animesh in the accepted answer.
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

Reference

*

*https://kotlinlang.org/docs/reference/basic-types.html

A: Type inference is described in https://kotlinlang.org/docs/reference/basic-types.html
Basically the default types when not specified for a number in range of -231 to 231-1 is Int and higher than that is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for Byte and Short.
val one = 1                    // inferred as Int
val threeBillion = 3000000000  // inferred as Long
val oneL = 1L                  // explicitly specify Long type by appending with L
val oneLong: Long = 1L         // explicitly specify Long by type
val oneByte: Byte = 1          // explicitly specify Byte for saving memory

For floating point numbers default type is Double, you can switch to float by either specifying type or appending f.
val pi = 3.14               // Double
val piFloat: Float = 3.14   // explicitly specify Float by type
val e = 2.7182818284        // Double
val eFloat = 2.7182818284f  // explicitly specify Float by appending with f

The characters and strings by nature having single data type so it is Char and String by default, and there is no need to change it explicitly.
It is generally Advisable to specify types to save memory because it is constant and will never change so conservation is a better choice, but it is all upto you.

A: I'm surprised there are so many answers here ignoring this, but using Byte and Short for properties will not save you memory. The backing variables still take up 4 bytes of memory for each. They only save you memory when you use them in ByteArray and ShortArray. They also can cause a performance penalty for doing arithmetic with them instead of Int or Long, but that's insignificant in most applications.
As other answers have mentioned Int is implicit unless the number is big enough to be a Long. And this is what you want because it is more performant and takes up the same amount of memory.

A: Const is a compilation time constant. This means that a value must be allocated during the compilation time, unlike the value that can be performed at run-time, meaning that the const cannot be assigned to a function or class constructor and should only be allocated as character series or basic data type.


text:
Q: How to create a webview with some functions in Android Studio? I am a newbie in java. Since 5 years I program in html, php and mysql.
I want to load a website in a webview with some functions.
The webview should load when the user open the app.
These functions should include:

*

*javascript enable

*image upload allowed (if possible, for all android versions)

*only allow the deposited domain and all other domains show a window where they can choose a installed browser just like chrome. this is importent when they click on a external link in the webview.
I have tried some things, but only the javascript and webview worked.
I dont know if the currently code is the best solution.
This is my code in the activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:addStatesFromChildren="false"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <WebView
        android:id="@+id/web1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

and this is my code in the MainActivity.java
    package com.example.user.testapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView myWebView = (WebView) findViewById(R.id.web1);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl("https://www.website.com");

        String url = myWebView.getUrl();
        if (url.contains("website.com")) {
            myWebView.loadUrl(url);

        } else {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            myWebView.getContext().startActivity(i);
        }
    }
}

and here the code of AndroidManifest.xml
   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.testapplication">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Thanks in advance for your assistance


text:
Q: Layer backed NSOpenGLView + animation timer = strange drawing behavior? I am creating an application which subclasses NSOpenGLView to do some OpenGL drawings. Now i wanted to add an overlay control, similar to QuickTime X. First thing i tried was setting NSOpenGLCPSurfaceOrder to -1 and making my window none-opaque. It did work, but i lost the windows shadow, so not a viable solution.
I then made my NSOpenGLView subclass layer-backed by calling [setWantsLayer:YES] and adding my control box as a subview. It worked, but i noticed a big drop in performance. I did some research and found this:
I am using an NSTimer object to call a method [timerFired:] 60 times per second. Works perfectly. The only thing i do within this method is calling [self setNeedsDisplay:YES], because when using a layer-backed OpenGLView one needs to overload the [drawRect:rect] method and do all the OpenGL drawing there. The problem: [drawRect:rect] often gets called although the timer didn't fire.
At first i thought "of course it does, it draws the NSOpenGLView, so it might be called by the window manager or something". So deleted my timer object to determine how it was called between [timerFired:] calls. The result: It wasn't called at all, at least not when not resizing or dragging the window.
So next i experimented with my timers time interval. Turns out, up until 55 times per second the [drawRect:rect] is called between 60 and 70 times per second, and from a timer interval of 59 times a second onward the [drawRect:rect] is called between 100 and 120 times a second.
I suspect that this highly unpredictable manner in which my drawing is called leads to the performance loss, either by being uneven or by clogging the thread with a lot of OpenGL drawings and not enough time to be executed or something. I also read that layer-backed OpenGLViews don't work with vsync, although i can't confirm this.
Does anyone have an explanation? Does anyone have an idea on how to only draw my OpenGL on timer fires?
I already tried the naive approach and added a boolean variable, set it true in my [timerFired:] and made my [drawRect:rect] only calling the OpenGL drawing method if the variable is true. The result was an extremely flickery and stuttery animation, so no luck.
What about using an CAOpenGLLayer with asynchronous animation oder CVDisplayLink? Would either help?
edit another thing which might be helpful information: I already used [setNeedsDisplay:YES] without my view being layer-backed, so i could easily switch between layer-backed and not-layer-backed, and i didn't have any of the problems described above, so it definitely has to do with my view being layer-backed. Everything gets a mess by just calling [setWantsLayer:YES].

A: So i replaced my NSTimer object with a CVDisplayLink and everything is smooth again. Although i don't actually understand why. It seems like requesting a backing layer broke the vertical sync, but it does not explain the random calls to drawRect that appeared out of nowhere.
Also i would really like to if vsync works with a layer backed NSOpenGLView and / or with a CAOpenGLLayer. I can't find any official information.


text:
Q: LINQ avoid OUTER APPLY Oracle 11g When running the LINQ Query below against Oracle 11g instance, it will throw an OUTER APPLY not supported error.
var shipmentDetails = (
    from r in _db.XXF_SHIPMENT_DETAILs
    where r.SHIP_TO == tradingPartnerId && r.PICKUP_DATE >= pickUpDate
    select r)
    .GroupBy(x => x.HEADERID)
    .Select(x => x.FirstOrDefault());

"OUTER APPLY is not supported by Oracle Database 11g and lower. Oracle
12c or higher is required to run this LINQ statement correctly. If you
need to run this statement with Oracle Database 11g or lower, rewrite
it so that it can be converted to SQL, supported by the version of
Oracle you use."

A: The solution is to use simple statements to achieve the results you are after. Referencing the query above, we...
First, get all the shipments. Use the .ToList() to force query execution
var shipmentDetails = (from r in _db.XXF_SHIPMENT_DETAILs where r.SHIP_TO == tradingPartnerId && r.PICKUP_DATE >= pickUpDate select r).ToList();

Now .GroupBy() and .Select() to filter - but this will be done in memory and not at the server level therefore avoiding the unsupported OUTER APPLY
var uniqueShipmentsWithDistinctHeaderIds = shipmentDetails.GroupBy(x => x.HEADERID).Select(x => x.FirstOrDefault());

A: You can use the following query which will get latest record from the group:
var filtered = db.XXF_SHIPMENT_DETAILs
    .Where(r => r.SHIP_TO == tradingPartnerId && r.PICKUP_DATE >= pickUpDate);

var grouped = fltered
    .GroupBy(r => r.HEADERID)
    .Select(g => new
    {
        HEADERID = g.Key,
        LastId = g.Max(x => x.Id)
    });

var shipmentDetails =
    from s in filtered
    join g in grouped on s.LastId equals g.Id
    select s;

Still not the best as raw SQL and window functions, but should give much better performance than processing data on the client side.


text:
Q: Rejection sampling - total probability of acceptance I am given the following pdf $$f(x)=3 x^{2}, \quad 0 \leq x \leq 1$$ which i need to simulate by using rejection sampling.
I have used the following code below in R.
PDF_function <- function(x){3*x^2}

c <- PDF_function(1)

curve(PDF_function, 0, 1)
abline(a = c, b = 0, col='red')

X = runif(4500, 0, 1)
U = runif(4500, 0, 1)

pi_x <- function(x) {
  new_x = 3*x^2
  return(new_x)
}

count = 1
accept = c()

while(count <= 4500 & length(accept) < 1000){
  test_u = U[count]
  test_x = pi_x(X[count])/(c*dunif(X[count],0,1))
  if (test_u <= test_x){
    accept = rbind(accept, X[count])
    count = count + 1
  }
  count = count + 1
}

hist(accept)

mean(accept)
var(accept)

integrate(PDF_function, 0, 1)

1/(1*3)

length(accept)/count

I am asked to compare the total probability of acceptance and compare it with the theoretical one. If I understand this correctly then by computing length(accept)/count I get the estimated probability of acceptance but what is the theoretical one? I think the theoretical one is the area of the pdf function over the total area (under the envelope). If I integrate my function from 0 to 1 I get 1 (obviously) and the total area is 1 * (f(1)=3) = 3. So the theoretical is 1/3 ~= 0.333. Is this correct?

A: Yes, the theoretical value is $1/3$, which is the area under the curve over the amplified proposal distribution area, which is uniform in your case. You're double-counting the count, so if you remove the additional count increment inside the conditional statement you'll obtain empirical acceptance ratio close to $1/3$.


text:
Q: How to remove parent category from Yoast breadcrumbs I'm having a bit of hard time trying to get this one link/category disappear from my bredcrumb path.
The path goes as follows: home/customPostTypeCategory/subCategory/child/ , so what I need to get done is to get that customPostTypeCategory to go away.
So as a clearness, this is a Custom post type made with Types -plugin, and breadcrumbs are using SEO by Yoast breadcrumbs.
This could be done via CSS, but that is the last solution I'm willing to use.
Any clues, tips or tricks how to do this?
Thanks!

A: add_filter( 'wpseo_breadcrumb_links', 'my_breadcrumb_filter_function' );
function my_breadcrumb_filter_function( $crumbs ) {
    foreach( $crumbs as $i => $crumb ) {
        $term = get_object_vars($crumb['term']);
       if( isset( $term['parent'] ) && $term['parent'] != 0 ) {

        } else {
            $new_crumbs[] = $crumbs[$i];
        }
    }
    return $new_crumbs;
}

A: So I solved this by using jQuery and contains -selector.
$( "#breadcrumbs a:contains('customPostTypeCategory')" ).removeAttr( "href" );
This obviously removes only the link, so that the category name still stays.
If the whole thing should be removed, then one could use the following:
$( "#breadcrumbs a:contains('customPostTypeCategory')" ).css( "display", "none" );
This did the trick for me, but it ain't the solution I was looking and asking for.

A: I had the same issue with a custom post type.
After looking at the output of the array, I saw that array(1) was the archive, and what I believe you're calling a category.
This did the trick for me:
function my_breadcrumb_filter_function( $crumbs ) {

    // replace "cpt" with your custom post type name
    if(is_singular('cpt')) {
      $crumbs[1] = '';
    }
    return $crumbs;

}
add_filter( 'wpseo_breadcrumb_links', 'my_breadcrumb_filter_function' );


text:
Q: How do I test if another installation is already in progress? Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?
[Update 2]
Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:
using System.Threading;

[...]

/// <summary>
/// Wait (up to a timeout) for the MSI installer service to become free.
/// </summary>
/// <returns>
/// Returns true for a successful wait, when the installer service has become free.
/// Returns false when waiting for the installer service has exceeded the timeout.
/// </returns>
public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime)
{
    // The _MSIExecute mutex is used by the MSI installer service to serialize installations
    // and prevent multiple MSI based installations happening at the same time.
    // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx
    const string installerServiceMutexName = "Global\\_MSIExecute";

    try
    {
        Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,
            System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify);
        bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false);
        MSIExecuteMutex.ReleaseMutex();
        return waitSuccess;
    }
    catch (WaitHandleCannotBeOpenedException)
    {
        // Mutex doesn't exist, do nothing
    }
    catch (ObjectDisposedException)
    {
        // Mutex was disposed between opening it and attempting to wait on it, do nothing
    }
    return true;
}

A: See the description of the _MSIExecute Mutex on MSDN.

A: I was getting an unhandled exception using the code above.  I cross referenced this article witt this one
Here's my updated code:
  /// <summary>
/// Wait (up to a timeout) for the MSI installer service to become free.
/// </summary>
/// <returns>
/// Returns true for a successful wait, when the installer service has become free.
/// Returns false when waiting for the installer service has exceeded the timeout.
/// </returns>
public static bool IsMsiExecFree(TimeSpan maxWaitTime)
{
    // The _MSIExecute mutex is used by the MSI installer service to serialize installations
    // and prevent multiple MSI based installations happening at the same time.
    // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx
    const string installerServiceMutexName = "Global\\_MSIExecute";
    Mutex MSIExecuteMutex = null;
    var isMsiExecFree = false;
    try
    {
            MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,
                            System.Security.AccessControl.MutexRights.Synchronize);
            isMsiExecFree = MSIExecuteMutex.WaitOne(maxWaitTime, false);
    }
        catch (WaitHandleCannotBeOpenedException)
        {
            // Mutex doesn't exist, do nothing
            isMsiExecFree = true;
        }
        catch (ObjectDisposedException)
        {
            // Mutex was disposed between opening it and attempting to wait on it, do nothing
            isMsiExecFree = true;
        }
        finally
        {
            if(MSIExecuteMutex != null && isMsiExecFree)
            MSIExecuteMutex.ReleaseMutex();
        }
    return isMsiExecFree;

}

A: I have been working on this - for about a week - using your notes (Thank you) and that from other sites - too many to name (Thank you all).
I stumbled across information revealing that the Service could yield enough information to determine if the MSIEXEC service is already in use. The Service being 'msiserver' - Windows Installer - and it's information being both state and acceptstop.
The following VBScript code checks this:
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Check = False
Do While Not Check
   WScript.Sleep 3000
   Set colServices = objWMIService.ExecQuery("Select * From Win32_Service Where Name="'msiserver'")
   For Each objService In colServices
      If (objService.Started And Not objService.AcceptStop)
         WScript.Echo "Another .MSI is running."
      ElseIf ((objService.Started And objService.AcceptStop) Or Not objService.Started) Then
         WScript.Echo "Ready to install an .MSI application."
         Check = True
      End If
   Next
Loop


text:
Q: Past or present to explain an active state in a past sentence So, I have a sentence, more or less like this:

"Gil, who HAS a psychokinesis ability, studied math yesterday."

or

"Gil, who CAN move things without touching them, studied math yesterday."

So, with those sentences, I want to explain something that happened in the past, while explain a little about Gil himself. The thing is that I'm confused with the form I have to use for the "HAS" or the "CAN". I don't think I could use "HAD" or "COULD", because his psychokinesis ability is something he always has, till now (present). But I'm not sure present tense is right one. What form should I use?
Sorry for my broken english.

A: If you wish to refer to the fact that Gil studied math yesterday, and he still has psychokinetic powers, use the present tense just as you did above:

Gil, who has psychokinetic powers, studied math yesterday.
Gil, who can move objects with his mind, studied math yesterday.

If his powers have ceased or you don't really know anything about him anymore, you can use the past tense in that construction:

Gil, who had psychokinetic abilities, studied math yesterday.
Gil, who could move objects with his mind, studied math yesterday.

Both are perfectly grammatical.  But, their meaning is slightly ambiguous:
Gil either used to have psychokinetic abilities, or we are generally done referring to Gil (in other words, Gil who we knew in the past had the powers at that time).
If you wish to avoid the ambiguity:

Gil, who used to have psychokinetic abilities, studied math yesterday.
Gil, who used to be able to move objects with his mind, studied math yesterday.

That said, the whole sentence construction is a bit off for English.  His psychokinetic abilities are so unrelated to his doing math, that it stretches the reader's mind trying to make a connection.

A: I'm pretty sure you're safe with "has/can".


text:
Q: How to execute a target when generic files exist I am using msbuild for my project and need to have a target execute only if, in a certain locations, a whatever text file exists.
My file is:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MYFolder>C:\myfolder\</MYFolder>
  </PropertyGroup>

  <ItemGroup>
    <TXTFiles Include="$(MYFolder)*.scss"/>
  </ItemGroup>

  <Target Condition="???"></Target>
</Project>

What I tried
This:
Condition="!Exists('@(TXTFiles ->'%(FullPath)')')"

But it does not work.
This:
Condition="!Exists('@(TXTFiles)')"

But it does not work.
What condition can I use?

A: You can try make condition on the count of items and execute target if count is greater than zero or non-equal to zero.
Condition=" '0' != '@(TXTFiles->Count())' "

or
Condition=" '0' < '@(TXTFiles->Count())' "

Symbol < must be escaped in xml.


text:
Q: How to keep my include from making my page longer I'm not sure what I'm doing wrong here but I have a limited amount of work with js and php so this might be an easy fix:
I have a resume page and I'm using js to replace a target div on my resume as needed. This is working fine and I've placed the additional divs in a hidden div at the bottom of the page. Instead of coding the included content into the page I was calling it in via a set of php includes. I assumed as they were inside a visibility hidden div they shouldn't impact the page. While they are not visible they do make the page longer by the same height as the 3 includes combined.
Is there an easy fix to this or is it better to hard code the divs into the page itself?
(PLESE NOTE: I am having a problem adding the code clip but I can provide a link to the site if desired)

A: What you actually is looking for is display: none; property, rather than visibility: hidden;. The difference is, visibility: hidden; still occupy the same space it would with the content displayed, while display: none; removes the div altogether.
Also, note that display is not only used to show or hide an element, it also set the inline/block behaviour of an element among others, but generally: as long as it's a div, you should most likely switch between display: none; and display: block;. If it's an <a>, <b>, <span> or some other inline element, go with display: inline; instead of block. You could take a look here.
Also, the display property is easily configurable with jQuery with the $('div').show() and $('div').hide() functions.
Hope this helps. Let me know if I'm not being helpful!


text:
Q: Is there any built-in function for human-readable F# quotations? When quoting
<@ 1 + 1 @>

I want "1 + 1"
instead of
"Call (None, Int32 op_Addition[Int32,Int32,Int32](Int32, Int32),
      [Value (1), Value (1)])"

A: You'll have to write it yourself.  See the F# quotations visualizer code as a guide for transforming the quotations abstract syntax tree.

A: I have implemented a quotation decompiler as part of a larger open source project Unquote. It can decompile many simple F# quoted expressions as single-line non-light syntax strings (see the project's home page for a list of decompiler features). For example,
> decompile <@ (11 + 3) / 2 = String.length ("hello world".Substring(4, 5)) @>;;
val it : string =
  "(11 + 3) / 2 = String.length ("hello world".Substring(4, 5))"

@Kurt Schelfthout is correct about the many challenges faced when decompiling F# Quotations into human readable form. But from my work so far, I believe that it is possible to write a quotation decompiler which can generate correct F# code. Take match expressions and computation expressions for example, the Unquote decompiler can produce correct F# code in the following simple cases:
> decompile <@ match true with | true -> "hi" | _ -> "bye"  @>;;
val it : string =
  "let matchValue = true in if matchValue then "hi" else "bye""

> decompile <@ seq {yield 1; yield 2}  @>;;
val it : string =
  "seq (Seq.delay (fun unitVar -> Seq.append (Seq.singleton 1) (Seq.delay (fun unitVar -> Seq.singleton 2))))"

Infix and prefix operators are not too hard (as you can see in the first example), but source structure such as new lines and indentation is an interesting topic (though not terribly difficult, I think). However, single-line non-light syntax is sufficient for Unquote's requirements.

A: There is none, and it's not quite that easy, except in very simple cases. One of the main problems, for example, is the match construct. It is syntactic sugar for a whole bunch of if and switch statements (try printing a quotation with a match in, you'll see). Another one of those biggies are computation expressions, but I guess you could skip those at first.
Then there is a the rabbit hole of ambiguities you'll have to resolve, with conventions like the pipe operator starts a new line, let starts a new line, indentation, infix, prefix, special cases like the (::) operator and so forth.
All in all, doable, but not trivial. Sort of like decompiling.


text:
Q: How to make a PATCH request to am API with ASP.NET Core 2.2? I have an application that is written using C# on the top of ASP.NET Core 2.2. I created a controller that responds to a PATCH request called Update. Here is my controller
[Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
    [HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
    public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
    {
        // Do something
        return true;
    }
}

also, to return a 401 error when the user isn't authorized instead of a redirect, I added the following code to my Startup class
services.ConfigureApplicationCookie(config =>
{
    config.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = ctx =>
        {
            if (ctx.Request.Path.StartsWithSegments("/api", StringComparison.CurrentCultureIgnoreCase))
            {
                ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                ctx.Response.Redirect(ctx.RedirectUri);
            }

            return Task.FromResult(0);
        }
    };
});

Now to call this API using jQuery I did the following
$('.update-property').click(function (e) {
    e.preventDefault();
    var obj = $(this);
    $.ajax({
        url: '/api/Categories/Update',
        type: 'PATCH',
        data: {
            'propertyId': obj.data('property-id'),
            'listId': obj.data('list-id'),
            'isOn': obj.data('is-on') === 'True' ? 'false' : 'true'
        },

        success: function (response) {

            console.log(response);

            // if response unauthorized, redirect to the login page with the ReturnUrl
            // else if response.data is true then change the icon
        }
    });
});

But this request keeps returning a 404 http error code. I inspected this question in the developer tools and I see that the parameter are being set correctly and the URL is valid.
How can I correctly handle this PATCH request?

A: [Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
    [HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
    public ActionResult<bool> Update(int propertyId, int listId, bool isOn)

The route templates here determine the URL for your Update endpoint. In this case, the resulting URL template would be this:
api/Categories/{propertyId}/{listId}/{isOn}

So for example, a valid URL for this endpoint would be /api/Categories/12/34/true.
If you don't want to pass the values as parameters (since you already pass them in the body), you have to change the route template. For example, you could just remove the route template on the action method:
[HttpPatch, Authorize]
public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
// …

Then, the URL would be just api/Categories.
Of course, you could also make api/Categories/Update the URL for the endpoint, but with REST, it's usually not recommended to have method names in the URL. A PATCH request usually means "update this resource" and then you would be pointing to the URL of the resource.

A: you need to send request with localhost:44313/api/Categories url. Don't put update prefix. You just need to send Patch request to your localhost:44313/api/Categories endpoint.
with Parameters
localhost:44313/api/Categories/{propertyId}/{listId}/{isOn}


text:
Q: ScalaMock does not work with ScalaTest's TestNG/JUnit Support Traits I'm trying to use ScalaMock with ScalaTest as such:
class MyTest extends TestNGSuite with MockFactory with ProxyMockFactory {

  @Test def someTest() = ...
}

However, I get the following compile error with this code:
ERROR: MyTest.scala: error: overriding method runTests in trait TestNGSuite of type
       (testName: Option[String], reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper,
       filter: org.scalatest.Filter, configMap: Map[String, Any], distributor: Option[org.scalattest.Distributor],
       tracker: org.scalatest.Tracker)Unit;
INFO: method runTests in trait MockFactory of type (testName: Option[String],
      reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper, filter: org.scalatest.Filter,
      configMap: Map[String,Any], distributor: Option[org.scalatest.Distributor],
      tracker: org.scalatest.Tracker)Unit cannot overrride final member;
ERROR: other members with override errors are runTest
INFO: class MyTest extends TestNGSuite with MockFactory with ProxyMockFactory {
            ^

Looking at the source it looks like ScalaMock's MockFactory cannot be mixed into TestNGSuite or JUnitSuite.  ScalaMock's documentation is a bit sparse.
Is there any way to use ScalaMock with ScalaTest's Junit/TestNG support?
Thanks!

A: I'm afraid that ScalaMock with TestNG isn't something I've tested (TBH, I hadn't even noticed that ScalaTest had a TestNG runner!).
Can you please report this as an issue on the ScalaMock tracker and I'll see what I can do. If you can make a small example project that illustrates the problem available, that would be even better :-)


text:
Q: How to add fields in custom registration form, validate it and save to db? Im using a WP theme with a custom registration form. I want to add two fields to it (for phone number and company name). What to add to the php file of the form and what to the function file of theme to validate the fields and save the values in the database?
The structure of the theme is quite complex (at least according to my skills and knowledge).
This is the registration form: register_form.php - https://pastebin.com/A5s4QPGw. The theme has a core plugin that uses different Managers for different features of the theme. This is the manager responsible for registration: RegisterManager.php - https://pastebin.com/buFfhFaU.
Thank you for your attention


text:
Q: Перегрузка индексации Есть класс:
class A
{
   public:
     int& operator [] (int a)
     {
        return x.at(a);
     }
     int operator [] (int a) const
     {
        return x.at(a);
     }
   private:
     vector<int> x;
};

Так как реализация обеих перегрузок одинаковая, хочу объединить их в шаблон. Можно ли это сделать?

A: Нет.
Хоть эти два метода содержат одинаковый текст, но они абсолютно разные: один работает на константном объекте и возвращает целое число, вызывая константный метод at; другой работает на неконстантном объекте, возвращает ссылку из неконстантного метода at. В целом, у них разные сигнатуры и разная реализация.
К слову, обычно перегрузки делают так:
int& operator [] (int a)
const int& operator [] (int a) const

Шаблоны предполагают, что класс обобщается по некоторому параметру-типу (или значению). Здесь они вообще не при чём. Впрочем, если вы хотите, чтобы ваш класс поддерживал не только int, то можно сделать шаблон:
template <typename T>
class A
{
   public:
     T& operator [] (int a)
     {
        return x.at(a);
     }
     const T& operator [] (int a) const
     {
        return x.at(a);
     }
   private:
     vector<T> x;
};


text:
Q: Mongo through PyMongo DB taking too much RAM I have a small DB that I use to train my Python ML models. Data is in a collection with 20 mil documents. I accesso to data using this code.
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient['local']
collection = mydb['mydataset']
for i in tqdm(range(len(list_of_companies))):
    cursor = collection.find({'company': companies[i]})
    dataset_part_df = pd.DataFrame(list(cursor))
    dataset_df = pd.concat([dataset_df,dataset_part_df)
    del cursor

The PC Mongo and Python are running on has 32 GB or RAM. Mongo is 5.0.6 and is running as a service in Windows 10.
When whole dataset is loaded, Python is using 8 GB or RAM, while "MongoDB Database Server" is using 12 GB of RAM (leaving me with very little free RAM to do any data analysis)
I have already tried setting this parameters in Mongo CGC files:
storage:
  dbPath: G:\MongoDB\Server\5.0\data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
        cacheSizeGB: 2
        wiredTigerCacheSizeGb: 2
        directoryForIndexes: true

I have also tried to set "wiredTigerCacheSizeGB" instead of "wiredTigerCacheSizeGb", but nothing is working. Mongo DB just take so much ram.
Thanks a lot in advance to anyone that can help


text:
Q: 1D binpacking: pack vector of sorted doubles into a fixed number of bins so that they are equally filled I have a sorted vector of n floats/doubles. I want to pack them into k bins, each with the same maximum size. The goal is to pack them in a way so that the space left in each bin is maximized.
My naive algorithm packed the lengths into the bin that still has the most space left. The problem I encoutered was a case where this algorithm failed where an even simpler algorithm succeeded. That simpler algorithm was the standard example of packing the numbers in the first bin they fit into - and open a new one when they don't.
Since my problem a very easy special case of the general problem (it's 1D, has sorted inputs, fixed number of bins, each bin the same size) I was hoping for a better way to solve it. Ideally exact, but better than mine would still be helpful.
Also the condition that the space left should be maximized may be ignored it if leads to an easier/better solution.
edit: An example would be an input sequence of 5.0, 4.0 and 3.0 with a max bin size of 9.0. A naive solution would be 5.0 and 4.0 in the first bin, 3.0 in the second. But I want 5.0 and 3.0 to be in one, and 4.0 in the other bin so that the space that is left in the bins is as big as possible.
To clarify on the space: The total space left in all the bins is always the same, independent of where each length is put in. But I want that the space left in each bin is "as equal as possible". I understand that that is a secondary condition next to the optimal bin packing. Therefore if it helps, that condition can be ignored. I'm not sure yet myself how much it increases the difficulty of the problem.


text:
Q: How to get ticks from QueryPerformanceCounter in C#? I need to replace Stopwatch to avoid using getters for its properties. I am going to implement it using QueryPerformanceCounter. I only need ticks nothing else.
Can anyone provide a code snipet please, to get correct ticks (1/10000 of ms) or any other small but stable value.
Please note my server sets clock granularity down to 0.5 ms (not sure if it affects QueryPerformanceCounter) but just for you to know.
Please also note - I do not need a timer. I only need to measure time intervals between parts of code.
EDIT: to avoid confusion I really want to know what is lpPerformanceCount in QueryPerformanceCounter(out long lpPerformanceCount);

A: [DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);

Taken from http://www.codeproject.com/Articles/2635/High-Performance-Timer-in-C
Old but it should still work
EDIT: The internals of StopWatch actually use QueryPerformanceCounter, so using the managed code should provide identical results, with better compatibility.

A: Do NOT use StopWatch for high resolution timing without testing it. It has been a few years since I have tested it, but at that time it gave the default windows time resolution. You can tell because really, really fast things will take either 0 time or 10-15 milliseconds if it is using the default windows resolution (the default resolution is actually the resolution of thread context switches, presumably the default windows clock is updated at each context switch, which is about every 10-15 milliseconds).

A: I use the following class that gives the time accurate to 100ns on my system.
public class MStopwatch : Stopwatch
{
    private double _frequencyScaler;

    public MStopwatch()
    {
        _frequencyScaler = 1.0 / Stopwatch.Frequency;
    }

    public double ElapsedSeconds
    {
        get
        {
            return ElapsedTicks * _frequencyScaler;
        }
    }

}

A: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.gettimestamp.aspx
Stopwatch.GetTimestamp
You don't have to instantiate a Stopwatch object, GetTimestamp should return the number of ticks regardless of its context.

A: NOT A DIRECT ANSWER (but Potentially necessary support info follows):
Some of the provided answers are pretty good to directly answer your question.  However, to accomplish what you're trying to do, I would like to add a couple notes.
First, take into account the timing overhead of the just-in-time (jit) compiler which happens at runtime.  Any code where you grab the initial timestamp then do stuff, and then grab a final timestamp to subtract t2-t1 for the delta, for any functionality inside of stuff, if you include any functions you haven't called yet during the current process then the first time you call it, you will pay for the jit overhead to compile the bytecode into native code.  In this case, the cost is not representative of the actual runtime cost of performance critical code which is presumably code that is called frequently and yet whose jit cost is paid just once (on the first call to it in the process).  So call the timed code multiple times, throw out the first timing, and take an average.
Furthermore beware of the runtime costs of the garbage collector.  If you are just playing around, then it might be possible and interesting to benchmark code that strictly avoids allocating new objects.  But sometimes this is not easy particularly when you are calling functions whose implementations you cannot change. Also, I must grant you that the real world performance overhead of production code cannot avoid garbage collection overhead so getting a realistic figure should include this overhead.  That said, if your stuff includes code that allocates new objects, then it may kick off the garbage collector which will be expensive so prepare yourself for some potential outliers that you might want to throw out.
Second, the good answers provided the code to declare external functions to call from system dlls and that's great.  Getting these signatures correct in the general case can be a nuisance sometimes so I would like to mention a great resource for this: pinvoke.net.
A search for QueryPerformanceCounter gave me the signatures that put me a cut-and-paste away from the answer already given and it is a great resource for any system calls you want to make.
http://pinvoke.net/search.aspx?search=QueryPerformanceCounter&namespace=[All]

A: I don't remember from where I copied it, but this code works well for me:

        public class QueryPerfCounter
    {
        [DllImport("KERNEL32")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
    private long start;
    private long stop;
    private long frequency;
    double multiplier = 1.0e6;  // usecs / sec

    public QueryPerfCounter()
    {
        if (QueryPerformanceFrequency(out frequency) == false)
        {
            // Frequency not supported
            throw new Win32Exception();
        }
    }

    public void Start()
    {
        QueryPerformanceCounter(out start);
    }

    public void Stop()
    {
        QueryPerformanceCounter(out stop);
    }

    public double Duration(int iterations)
    {
        return ((((stop - start) * multiplier) / frequency) / iterations);
    }
}


text:
Q: How to only call onCreateView when fragment is visible? I'm using a ViewPager with 5 fragments and my problem is that when the first fragment is visible, it already loads the second one.
I read something about viewPager.setOffscreenPageLimit(); but default value for this is '1' and can't be set to '0' because ViewPager needs this for the swipe animation.
So the second fragment will always be loaded by default.
But my problem is that i have a global Arraylist in both fragments with different values loaded in each fragment and when i'm on fragment one, the values get overwritten because the second fragment is called.
How to only call onCreateView for each fragment when that fragment is visible for the user?

A: First, I would not use a global list. Make a baseFragment if you need to hold a similar type of list. If your goal is to share filtering among fragments, then simply pass the applied filters to each fragment so it knows how to manage its list as it loads or pass the list, but don't use a global that's just asking for trouble.
Second, onCreate is called on the pager on purpose so you can preload some things before it shows on the screen. It's to improve rendering performance as the user swipes from side to side. If you load as the swipe happens, it will be jumpy and bad.
Lastly consider moving your logic to onResume, unless you have good reason not to.
If that doesn't work for you, then monitor the page changing event and call a shared "load" method that you create on each baseFragment that you can simply call and handle your code there.

A: By using this you can give a try,
@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
}

A: View pager will load the near by fragments, even if you set setOffscreenPageLimit to 0. Since if the value is less than 1, they will set it as 1.
So onCreate, onCreateView... onResume of the near by fragments will be called before it is visible.
So just load your data in setUserVisibleHint.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(getView() != null && isVisibleToUser){
        loadData();
    }
}

But there exists a problem. This method(setUserVisibleHint) will be called before the onCreate of our fragment.
If you get the data from arguments.. We will get those data from onCreate or onCreateView of fragment. So the first visible fragment's setUserVisibleHint will be called, without data to load(getView() != null from the above method). For this we can use
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater,container,savedInstanceState);

    // This is because for the first fragment to loadData, since the
    // setUserVisibleHint is called before the onCreateView of the fragment.

    if(getUserVisibleHint()){
        loadData();
    }

    return view;
}

loadData is the method which will do data binding part of my fragment.
By doing this, For the first visible fragment loadData will be called from onCreateView and near by fragment it will be called from setUserVisibleHint.


text:
Q: PHP convert emojis in string to unicode I use the below code to convert an emoji to unicode, but how do i apply this to a string without affecting the other text in string.
function emoji_to_unicode($emoji) {
   $emoji = mb_convert_encoding($emoji, 'UTF-32', 'UTF-8');
   $unicode = strtoupper(preg_replace("/^[0]+/","U+",bin2hex($emoji)));
   return $unicode;
}

$var = "";
echo emoji_to_unicode($var);

If $var is hello , goodbye then the output is U+68000000650000006C0000006C0000006F000000200001F6000000002C00000020000000670000006F0000006F00000064000000620000007900000065
When it should be hello U+1F600, goodbye

A: Emojis are not 1-byte characters like 123abc@#$^, they are characters with 4 bytes so you can't remove them with unicode range or something like this. But you can select every character with 4 bytes:
function to_unicode($text) {
    $str = preg_replace_callback(
        "%(?:\xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2})%xs",
        function($emoji){
            $emojiStr = mb_convert_encoding($emoji[0], 'UTF-32', 'UTF-8');
            return strtoupper(preg_replace("/^[0]+/","U+",bin2hex($emojiStr)));
        },
        $text
    );
    return $str;
}

echo to_unicode( 'hello world ' );

output is hello world U+1F600
How it's working
First of all, you have to check 4 bytes characters with regex:
%(?:\xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2})%xs

and using preg_replace_callback function.
then use a callback function to encode selected character:
function($emoji){
   $emojiStr = mb_convert_encoding($emoji[0], 'UTF-32', 'UTF-8');
   return strtoupper(preg_replace("/^[0]+/","U+",bin2hex($emojiStr)));
}

resources:
Detect emoji (stackoverflow)
What is emoji?


text:
Q: Why won't this query cache in ColdFusion 9.01 using cfscript? I am writing a query in ColdFusion 9.01 script and having trouble understanding why it is not caching the results. The same exact query will cache when executed using the CFML tag syntax.
The SQL, datasource, username, password are not changing. I have dumpped the cfscript query object after instantiating it and verified the cachedWithin argument was properly received during init. I'm stumped.
CFScript Version that will not cache
var Q = new Query(
     SQL="SELECT * FROM TABLE"
    ,cachedwithin=createTimeSpan(0,0,60,0)
).execute().getResult();

CFML Tag Version that will cache
<cfquery name="local.q">SELECT * FROM TABLE</cfquery>

Thank you for your time and help.
Aaron

A: Give it a name! :)
var Q = new Query(
     SQL="SELECT * FROM TABLE"
    ,cachedwithin=createTimeSpan(0,0,60,0)
    ,name="myQuery"
).execute().getResult();

http://www.compoundtheory.com/?action=displayPost&ID=500

A: here: http://adiefatlady.posterous.com/compound-theory-getting-cfscript-queries-to-c


text:
Q: How to find the maximum average marks in 2D vector of string? I have taken the name and marks of each student in 2D vector of string.
How can we find the student name having maximum average Marks
I am not able to fetch the Marks of student as it is string in 2d vector.
I can do the same using STL Map. But how to do the same using 2D vector of string.
vector<vector<string>>vect {{"James", "70"}, {"Fernando", "40"}, {"Nick", "60"},{"James", "90"},{"Nick", "70"},{"Amit", "50"}};

Expected output is "James : 80"

A: You can do it this way as well
int max = stoi(vect[0][1]);
string name;
for(int i=0;i<vect.size();i++)
    If(max < stoi(vect[i][1]))
    {
        max = stoi(vect[i][1]);
        name.insert(0,vect[i][0]);
    }

Here, name is the person who's scored the maximum average marks

A: If you want to do the calculation in place, that is with O(1) additional memory requirements, you can use the following approach:

*

*Iterate over all the records.

*Find out if the actual name hasn't been already processed before (by comparing the name with all the records having lower indexes).

*If not, find all the records having the same name starting from the actual one while summing up the scores and their count.

*Calculate the average (sum / count).

*If the average is higher the up-to-now maximum, update this maximum to the actual one.

Hope you can write the code by yourself ;-)

Note that this approach does not modify the input vector. If you can to that, a better approach would be to sort it first by name and then perform one linear pass by its elements, as suggested by @mahbubcseju.

A: Firstly sort the vector by using the name as key .
After that all the same persons will be besides each others.
For Example:
  vector<vector<string>>vect {{"James", "70"}, {"Fernando", "40"}, {"Nick", "60"},{"James", "90"},{"Nick", "70"},{"Amit", "50"}};

   sort(vect.begin(),vect.end());
   for(int i=0;i<vect.size();i++){
      cout<<vect[i][0]<<" "<<vect[i][1]<<endl;
   }

This will output like following:

Amit 50
  Fernando 40
  James 70
   James 90
  Nick 60
  Nick 70

After that iterate through the row vector by the following way and calculate the average:
   int ma=-1;
   string maxPerson="";
   int counter=0;
   int cumSum=0;
   for(int i=0;i<vect.size();i++){

   if(i>0&&vect[i][0]!=vect[i-1][0]){
       int avg=(cumSum/counter);
       if(avg>ma){
          ma=avg;
          maxPerson=vect[i-1][0];
       }

      counter=1;
      cumSum=stringTonumber(vect[i][1]);
   }
   else {
       counter++;
       cumSum+=stringTonumber(vect[i][1]);
   }

}
    int avg=(cumSum/counter);
    if(avg>ma){
    ma=avg;
    maxPerson=vect[vect.size()-1][0];
   }
You can declare ma and avg variable as double to calculate the real average if need. Cz sometimes result can be 90.5 but int will not consider .5.
Whole code:
#include <bits/stdc++.h>

#define LEN 150
using namespace std;
int stringTonumber(string x)
{
    int num = 0;
    for (int i = 0; i < x.size(); i++) {
        num = num * 10 + x[i] - '0';
    }
    return num;
}
int main()
{
    vector<vector<string> > vect{ { "James", "70" }, { "Fernando", "90" }, { "Fernando", "80" }, { "Fernando", "100" }, { "Nick", "60" }, { "James", "80" }, { "Nick", "70" }, { "Amit", "50" } };

    sort(vect.begin(), vect.end());
    for (int i = 0; i < vect.size(); i++) {
        cout << vect[i][0] << " " << vect[i][1] << endl;
    }
    int ma = -1;
    string maxPerson = "";
    int counter = 0;
    int cumSum = 0;
    for (int i = 0; i < vect.size(); i++) {

        if (i > 0 && vect[i][0] != vect[i - 1][0]) {
            int avg = (cumSum / counter);
            if (avg > ma) {
                ma = avg;
                maxPerson = vect[i - 1][0];
            }

            counter = 1;
            cumSum = stringTonumber(vect[i][1]);
        }
        else {
            counter++;
            cumSum += stringTonumber(vect[i][1]);
        }
    }
    int avg = (cumSum / counter);
    if (avg > ma) {
        ma = avg;
        maxPerson = vect[vect.size() - 1][0];
    }
    cout << maxPerson << " " << ma << endl;

    return 0;
}

A: My approach: Use a map Student -> Vector of Marks, fill it, then average it.
map<string, vector<double> > marks;

for(const vector<string>& entry : vect)
{
    string name = entry[0];
    int mark = stod(entry[1]);
    marks[name].push_back(mark);
}

Now you have a map filled with a vector of marks for each student, easy to handle. If you want the averages, go like:
string best_student = "nobody";
double best_average = 0.;

for(auto const& entry : marks)
{
    const string& name = entry.first;
    const vector<double>& student_marks = entry.second;
    double average = accumulate(student_marks.begin(), student_marks.end(), 0) / student_marks.size();

    cout << "The student " << name << " has an average mark of " << average << endl;

    if(average > best_average)
    {
        best_average = average;
        best_student = name;
    }
}

cout << endl;
cout << "The student with the highest average mark is " << best_student << " with " << best_average << endl;

(Note that you need to #include<numeric> for std::accumulate, and that I used for each, thus you need at least C++11.)
Might not be the most time optimized approach, but works nicely and is quite readable as far as I see it.
I implemented this here: http://cpp.sh/6lijg
(I did some assumptions that one might check (/handle by something like throwing an exception if not met or printing some message): 1. The original vector is always correctly filled, that is every subvector has length 2; 2. the original vector always has at least one entry; 3. marks are non-negative and there is a student with a non-zero mark - else the initializations of best_student and best_mark are wrong.)


text:
Q: Why is location services not working as background task? In my app there is a location (area) to be watched. When the device is moved away from that location (it could be a distance as small as 5 - 10 meters) an AlertView pops up and a sound is played. When the app is in the background an local notification is generated. Tapping or sliding the notification brings the app to the front. This works fine. However, when running in the background the location updates stoppes after 15-16 minutes or so. The arrow is removed from the status bar. Bringing the app to the front the AlertView pops up and the sound is played. As far as I can see is location services getting a new fix on the current position and is the AlertView shown because the initial distance is greater then the area to be watched. Due to the small areas to be watched I think I could not use "significant-changes" or "didExitRegion". Is that true?
I set the tag in the info.plist to "App registers for location updates" in "required background modes".
Is there anyone out there who has a clou about what's goiing on?
Do I have to put some code in - (void)applicationDidEnterBackground:(UIApplication *)application {} and if so.... what should that be?
Thanks in advance,
Regards,
Adri

A: before startUpdatingLocation you can set your CLLocationManager's desiredAccuracy and distanceFilter fields for desired precission


text:
Q: Force CSS Hexcode in HTML Output I am trying to retrieve HTML-content from my (self-made) web based texteditor via a simple document.body.innerHTML retrieval which works fine.
For various reasons I want all css-color references (e.g. font-, border-,  background colors etc) to be in a hex-notation as opposed to a rgb() notation.
For example to convert all rgb values to hex of fontcolors I use a function rgb2hex():
var elems =     this.cont_doc.getElementsByTagName('*');
var len =       elems.length;
for(var n=0;n<len;n++)
{
    if(elems[n].style.getPropertyValue('color'))
    {
        var color = this.rgb2hex(elems[n].style.getPropertyValue('color'));//e.g rgb(255,38,0) becomes #ff2600
        elems[n].style.setProperty('color',color);
    }
}

However when I set colors in hex-format is always outputs the rgb-values in the end in for example var output_string = this.cont_doc.body.innerHTML; . Is there a way to preserve the hex-formatting or is there a regex solution i can apply in the final output_string ?
thank you
Patrick

A: As I understand, Chrome forces all to rgb when requesting innerHTML. You can easily use a regexp on the HTML tough.
This is an example, just use it on your innerHTML.

go.addEventListener('click', _ => {
  const replaceRGB = (all, r, g, b) => [r, g, b].reduce((a, x) => a + (+x).toString(16).padStart(2, '0'), '#');
  output.value = input.value.replace(/rgb\(\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\s*\)/g, replaceRGB);
});
<textarea id="input">
rgb(255, 50, 15);
</textarea>
<textarea id="output">
</textarea>
<button id="go">Process</button>


text:
Q: Writing to Object Variable from within script task I'm working on creating a maintenance job within SSIS and one of the steps requires me to read from a variable, check a value, and if that value is within a specific range, write that row to a new object for processing in a following step.  I have the majority of the script written, but I can't quite put together how to write values to an object from within a script task.
Here's what I have now:

To quickly run through this, it grabs all database names from the server then runs a database integrity check.  Following that it pulls up a list of all databases and their last known good integrity check.  The final ForEach Loop is where I'm experiencing issues.  I want it to take the object from the previous SQL task, read the variables, and if the last known good date is near the current time, feed it into a new object for use in a coming step to back that database up.

A: I would create a new Data Flow and use the current "Execute SQL Task" code for a new OLE DB Source. Then I would connect it to a Script Transformation (within the Data Flow) with your current "Script Task" logic.  The Data Flow would be completed with a Recordset Destination, which would load the object variable.


text:
Q: When I create one file in Emacs, I can not open the directory I use C-x C-f and C-X C-s to save a file to directory "test", then I can not open the test directory with "tab", it says "Dired (directory): ~/test.....".
I want to know what is the wrong and the correct method to create a file in emacs, thanks!

A: Emacs distinguishes between files and buffers. You do all your editing in buffers, which do not necessarily have to be associated with a file (see, e.g., the *scratch* buffer). However, you often want to edit a buffer that is associated with a file. In that case you visit (Emacs lingo for "open") said file with C-x C-f.
Let's say you have a directory "test" in your home directory, and in that directory a single file "foo.txt". If you want to edit the contents of that file, visit it by typing:
C-x C-f ~/test/foo.txt RET
That's easy enough: now you get a new buffer in Emacs which is conveniently named after the file you're visiting ("foo.txt"). If you want to store changes you've made in the buffer back to the associated file, you type C-x C-s, and Emacs will write the contents of the buffer to the file "~/test/foo.txt".
This mechanism also works for files that do not exist when you start editing!
If you type, say,
C-x C-f ~/test/bar.txt RET
You get a buffer associated with a (yet non-existent) file "bar.txt" in the directory "~/test". Again, you can edit that buffer to your liking and then save the buffer with C-x C-s. The first time you do that, a new file is created.
If you want to create a buffer named "baz" that is not associated with any file, type
C-x b baz RET
Since it is not associated with a file yet, typing C-x C-s in that buffer will prompt you to specify a file-name. After saving, the buffer will be associated with the file you specified.
Finally, if you're in a buffer that is associated with a file, but you want to save it to a different file, you can do so with C-x C-w, which will give you the same prompt as in the previous case. Again, the buffer will be associated after saving with the file you provide.

Tab completion does work in all of the commands that ask you for a file name. If you think it doesn't then it might be because the file you think should be completed does not exist (also beware of upper-/lower-case distinctions in file names), or because another file with the same prefix forbids further disambiguation. Tapping TAB twice should list the available completions in a temporary buffer, letting you continue specifying the path name until it is complete.

Dired mode is pretty much orthogonal to all of the above. It is a mode for "editing" directories, i.e., doing file system operations. You invoke it by typing C-x d, which you may have typed accidentally?! It is quite powerful, but also quite complex. See here for its documentation.


text:
Q: Weird behavior of VirtualKey codes in java I am getting keyboard input from a phone, and trying to display that on the computer using the robot class. Since I get ascii from the phone, I have a hashmap for ascii to VirtualKey value conversions. But my current code has some weird behavior. When I try to map certain symbols in the hashmap such as ! " ' @      I get a NullPointer Reference exception when I run it. For excample, for the ! , The phone sends the right unicode value (33) and in the hashtable I have (int)'!' as the key, which is also 33. So it should return VK_EXCLAMATION which is what it is mapped to, but it returns null :( Can someone please help?
Here is my code snipped where I do the lookup:
int unicodekey = scanner.nextInt(); //unicode
    robotkey = ascii2VK.asciiForVirtualKey.get(unicodekey);
    robot.keyPress(robotkey);
    robot.keyRelease(robotkey);

And my hashmap looks like this:
public class ascii2VK {
      protected static final Map<Integer, Integer> asciiForVirtualKey;
            static {
                asciiForVirtualKey = new HashMap<Integer, Integer>();
                asciiForVirtualKey.put(KeyEvent.VK_UNDEFINED, 0);
                asciiForVirtualKey.put(KeyEvent.VK_QUOTE, (int)'\'');
                asciiForVirtualKey.put(KeyEvent.VK_QUOTEDBL,(int)'"');
                asciiForVirtualKey.put(KeyEvent.VK_AMPERSAND, (int)'&');
                asciiForVirtualKey.put(KeyEvent.VK_BACK_QUOTE, (int)'`');
                asciiForVirtualKey.put(KeyEvent.VK_NUMBER_SIGN, (int)'#');
                asciiForVirtualKey.put(KeyEvent.VK_EXCLAMATION_MARK, (int)'!');
                asciiForVirtualKey.put(KeyEvent.VK_AT, (int)'@');
                asciiForVirtualKey.put(KeyEvent.VK_DOLLAR, (int)'$');
                asciiForVirtualKey.put(KeyEvent.VK_BACK_SLASH, (int)'\\');
                asciiForVirtualKey.put(KeyEvent.VK_SLASH, (int)'/');
    .
    .
    .
    .
    }

A: You should to reverse keys and values in your map.
The KeyEvent.VK_EXCLAMATION_MARK is the constant with value 0x0205 (517 decimal). But you try to find it by the 33 code, which is actually (int)'!'
This will be the right ordering:
asciiForVirtualKey.put((int)'!', KeyEvent.VK_EXCLAMATION_MARK);

and so on.