text:
Q: Different Metastore/Data Catalog options with Apache Spark? What are the metastore/data-catalog options I can use with Apache Spark?
In the simples case, I can use the Hive Metastore - which works great with Hive, Spark and Presto.
Are there any other data catalog options I can use here?

A: Unashamedly from the documentation to be found at https://spark.apache.org/docs/latest/sql-data-sources-hive-tables.html:

Spark SQL also supports reading and writing data stored in Apache
  Hive. However, since Hive has a large number of dependencies, these
  dependencies are not included in the default Spark distribution. If
  Hive dependencies can be found on the classpath, Spark will load them
  automatically. Note that these Hive dependencies must also be present
  on all of the worker nodes, as they will need access to the Hive
  serialization and deserialization libraries (SerDes) in order to
  access data stored in Hive.
Configuration of Hive is done by placing your hive-site.xml,
  core-site.xml (for security configuration), and hdfs-site.xml (for
  HDFS configuration) file in conf/.
When working with Hive, one must instantiate SparkSession with Hive
  support, including connectivity to a persistent Hive metastore,
  support for Hive serdes, and Hive user-defined functions. Users who do
  not have an existing Hive deployment can still enable Hive support.
  When not configured by the hive-site.xml, the context automatically
  creates metastore_db in the current directory and creates a directory
  configured by spark.sql.warehouse.dir, which defaults to the directory
  spark-warehouse in the current directory that the Spark application is
  started. Note that the hive.metastore.warehouse.dir property in
  hive-site.xml is deprecated since Spark 2.0.0. Instead, use
  spark.sql.warehouse.dir to specify the default location of database in
  warehouse. You may need to grant write privilege to the user who
  starts the Spark application.

But may be you mean something else? Simple cases?


text:
Q: What is the meaning of this Entity Framework exception? What is the meaning of this exception? Where can I find references of the cause to this kind of exception?

The changes to the database were committed successfully, but an error
  occurred while
      updating the object context. The ObjectContext might be in an inconsistent state.
      Inner exception message: Metadata information for the relationship
      'MyModel.FK_T_WORKER_VEHICLE_T_VEHICLE' could not be retrieved. If mapping attributes are used, make sure that the
  EdmRelationshipAttribute for the relationship has been defined in the
  assembly.  When using convention-based mapping, metadata information
  for relationships between detached entities cannot be determined.
      Parameter name: relationshipName

I am using edmx with code generation set to Default. The pocos are in different project then the edmx file.

A: In my case, I got same error when I added a new entity(A) to my EDMX diagram  which A has Foreign key reference to an existing entity B. Then this error came up when I tried to do CRUD for B.
I did some researches and followed a tip on MetadataException when using Entity Framework Entity Connection which advises to rename metadata in Connection String but it didn't work for me.
Steps to resolve:
The issue was in entity A not B. You need to check newly added entity A to be mapped correctly to your class A in your domain. Check property names and property types to be same (i.e. a column might need to be converted to an Enum type in your diagram to be same with your entity). Keep in mind that property names are case sensitive so if they are in upper-case in your entity it should be in upper-case in your diagram.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding Random numbers into a heap According to Eclipse, I'm not allowed to directly add a randomNumber arraylist into my "Comparable" parameter. I haven't a clue how to add them in.
Random generator = new Random(777);
MinHeap mh = new MinHeap();

for(int i = 0; i < 20; i++)
{
    System.out.println(generator.nextInt(100));
    mh.add((Comparable) generator);
}

This is my method for adding(in another class)
 public void add(Comparable newElement)
  {
  // Add a new leaf
  elements.add(null);
  int index = elements.size() - 1;

  // Demote parents that are larger than the new element
  // change this last "comparator" to < for maxHeap and > for MinHeap.
  while (index > 1
        && getParent(index).compareTo(newElement) < 0)
  {
     elements.set(index, getParent(index));
     index = getParentIndex(index);
  }

  // Store the new element into the vacant slot
  elements.set(index, newElement);

}
I get this error: java.util.Random cannot be cast to java.lang.Comparable
Why??

A: You are trying to cast generator which is the Random Object instead of random value you get from using the generator
You may auto box the value to Integer which implements Comparable
Try:
Integer rand = generator.nextInt(100);
System.out.println(rand);
mh.add(rand);

A: Because Random does not implement Comparable.


text:
Q: Oracle convert varchar to timeStamp gives ORA-01843: not a valid month SYSCREATEDATE is saved as varchar2 in DB. Value is as follows:
SYSCREATEDATE
10/17/2006 7:44
11/29/2011 6:17
11/16/2011 11:46
2/27/2012 4:01
2/27/2012 4:01
2/27/2012 4:01

Now i want to convert the field to timestamp and pick dates less than a certain date say '06/01/2020'.
Tried this:
select * from legacy_case where  TO_TIMESTAMP(SYSCREATEDATE, 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00';

I am getting the below error:
ORA-01843: not a valid month
01843. 00000 -  "not a valid month"
*Cause:
*Action:

Any input please?

A: Several issues/comments:

*

*never store dates in varchar2 fields.  use a proper DATE or TIMESTAMP data type to avoid parsing errors to begin with.  This is just asking for trouble.  Better to enforce validation with the proper data types.

*Is the date format in this field 12 hour AM/PM or 24 hours?  I don't see any values > 11:xx so can't tell, but HH format is only for hours 1-12.  If the timestamp string is 24 hour format, then you need to use HH24.

*Never use string literals in a comparison, always convert using to_date or to_timestamp, as the literal may not match the current NLS_DATE_FORMAT default and may not be parsed properly.  You can see the default format with the following query:
select *
from nls_session_parameters
where parameter = 'NLS_DATE_FORMAT';

A: Convert a sting literal to timestamp explicitly
select *
from legacy_case
where  TO_TIMESTAMP(SYSCREATEDATE, 'MM/DD/YYYY HH:MI:SS') < TO_TIMESTAMP('06/01/2020 00:00:00', 'MM/DD/YYYY HH24:MI:SS')

A: I tried to rewrite the statement to test your time format. It did throw ORA-01843.
SQL> select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00';
select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH:MI:SS') < '06/01/2020 00:00:00'
                                                                                *
ERROR at line 1:
ORA-01843: not a valid month

The pointer (*) in the error message indicates that the string '06/01/2020 00:00:00' is the source of problem.
To make the comparison succeed, you should compare both sides on the same base. For example.
SQL> select 'TRUE' "Compare" from dual where to_timestamp('10/17/2006 7:44', 'MM/DD/YYYY HH24:MI:SS') < to_timestamp('06/01/2020 00:00:00','MM/DD/YYYY HH24:MI:SS');

Comp
----
TRUE

In the above query, I use TO_TIMESTAMP() function on both side, additionally, I use HH24 instead of your HH. This time, the test is passed.


text:
Q: How to remove a html element using :not and jquery I am trying to use the following code:
$(':not(.fc-event.active-wrapper) .outer-event-info-wrapper').remove();

I assumed that this would remove all elements with an 'outer-event-info-wrapper' class, which do NOT have a parent of .fc-event.active-wrapper. What looks like is happening is that ALL elements with 'outer-event-info-wrapper' class are being removed.
Am I doing something wrong here?
EDIT:
Here is my whole script:
eventClick: function(calEvent, jsEvent, view) {
                console.log($(this).find('.outer-event-info-wrapper'));
                //$(this).find('.outer-event-info-wrapper').remove();
                $('.active-event').removeClass('active-event')
                $(this).addClass('active-event');
                if(!$(this).hasClass('active-event')) {

                }
                //$('.outer-event-info-wrapper').remove();
                $('.outer-event-info-wrapper').not('.fc-event.active-wrapper .outer-event-info-wrapper').remove();
                var url = $(this).attr('href');
                console.log(url);
                var $this = $(this);
                var $thisHtml = $this.html();
                $.get('calendar/event/teaser',{url: url},function(data, status) {
                        if(status) {
                            $this.html($thisHtml + data);
                        }
                    },
                    'html'
                );
                return false;
            }

A: You could select all .outer-event-info-wrapper then filter out .fc-event.active-wrapper .outer-event-info-wrapper elements like
$('.outer-event-info-wrapper').not('.fc-event.active-wrapper .outer-event-info-wrapper').remove();

$('.outer-event-info-wrapper').not('.fc-event.active-wrapper .outer-event-info-wrapper').remove();

  1
  2
  3

4
5
6

Your selector won't work if there is at least one ancestor which do not have the class fc-event.active-wrapper, which there will be like html, body etc

A: You just need a > between your two selectors to express the parent-child relationship. At the moment with just a space separator you're specifying an ancestor-descendant relationship, and all your .outer-event-info-wrapper elements are descendants of at least one not .fc-event.active-wrapper ancestor.
$(':not(.fc-event.active-wrapper) > .outer-event-info-wrapper').remove();

A: If you need a single selector string (such as when passing a selector as an option to a plugin) you can use a format like:
'.outer-event-info-wrapper:not(.fc-event.active-wrapper *)'

The general form is:
'<selector to match>:not(<parent to exclude> *)'

A: Try this..
$(".fc-event.active-wrapper").has(".outer-event-info-wrapper").remove()


text:
Q: Uniqueness for tempered distributional Cauchy problems
Question. Assume that $U\in C^1(\,[0, \infty)\to \mathcal{S}'(\mathbb{R}^n)\,)$ is a solution to the following tempered distributional Cauchy problem
  $$\tag{CP}\begin{cases}
\frac{ d U}{dt} = f \cdot U(t), & t>0 \\
U(0) = 0
\end{cases}
$$
  where $f\in C^\infty(\mathbb{R}^n)$ is a smooth function not depending on $t$. Is it true that $U(t)=0$ at all times $t>0$?

The background for this question comes from a passage in the book on PDEs by Michael E. Taylor.  The author claims that the problem
\begin{equation}
\begin{cases}
\frac{\partial u}{\partial t} -\Delta u =0, & t>0,\ x\in \mathbb{R}^n \\
u(0, x)=u_0
\end{cases}
\end{equation}
has a unique tempered distributional solution if $u_0$ is a tempered distribution. (This is not entirely trivial, as uniqueness fails if one imposes no growth conditions on $u$). The proof via Fourier transform is essentially reduced to the statement that the Cauchy problem
$$
\begin{cases}
\frac{\partial \hat{u}}{\partial t}(t, \xi) + \lvert \xi\rvert^2 \hat{u}(t, \xi)=0, & t > 0 \\
\hat{u}(0, \xi)=0\\
\hat{u}\in C^1(\, [0, \infty)_t \to \mathcal{S}'(\mathbb{R}^n_\xi)\, )
\end{cases}
$$
has the unique solution $\hat{u}(t, \xi)\equiv 0$. This does not seem obvious to me and that's why I am posing this question.

A: I think this is a great question.  This is the direction I would try.  So I presume that you are able to prove this if $f$ is compactly supported (since multiplication by $f$ would then be a continuous operation from $\mathcal S \to \mathcal S$).  Secondly, I presume that there is a theorem that says if $\mu, \nu \in \mathcal S'$, and $\mu(\phi) = \nu(\phi)$ for all $\phi \in \mathcal S$ which are compactly supported, then $\mu = \nu$.  I think that whatever proof is used to show this would have to be an important part of my argument.
So pick a bump function $\rho \in \mathcal S$ such that $\rho(x) = 1$ if $|x| \le 1$, and $\rho(x) = 0$ if $|x| \ge 2$, and $\rho(x) \in [0,1]$ for all $x \in \mathbb R^n$.
Then for each positive integer $m$, let $U_m$ be the solution to the equation
$$ \frac d{dt} U_m = \rho(\cdot/m) f \cdot U_m ,\quad U_m(0) = 0$$
and show that $U_m \equiv 0$.  Then show that $U(t,\cdot) = U_m(t,\cdot)$ on $B(0,m)$.  And then conclude $U = \lim_{m\to\infty} U_m = 0$.

A: Here's a partial solution suggested to me by my thesis director. It is partial because it needs some additional assumption on $f$. Either $f$ must be real valued and each of its derivatives must be bounded above, or $f$ must be complex valued and each of its derivatives must be bounded. $^{[1]}$ In particular, this method of proof works when $f$ is the symbol of the Laplacian and also when $f$ has compact support.
This partial result could then be plugged into Stephen Montgomery-Smith's great answer to eliminate the additional assumption on $f$. I haven't still checked the details, though.
Let us consider our Cauchy problem together with a suitable dual problem:
$$\tag{CP}
\begin{cases}
\partial_t U - f\cdot U = 0, & U \in C^1(\, [0, +\infty) \to \mathcal{S}'\, ) \\
U(0) = 0
\end{cases}
$$
and
$$
\tag{CP'}
\begin{cases}
\partial_t \phi + f\cdot \phi = 0, &  t\in(0, T) \\
\phi(T)=\psi \in \mathcal{S}
\end{cases}
$$
Here $T > 0$ and $\psi\in \mathcal{S}$ are arbitrary. Our task is to prove that
$$
\langle U(T), \psi\rangle=0.
$$
Now the dual problem (CP') has the unique classical solution
$$
\phi(t, \xi) = e^{( T - t )f(\xi)} \psi(\xi).
$$
Our assumptions on $f$ imply that $\phi \in C^1(\,[0, +\infty)\to \mathcal{S}\, )$. We may therefore use $\phi(t)$ as a test function for $U(t)$. The resulting pairing is constant, because
$$
\begin{split}
\frac{d}{dt} \langle U(t), \phi(t) \rangle & = \langle f U (t), \phi(t) \rangle \\
& = \langle U(t), f\phi(t)\rangle \\
& = -\frac{d}{dt} \langle U(t), \phi(t) \rangle.
\end{split}
$$
We infer that
$$
\langle U(T), \psi\rangle = \langle U(T), \phi(T)\rangle=\langle U(0), \phi(0)\rangle = 0.
$$
Since $T$ and $\psi$ are arbitrary, we conclude that $U\equiv 0$.

$^{[1]}$ Actually, we need the slightly less stringent requirement that $e^{\lambda f}$ is a slowly increasing function for any $\lambda>0$. For more information one may look into this French Wikipedia page.


text:
Q: Updating ALL SOLine items unit prices dynamically when a new SOLine is added I have a stored procedure that's called by a PXAction. I know it's against Acumatica's best practices to use a stored procedure, but I have yet find an alternative solution for my goal. The stored procedure evaluates each line item and the price class it's associated with depending on the breakQuantity that determines the unit price. If multiple items belong to the same price class == or exceed the break quantity the unit price is reduced.
What I started with was a row updating
 protected virtual void SOLine_RowUpdating(PXCache sender, PXRowUpdatingEventArgs e)
    {
        SOLine row = (SOLine)e.Row;
        formalizeOrderTotal(row);
    }

then in my formalizeOrderTotal function it performed a foreach loop on SOLine in lines.Select() to add up order quantity. As a test i just tried adding up all order quantities and applying it to every line item. This only updated after refreshing which negates the purpose of moving the stored procedure to a c# function/Acumatica event handler.
If anyone has some recommendations a good approach to updating all line items in cache it would be greatly appreciated if you could provide some input.

A: Try using Base.Transactions.View.RequestRefresh(); which will ask the grid to refresh itself. In this example, I am setting each line quantity to the number of SOLines present in the grid.
using PX.Data;
namespace PX.Objects.SO
{

    public class SOOrderEntry_Extension:PXGraphExtension<SOOrderEntry>
    {
        protected virtual void SOLine_RowUpdating(PXCache sender, PXRowUpdatingEventArgs e)
        {
            SOLine row = (SOLine)e.Row;
            formalizeOrderTotal(row);
        }

        private void formalizeOrderTotal(SOLine row)
        {
            foreach (SOLine line in Base.Transactions.Select())
            {
                if(line.Qty == Base.Transactions.Select().Count)
                {
                    continue;
                }

                line.Qty = Base.Transactions.Select().Count;
                Base.Transactions.Update(line);
                Base.Transactions.View.RequestRefresh();
            }
        }
    }
}


text:
Q: how to get all keys of this multidimensional array I have similar problem, which is here: solved Problem
But I would like to get such an array in return as final result for this demo array in 1.
thanks a lot!
return array I would like to get:
    [0] => "0.name "
    [1] => "0.id "
    [2] => "0.phone "
    [3] => "0.Base.city "
    [4] => "0.EBase.city "
    [5] => "0.Qty "
    [6] => "1.name "
    [7] => "1.id "
    [8] => "1.phone "
    [9] => "1.Base.city "
    [10]=> "1.EBase.city "
    [11]=> "1.Qty "

I have tried this: But does not work:
        function array_flat(array $myarr)
        {
            $myline = "";
            foreach ($myarr as $key => $value)
                {
                if ( $myline == "" ){$myline=sprintf("%s",$myarr[$key]);}
                else {$myline=sprintf("%s%s",$myline,$myarr[$key]);}
                }
            return array($myline);
        }

        function array_keys_multi(array $array)
        {
            $keys = array();

            foreach ($array as $key => $value) {
            $keys[] = $key;

            if (is_array($value)) {
                $keys = array_merge($keys, array_keys_multi($value));
            }
                else {
                    $keys = array_flat($keys);
                }

            }

            return $keys;
        }

Moreover I have found this:Maybe it could help to solve my request:
get all path of an array

A: Yes this link did what I wanted:
Solution
             function getKeyPaths(array $tree, $glue = '_')
             {
                 $paths = array();
                 foreach ($tree as $key => &$mixed) {
                     if (is_array($mixed)) {
                         $results = getKeyPaths($mixed, $glue);
                         foreach ($results as $k => &$v) {
                             $paths[$key . $glue . $k] = $v;
                         }
                         unset($results);
                     } else {
                         $paths[$key] = $mixed;
                     }
                 }

                 return $paths;
             }

to call it by:
     print_r(getKeyPaths($jsonquotesum));

A: Use array_key().
You will get all the keys.
doc here:
http://php.net/manual/fr/function.array-keys.php


text:
Q: How to save password to file on android? I got  problem with writing a file to Android storage. I use a lot  of examples, most annoying problem is

java.io.FileNotFoundException: /storage/emulated/0/Android/fileSD (Permission denied)

Yes, I'm adding uses-permission to my manifest
This is my Activity:
public class MainActivity extends Activity {
    // init variables
    EditText pass;
    Button login;
    String password;
//    final String DIR_SD = "/Android";
//    final String FILENAME_SD = "fileSD";
//    final String LOG_TAG = "myLogs";

//init onCreate method that provide our logic when activity start open
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

//        if(mFileName.()){
//
//        }

    pass = (EditText) findViewById(R.id.pass);
    login = (Button) findViewById(R.id.button);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            password = pass.getText().toString().trim();

                if (TextUtils.isEmpty(password)) {

                    pass.setError("password mustnot be empty");
                    pass.focusSearch(View.FOCUS_DOWN);

                } else if (password.length() >= 6 && password.length() <= 24) {

                    Toast.makeText(getApplicationContext(), "validation sucess", Toast.LENGTH_LONG).show();

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

                } else {
                    pass.setError("password length must be match:5=<password>=10");
                    pass.focusSearch(View.FOCUS_DOWN);
                }

          }
    });

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

if user open app at first time, he enter the password and it should write to file. If file exist we should read it and compare with pass that user will enter, if it equals start new activity, else display message that it was incorrect pass.
please help, i try do it for few days and idk what i should to do

A: is not sufficient to write it uses-permission to your manifest, you should handle it in your runtime,
plus its a bad  idea to store user password in a file, everyone can read it

A: Try to use SharedPreferences, you can save password like this
SharedPreferences sharedPreferences = getSharedPreferences("PrefName", MODE_PRIVATE);
sharedPreferences.edit().putString("password", "Your Password").apply();

When you need it you can retrieve easily
sharedPreferences.getString("password", "")


text:
Q: Trying to get slider to work, "appendTo' not working Trying to fix a widget on my website which displays some RSS feed. Got the scrolling but can't figure out how to restart the scrolling.
I have tried The 'appendTo' but without any succes. I can't find a solution, please help me out.
http://server.info-spot.net/
Regards!
(function($){
$.fn.vTicker = function(options) {
    var defaults = {
        speed: 700,
        pause: 3000,
        showItems: 3,
        animation: '',
        mousePause: true,
        isPaused: false
    };
var options = $.extend(defaults, options);

moveUp = function(obj2, height, paused){
    if(paused) return;

    var obj = obj2.children('ul');

        first = obj.children('li:first').clone(true);

        obj.animate({top: '-=120px'}, options.speed, function() {
            $(this).children('li:first').remove();

            first.appendTo(obj);
        });

    if(options.animation == 'fade') {
        obj.children('li:first').fadeOut(options.speed);
        obj.children('li:last').hide().fadeIn(options.speed);
    }

        first.appendTo(obj);
};

return this.each(function() {
    var obj = $(this);
    var maxHeight = 0;
    var itempause = options.isPaused;

    //obj.css({overflow: 'hidden', position: 'relative'})
    obj.css({position: 'relative'})
        .children('ul').css({position: 'absolute', margin: 0, padding: 0})
        .children('li').css({margin: 0, padding: 0});

    obj.children('ul').children('li').each(function(){

        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });

    obj.children('ul').children('li').each(function() {
        $(this).height(maxHeight);
    });

    obj.height(maxHeight * options.showItems);

        var interval = setInterval(function(){ moveUp(obj, maxHeight, itempause); }, options.pause);

    if (options.mousePause)
    {
        obj.bind("mouseenter",function() {
            itempause = true;
        }).bind("mouseleave",function() {
            itempause = false;
        });
    }
});

};
})(jQuery);


text:
Q: PHP Contact Page Works but Shows Value Code I have a .php contact page that works and sends the information from the form to my email, but it also shows {value=""} in two places on my form.

Am I missing "

The code is as follows:
<?php

        <form method="post" action="#contact" role="form">

                          your name

                              <input type="text"
                              input pattern=".{5,}"
                              required title="5 characters minimum"
                              name="name"
                              id="input-field-name"
                              class="form-control"
                          >
                          value="<?php echo $_POST['name']; ?>"

                      your email address

                      <input type="email"
                          name="email"
                          id="input-field-email"
                          input pattern=".{6,}"
                          required title="6 characters minimum"
                          class="form-control"
                        >
                      value="<?php echo $_POST['email'];?>"

A: Here your error
id="input-field-name"
                          class="form-control"
                      >
                      value="<?php echo $_POST['name']; ?>"

you put value=".... after the closing > of the input

A: Use code as follows.Input value always in tag

    <form method="post" action="#contact" role="form">

                      your name

                          <input type="text"
                          input pattern=".{5,}"
                          required title="5 characters minimum"
                          name="name"
                          id="input-field-name"
                          class="form-control"
                          value="<?php echo $_POST['name']; ?>"
                      >

                  your email address

                  <input type="email"
                      name="email"
                      id="input-field-email"
                      input pattern=".{6,}"
                      required title="6 characters minimum"
                      class="form-control"
                      value="<?php echo $_POST['email'];?>"
                    >


text:
Q: Quiz website with timer for questions using javascript I wanted to ask how a quiz website works with an associated timer with each question. Since each question has a timer associated with each question and is handled at the front end, a client can change the value for these timers using developer console as these will be global variables.

A: No. They can not edit the time. Since the time is coming from the server,  you shouldn't be able to edit it using the console. If you are able to edit it from the console, usually the server will notice that this client is off sync and try to bring it back on sync. If it does neither, it's probably bad programming

A: Use an Immediately Invoked Function Expression (IIFE), which will put your variables inside the function and make them non-global:
(function(){
    // Put your code in here.
})();

Note that while someone won't be able to change the time directly, they can still spoof different requests. You should probably keep track of time server-side.


text:
Q: Does pcap_findalldevs() in WinPcap work for IPv6 in Windows10? I'm checking whether pcap_findalldevs can find IPv6 devices in Windows10
I'm not sure because Windows 10 doesn't seem one of supported platforms according to the homepage
(https://www.winpcap.org/install/default.htm)

Supported platforms:
Windows NT4/2000
Windows XP/2003/Vista/2008/Win7/2008R2/Win8 (x86 and x64)

I checked it out as below steps
(1) download developer's pack : https://www.winpcap.org/devel.htm
(2) open cygwin
(3) mv WpdPack\Examples-pcap\iflist
(4) build and run
As you see below result, it succeeds finding IPv4 devices
but it doesn't provides enough information for IPv6 devices
"Realtek USB NIC" is the device for IPv6
C:\cygwin64\home\WpdPack\Examples-pcap\iflist> iflist.exe

{6BA7B1CA-9393-4747-A1C7-BAFA5BF3CF0F}
Description: Microsoft                                                                                Loopback: no
Address Family: #2
Address Family Name: AF_INET
Address: 10.177.98.131
Netmask: 0.0.0.0
Broadcast Address: 0.0.0.0

{6C5D9B8C-CA69-4E39-9946-A2CC10072117}
Description: Realtek USB NIC
Loopback: no

{1E922BCB-F3EF-4DC8-94A7-DCF1349730B4}
Description: VMware Virtual Ethernet Adapter
Loopback: no
Address Family: #2
Address Family Name: AF_INET
Address: 192.168.0.1
Netmask: 0.0.0.0
Broadcast Address: 0.0.0.0

A: WinPcap is a dead product.  Even the WinPcap advise switching to Npcap.  From the WinPcap news:

15 September 2018
WinPcap, though still available for download (v4.1.3), has not seen an upgrade in many years and there are no road map/future plans
to update the technology. While community support may persist,
technical oversight by Riverbed staff, responses to questions posed by
Riverbed resources, and bug reporting are no longer available.
Gordon Lyon, Nmap project founder, has created Npcap, a packet capture library for Windows, that includes WinPcap compatibility and
may be a suitable replacement for WinPcap and WinPcap Pro. Information
can be found at https://nmap.org/npcap/.

I would suggest looking into Npcap instead: https://nmap.org/npcap/guide/npcap-devguide.html


text:
Q: Get Posts by Custom Taxonomy on Custom Post I have been trying and struggling to pull in custom posts based on the taxonomy slug 'peers' I am not sure what I am doing wrong!
   'coaches_post_type' => [
        'slug'                      => 'coaches',
        'name_plural'               => 'Coaches',
        'name_singular'             => 'Coach',
        'taxonomy_slug'             => 'coaches_category',
        'taxonomy_rewrite'          => 'coaches-category',
        'taxonomy_name_plural'      => 'Coach Categories',
        'taxonomy_name_singular'    => 'Coach Category'
    ],

public static function WhoHTML() {

    $args = array(
        'post_type' => 'coaches',
        'posts_per_page' => '4',
        'order' => 'DESC',
        'orderby' => 'date',
        'tax_query' => array(
            array(
                  'taxonomy' => 'coaches_category',
                  'field' => 'slug',
                  'terms' => 'peers'
            )
         )
    );

    $coaches = new WP_Query($args);

    foreach ($coaches->posts as $coach) {

        $image = get_the_post_thumbnail_url($coach->ID);

        $html .= "

{$coach->post_title}

";
    }

    echo $html;
    return;
}

A: <?php
// get the WP_Query object
$query = new WP_Query($args);

// Missed essential point:
// loop through the WP_Query object
// to get the array of distinct posts objects
$coaches = $query->posts;

// each $coach is distinct post object now
foreach( $coaches as $coach ) {
    // echo $coach->ID;
}


text:
Q: python3.5 import tensorflow.contrib error: Function has keyword-only arguments or annotations, use getfullargspec() API which can support them I am using python 3.5 and installed tensorflow-gpu 1.12.0 on Linux. When I run this in python3.5:
import tensorflow as tf

It works fine with no errors.
However, when I run:
import tensorflow.contrib

There is an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/__init__.py", line 49, in <module>
    from tensorflow.contrib import distributions
File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/distributions/__init__.py", line 38, in <module>
from tensorflow.contrib.distributions.python.ops.estimator import *
     File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/estimator.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/__init__.py", line 96, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/__init__.py", line 28, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/__init__.py", line 30, in <module>
    from tensorflow.contrib.learn.python.learn import estimators
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/__init__.py", line 302, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 35, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py", line 36, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import estimator
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 52, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io import data_feeder
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/__init__.py", line 26, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io.dask_io import extract_dask_data
  File "/home/myname/anaconda3/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py", line 33, in <module>
    import dask.dataframe as dd
  File "/home/myname/anaconda3/lib/python3.5/site-packages/dask/dataframe/__init__.py", line 1, in <module>
    from .core import (DataFrame, Series, Index, _Frame, map_partitions,
  File "/home/myname/anaconda3/lib/python3.5/site-packages/dask/dataframe/core.py", line 23, in <module>
    from .. import array as da
  File "/home/myname/anaconda3/lib/python3.5/site-packages/dask/array/__init__.py", line 4, in <module>
    from .core import (Array, stack, concatenate, take, tensordot, transpose,
  File "/home/myname/anaconda3/lib/python3.5/site-packages/dask/array/core.py", line 13, in <module>
    from toolz.curried import (pipe, partition, concat, unique, pluck, join, first,
  File "/home/myname/anaconda3/lib/python3.5/site-packages/toolz/curried/__init__.py", line 53, in <module>
    _curry_namespace(vars(toolz)),
  File "/home/myname/anaconda3/lib/python3.5/site-packages/toolz/curried/__init__.py", line 48, in _curry_namespace
    for name, f in ns.items() if '__' not in name
  File "/home/myname/anaconda3/lib/python3.5/site-packages/toolz/curried/__init__.py", line 48, in <genexpr>
    for name, f in ns.items() if '__' not in name
  File "/home/myname/anaconda3/lib/python3.5/site-packages/toolz/curried/__init__.py", line 42, in _should_curry
    return (callable(f) and _nargs(f) > 1 or f in do_curry)
  File "/home/myname/anaconda3/lib/python3.5/site-packages/toolz/curried/__init__.py", line 35, in _nargs
    return len(inspect.getargspec(f).args)
  File "/home/myname/anaconda3/lib/python3.5/inspect.py", line 1050, in getargspec
    raise ValueError("Function has keyword-only arguments or annotations"
ValueError: Function has keyword-only arguments or annotations, use getfullargspec() API which can support them

I searched for getfullargspec() API but got even more confused. As far as I know, the getfullargspec() API from inspect can only do with something like
getfullargsspec(function_name)

How can I do with it? I could appreciate it a lot if you could explain the cause and also possibly a simple solution.

Plus, I am running the code on a remote server without root permission. Command lines such as
sudo xxxxx
do not work for me.
Thank you for your help!

A: I also face this problem. I found this way to solve this problem.
conda install toolz

Good Luck


text:
Q: Don't insert inner objects in Entity Framework 5 I have a class:
public class Foo {
    public Guid Id { get; set; }
    public Bar Child { get; set; }
}

When I insert into Foo via context.Foos.Add(myFoo), a Bar is being inserted into the database if it is not null.
How can I prevent this from happening? Do I have to set Child to null prior to inserting into the context?


text:
Q: Deeper Explanation of Prolog Count Currently playing around in Prolog... I'm having trouble groking the count list rule. I haven't been able to find a good explanation anywhere. Can someone give me a break down of it at each recursion?
count(0, []).
count(Count, [Head|Tail]) :-
    count(TailCount, Tail),
    Count is TailCount + 1.

One place says that it is recursive (which makes sense to me) and another that says it isn't.

A: The procedure it's recursive, but not tail recursive. Writing tail recursive procedures is an optimization that allows the system to transform recursion into iteration, avoiding  useless stack usage for deterministics computations (like the one we are speaking of).
In this case (that BTW it's the same of the builtin length/2, just with arguments swapped), we can use an accumulator, and rewrite the procedure in this way:
count(C, L) :- count(0, C, L).

count(Total, Total, []).
count(SoFar, Count, [_Head|Tail]) :-
    Count1 is SoFar + 1,
    count(Count1, Count, Tail).

Some system older required a cut before the recursive call, to make the optimization effective:
    ...,
    !, count(Count1, Count, Tail).

A: The definition of the inference rule is recursive.
This program tries to count the quantity of elements inside the list.
count(0, []). This is an axiom, a fact, something that its true because you said so. Here you are stating that every empty list has a count of zero.
count(Count, [Head|Tail]) :-
    count(TailCount, Tail),
    Count is TailCount + 1.
This is an inference rule, that it a rule that dictates that the left part of :- is true if the right part is true. This inference rule also uses pattern matching, wicth matchs non empty lists ([Head|Tail]).
Specifically, the count rule says that the Count variable of a non empty list is the count of the Tail part of the list, plus 1 (the plus 1 is for counting the Head element of the list).


text:
Q: find $y''=x-x^{2}$ that solves also $y''=-\lambda y$ Given the orthonormal basis $\{\phi_n\}$ in $L^2$ that solves Sturm-Liouville eigenvalue problem
$y''=-\lambda y$ which also satisfies $y(0)=y(1)=0$ (1),
find the series expansion in this basis of the solution to:
$y''=x-x^{2}$.(2)
my idea:
I shall take the orthonormal basis that solves Sturm-Liouville in $L^2$.
This will be $\{\phi_n\}$, and I find a series that satisfies (2).
Meaning $y=\sum_{n\in\mathbb{Z}}\phi_{n}a_{n}$ represents a function that satisfies (2).
first I shall use the inner product of $L^2$:
$$
b_{n}=\langle x-x^{2},\sqrt{2}\sin(n\pi x)\rangle
=\int_{0}^{1}(x-x^{2})\sqrt{2}\sin(n\pi x)dx\\
=-\frac{\sqrt{2}(-2+2\cos(n\pi)+n\pi \sin(n\pi))}{n^{3}\pi^{3}}$$
thus
$$\Rightarrow b_{n}=\begin{cases}
\begin{array}{c}
n\in\mathbb{Z_{\textrm{even}}}\\
n\in\mathbb{Z_{\textrm{odd}}}
\end{array} & \begin{array}{c}
0\\
\frac{4\sqrt{2}}{n^{3}\pi^{3}}
\end{array}\end{cases}$$
now this solution also satisfies (1) as it's a linear combination of solution to (1).
Hence we've found a joint solution for both.
Am I correct?
Edit:
Hmm for a solution to be solution of 1 it must also have only be a square of integer. yet it might be still correct?

Edit:
$n^{2}\pi^{2}a_{n}=b_{n}\\\Rightarrow a_{n}=\begin{cases}
\begin{array}{c}
n\in\mathbb{Z_{\textrm{even}}}\\
n\in\mathbb{Z_{\textrm{od}}}
\end{array} & \begin{array}{c}
0\\
\frac{4\sqrt{2}}{n^{5}\pi^{5}}
\end{array}\end{cases}$

A: Expanding both sides of $y''=r(x)=x-x^2$ gives the equation
$$
-\sum\lambda_na_n\phi_n=\sum b_n\phi_n
\\
\implies a_n=-\frac{b_n}{\lambda_n}
$$
where
$$
b_n=\langle r(x),\phi_n(x)\rangle
$$
as you computed. This gives that the non-trivial coefficients are those with odd index $n$ and
$$
a_n=-\frac{4\sqrt2}{n^5\pi^5}
$$

Test: Direct integration and application of the boundary conditions $y(0)=y(1)=0$ gives as solution
$$
y(x)=-\frac{x}{12}(x^3-2x^2+1)
=-\frac{x(x-1)}{12}(x^2-x-1)
=-\frac{x(1-x)}{12}(1+x(1-x))
$$
Now computing the expansion coefficients gives
$$
a_n=⟨y(x),ϕ_n(x)⟩=-\frac{2\sqrt2(1-\cos(n\pi))}{n^5\pi^5}
$$
which confirms the solution.


text:
Q: spinner.onItemSelectedListener causes crash on rotation I have a spinner inside a fragment. Setting onItemSelectedListener in onViewCreated causes a crash after device rotation.
This is my code:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    myspinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            Log.d("debug", "onSelectItem")
        }
        override fun onNothingSelected(parent: AdapterView<*>?) {}
    }

    val adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOf(getString(R.string.mystring), getString(R.string.mystring1), getString(R.string.mystring2)))
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    myspinner.adapter = adapter
    myspinner.setSelection(Values.selectedIndex)
}

I receive the following errors:
 FATAL EXCEPTION: main
                  Process: myproject, PID: 12899
                  java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter view
                      at myproject.MyFragment$onViewCreated$1.onItemSelected(Unknown Source:45)
                      at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
                      at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
                      at android.widget.AdapterView.selectionChanged(AdapterView.java:922)
                      at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1105)
                      at android.widget.AdapterView.handleDataChanged(AdapterView.java:1081)
                      at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:191)
                      at android.widget.Spinner.onMeasure(Spinner.java:602)
                      at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:420)
                      at android.view.View.measure(View.java:23169)
                      at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1212)
                      at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1552)
                      at android.view.View.measure(View.java:23169)
                      at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1212)
                      at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1552)
                      at android.view.View.measure(View.java:23169)
                      at android.support.v4.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1450)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.support.v4.widget.NestedScrollView.onMeasure(NestedScrollView.java:516)
                      at android.view.View.measure(View.java:23169)
                      at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1632)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
                      at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                      at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                      at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
                      at android.view.View.measure(View.java:23169)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2719)
E/AndroidRuntime:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1572)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1856)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7184)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:761)
                      at android.view.Choreographer.doFrame(Choreographer.java:696)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
                      at android.os.Handler.handleCallback(Handler.java:873)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:193)
                      at android.app.ActivityThread.main(ActivityThread.java:6669)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

If I comment out onItemSelectedListener then it doesn't crash.


text:
Q: how to move user input array value to end of array and set it to 0? What I need, is make program where user type 10 integers in array and then type one more integer which need to replace with 0 and move to the end of final array.
Tried out everything what I can find in google, but didn't work still.
#include <iostream>
using namespace std;

int main ()
{
    int i, array[10], v;

cout << "Please enter 10 integer elements of an array!\n" << endl;
    for (int i = 0; i < 10; i++)
    {
        cout << "array[" << i << "]: ";
        cin >> array[i];
    }

    cout << endl;
cout << "Now, enter the integer, 'V': ";
    cin >> v;
    cout << endl;
cout << "The final array is:\n" << endl;

    for (int i = 0; i < 10; i++)
    {
        cout << "array[" << i << "]: " << array[i] << endl;
        if (array[i] == v)
        {
            v = 0;
        }
    }
    for (i = 0; i < 1; i++)
    cout << "array[" << array[8] << "]: " << v << endl;

This is how far I am done, almost finished, but don't know how to make it proper, to see in final only 10 array values, not 11, when user enter the same value of main array.
there is final result, how it should look like
Because I guess you will not understand anything what I need from this description, because my English is trash ;/

A: To replace the i:th value in the array with zero, you write array[i] = 0, not v = 0.
To copy the i:th element to the last position, you write array[9] = array[i].
Also, you should modify the array first and then print it, not print it as you go.

A: this is code for moving all equal elements in array, you can refer it
#include <iostream>
using namespace std;

int main ()
{
    const int N = 10;
    int array[N];
    int v;

    cout << "Please enter 10 integer elements of an array!\n" << endl;
    for (int i = 0; i < N; i++)
    {
        cout << "array[" << i << "]: ";
        cin >> array[i];
    }

    cout << endl;
    cout << "Now, enter the integer, 'V': ";
    cin >> v;
    cout << endl;
    cout << "The final array is:\n" << endl;

    int pos = 0;
    // move element which are not equal backward
    for (int i = 0; i < N; i++)
    {
        if (array[i] != v)
        {
            array[pos] = array[i];
            ++pos;
        }
    }
    // set value in remaining position to 0
    for ( ; pos < N; ++pos){
        array[pos] = 0;
    }

    // print output
    for (int i = 0; i < N; i++){
        cout << "array[" << i << "]: " << array[i] << endl;
    }

}

A: #include <iostream>
using namespace std;

int main () {

    const size_t MAX_SIZE = 10;
    size_t i = 0, array[MAX_SIZE], v;

    cout << "Please enter 10 integer elements of an array!\n" << endl;

    for (int i = 0; i < MAX_SIZE; i++) {
        cout << "array[" << i << "]: ";
        cin >> array[i];
    }

    cout << endl;
    cout << "Now, enter the integer, 'V': ";
    cin >> v;
    cout << endl;
    cout << "The final array is:\n" << endl;

    while (true)
    {
        if (i == MAX_SIZE) {
            break;
        }

        if (array[i] == v) {

            for (size_t j = i; j < MAX_SIZE - 1; j++) {
                array[j] = array[j + 1];
            }

            array[MAX_SIZE - 1] = 0;
            continue;
        }

        cout << "array[" << i << "]: " << array[i] << endl;

        i++;
    }

}

_
You can also do it with a for loop.
for (size_t i = 0; i < MAX_SIZE; /*EMPTY*/) {

    if (array[i] == v)
    {
        for (size_t j = i; j < MAX_SIZE - 1; j++) {
            array[j] = array[j + 1];
        }

        array[MAX_SIZE - 1] = 0;
        continue;
    }

    cout << "array[" << i << "]: " << array[i] << endl;

    i++;
}

_
Please enter 10 integer elements of an array!

array[0]: 1
array[1]: 1
array[2]: 1
array[3]: 2
array[4]: 1
array[5]: 1
array[6]: 1
array[7]: 1
array[8]: 1
array[9]: 1

Now, enter the integer, 'V': 1

The final array is:

array[0]: 2
array[1]: 0
array[2]: 0
array[3]: 0
array[4]: 0
array[5]: 0
array[6]: 0
array[7]: 0
array[8]: 0
array[9]: 0

_
Please enter 10 integer elements of an array!

array[0]: 1
array[1]: 1
array[2]: 1
array[3]: 2
array[4]: 1
array[5]: 1
array[6]: 1
array[7]: 1
array[8]: 1
array[9]: 1

Now, enter the integer, 'V': 2

The final array is:

array[0]: 1
array[1]: 1
array[2]: 1
array[3]: 1
array[4]: 1
array[5]: 1
array[6]: 1
array[7]: 1
array[8]: 1
array[9]: 0


text:
Q: GenStaticText on MS Windows: does it support markup? If I understand wxPython docs correctly, this part:

Currently wx.Button supports markup in all major ports (wxMSW, wxGTK and OSX/Cocoa) while wx.StaticText supports it in wxGTK and wxOSX and its generic version (which can be used under MSW if markup support is required). Extending support to more controls is planned in the future.

state that GenStaticText should support markup on MS Windows? Reading this thread also implies that?
My code does not reproduce that:
import wx
from wx.lib.stattext import GenStaticText

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(None, *args, **kwargs)
        self.Title = 'Example'

        self.panel = MainPanel(self)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.panel,1, wx.EXPAND)
        self.SetSizer(sizer)

        self.Center()
        self.Layout()
        self.Show()

class MainPanel(wx.Panel):
    def __init__(self, parent):
        super().__init__(parent)

        self.ST = GenStaticText(self, label='', style=wx.ALIGN_LEFT)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.ST,1,wx.EXPAND)

        self.ST.SetLabelMarkup("<b>Bold text</b>")

        self.SetSizer(sizer)

app = wx.App()
frame = MyFrame()
app.MainLoop()

Is there an error? Is there any way to get GenStaticText or wx.StaticText to support markup on MSW?

A: on wx.StaticText one can SetFont(font)


text:
Q: Concatenating date and time fields I have a table invoices with this fields:
invDate -> a date field
invTime -> a time field

I need to do querys like
SELECT top 10 * from invoices WHERE DATETIME(invDate+invTime)
BETWEEN DATETIME('2013-12-17 17:58') AND DATETIME()

or something like that. I don't know how to concatenate the invDate and invTime to create a datetime field. The only thing that i could do is this horribly thing:
DATETIME( YEAR(invDate), MONTH(invDate), DAY(invDate), 17, 52 ) AS MyDatetime

Couldn't even get hour and time with hour(invTime) and minute(invTime):
DATETIME( YEAR(invDate), MONTH(invDate), DAY(invDate),
HOUR(invTime), MINUTE(invTime) ) AS MyDatetime

I'm doing the querys throught the VFP Odbc Driver via PHP.

A: You were pretty close.  If the value coming from PHP is not of a date/time, how could VFP interpret it properly.  VFP also has a function CTOT()  (character to time), and expects it in the format of 'yyyy-mm-ddThh:MM:ss??'
yyyy = 4 digit year
mm = 1 OR 2 digit month
dd = 1 OR 2 digit day
T -- literally the letter "T"
hh = 1 OR 2 digit hour (but typical is 2 anyhow)
MM = 1 or 2 digit minute (but typical is 2)
ss = 1 or 2 digit for seconds -- not required
?? = "AM" or "PM" if you wanted to explicitly provide that vs 24 hour clock

The MM and ss are optional, so if you finished with "T1" would be 1:00:00am
Now, to finish your query.
WHERE DATETIME(invDate+invTime)
BETWEEN DATETIME('2013-12-17 17:58') AND DATETIME()

Since this appears to be querying all invoices between a given date/time and NOW (via DateTime()), you don't even need between, you can do
WHERE YourTable.Column > CTOT( '2013-12-17T17:58')

If you specifically DID have a date/time range to consider, THEN you could do something like
WHERE YourTable.Column BETWEEN CTOT( '2013-12-05T10:00') AND CTOT( '2013-12-14T11:58')

PROBLEMS WITH your DATE() and TIME() implementations
The problem is Date() is a function to either return current date, or create based on y/m/d provided such as date( 2013, 12, 7 ).  If you are passing a string, use CTOD( 'mm/dd/yyyy' ) such as CTOD( 12, 7, 2013 ).
As for the TIME() function that just expects a number and is of no use for you.  From the OleDbProvider, your best bet is to just create a php function that builds a single string in the CTOT() format I've described and pass to the php function the date and time fields.  Then use that as your "CTOT( functionReturnResult )"

A: To add a Date  and a Time Field together you will need to convert them both to a same datatype 1st and than just simply add them together something like this....
DECLARE @D DATE = '2013-12-17'
DECLARE @T TIME = '17:58:00'

SELECT CAST(@D AS DATETIME) + CAST(@T AS DATETIME)

Result
2013-12-17 17:58:00.000

Your Query
SELECT top 10 *
from invoices
WHERE CAST(invDate AS DATETIME) + CAST(invTime AS DATETIME)
BETWEEN '20131217 17:58:00.000' AND GETDATE()


text:
Q: Seeking shortcut to execute a Program with a supplied Local Path A program requires local path property to perform correctly.
I'm seeking shortcut command to execute a program with a supplied localPath
For example,
cd /usr/local/blogrmis
/usr/local/blogrmis/remote &

remote program requires local path @ /usr/local/blogrmis to run.
is there any shortcut which i can do it in 1 line?

A: If the program must be run with the current working directory set to the directory containing the program you can combine both commands on one line:
 cd /usr/local/blogrmis; ./remote &

To shorten this you can create an alias (one-off, or permanently in your shell's .profile file)
 alias blogrmis="(cd /usr/local/blogrmis; ./remote &)"

then you just type
 blogrmis

Or create and use a shell-function (see man bash)

A: Try this
cd /usr/local/blogrmis ; /usr/local/blogrmis/remote &


text:
Q: (Symfony 4) I Can access my RDS database fine outside Symfony (i.e. a program like HeidiSQL), but not from within Symfony Here is my .env file where you specify the credentials:
###> doctrine/doctrine-bundle ###
# Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://myusername:mypassword@rdsservername.ccjd7fkj4brb.us-east-1.rds.amazonaws.com:3306/databasename
###< doctrine/doctrine-bundle ###

It's weird because using the username/password/server/database name credentials I can connect via HeidiSQL no problem, but when I run it through Symfony I get the following message in the log file:
[2019-04-19 18:34:20] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\ConnectionException: "An exception occurred in driver: SQLSTATE[HY000] [1045] Access denied for user 'myusername'@'10.0.0.206' (using password: YES)" at /var/www/vhosts/mywebsite.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 93 {"exception":"[object] (Doctrine\\DBAL\\Exception\\ConnectionException(code: 0): An exception occurred in driver: SQLSTATE[HY000]

[1045] Access denied for user 'myusername'@'10.0.0.206' (using password: YES) at /var/www/vhosts/mywebsite.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:93, Doctrine\\DBAL\\Driver\\PDOException(code: 1045): SQLSTATE[HY000] [1045] Access denied for user 'myusername'@'10.0.0.206' (using password: YES) at /var/www/vhosts/mywebsite.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 1045): SQLSTATE[HY000] [1045] Access denied for user 'myusername'@'10.0.0.206' (using password: YES) at /var/www/vhosts/mywebsite.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)"} []

Would anyone know why the same credentials would work perfectly fine when I connect to the RDS server from home using a program like Heidi, but they won't work from within Symfony on my EC2 server?


text:
Q: I am having formatting issues I want my program to format nicely like
But, it formats like:
I have two classes, one of them is the getter one (Item), and the majority of the code will be in this one (TestItem)
This is the toString method in the getter file
    public String toString()
    {
        return " " + itemID + "\t" + itemName + "\t" + inStore + "\t" +  "$"  +     df.format(Price);//String.format("$%,1.2f", Price) +"\n" ;
    }

And in TestMovie, Thses are the important methods:
   public static void main (String [] args)
   {
       Item[] hardware = new Item[6];

      hardware[0]=new Item(1011,"Air Filters",200,10.5);
      hardware[1]=new Item(1034,"Door Knobs",60,21.5);
      hardware[2]=new Item(1101,"Hammers",90,9.99);
      hardware[3]=new Item(1600,"Levels",80,19.99);
       hardware[4]=new Item(1500,"Ceiling Fans",100,59);
       hardware[5]=new Item(1201,"Wrench Sets",55,80);

       System.out.println("Original Array:");
      System.out.println();
      printInventory(hardware);
      System.out.println();

and this method traverses through the array
     public static void printInventory(Item[] hardware) //traverse and print
   {
       System.out.printf("itemID\titemName\tinStore\tprice\n");

  System.out.println("--------------------------------------------------------");
        for(Item print : hardware)
       {
            for (int i = 0; i < 1; i++)
            {
               //System.out.println(hardware[i]);
              System.out.printf(print.getItemID() + "\t" + print.getItemName() + "\t" + print.getInStore() + "\t$" + print.getPrice()); //format
           }
           System.out.println();
       }
      }

The program runs without errors, It's just not formatted the way i would like it to be. I need implementing the printf function in my program. I'm more worried about the items, than the header.

A: As already proposed use printf() with format pattern instead of TAB characters. Then your printInventory() could look like
public static void printInventory(Item[] hardware) {
    System.out.printf("%-10s  %-20s  %-10s  %-10s%n",
            "itemID",
            "itemName",
            "inStore",
            "price"
    );

    System.out.println("--------------------------------------------------------");

    for (Item print : hardware) {
        System.out.printf("%-10s  %-20s  %-10s  $%,.2f%n",
                print.getItemID(),
                print.getItemName(),
                print.getInStore(),
                print.getPrice()
        );
    }
}

Some fine tuning is needed. But you should already get the big picture.

A: In your first line
System.out.println("itemID       itemName        inStore      price      ");

You have also to use printf with tabulations and no space to get same indentation.

A: Adding tabs to your header:
System.out.printf("itemID\titemName\tinStore\tprice\t");

Will help get the first column in order. Your second problem is the length of the text in the title column which pushes your formatting out. A quick fix would be to add more tabs. But this may not work with short or longer titles.
As mentioned it is best to use the Formatter class


text:
Q: How to link to a page and have a specific tab active with rails If an info page has multiple tabs based on different topics and there are links leading to the info page from different pages, how do you link to the info page with an active tab depending on the link used?
I want to have a link like this:

View the terms & conditions on our info page <%= link_to "here", info_path %>, thanks.

Lead to my info page with the Terms tab active like this:

Terms

These are the terms.

I was wondering how to change the "active" status based on the link from a different page on my site. Does the active status need to be changed on the specific tabpanel instead? Thank you!
This is the tab section from the info page:

      About

      Advertise

      Legal

      Privacy

      Terms

About

This is the about tab using a div to indent lines

Advertise

Legal

Privacy

Terms

A: You can pass params on link_to method. Something like:
link_to "here", info_path(active_tab: "your_active_tab_name")

So, in your info page view, you can try to retrive it from params[:active_tab], so you can set your active attribute based on that value.
Hope this helps, good luck
EDIT:
If you're using bootstrap tabs (https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp), you can set some tab as active by adding the active class to the "li" element, like this:

      Advertise

So, wherever you put a link to that info page, you should pass a param that indicates which tab will be active, something like this:
link_to "more info", info_path(active_tab: "advertise")

Then, on your info page, you check the params[:active_tab] to determine which tab will be active. Something like:

      About

      Advertise

   ... and so it goes on

Hope this makes it clear! Also, has to test it, but think this works

A: I've tried with a bit of Javascript.
Add an identifier to your li element inside the ul.nav.nav-tabs, this way it could be easily reached with the params sent, like:

  ...

Then, the same for your div tag with role="tabpanel", like:

  ...

Then in the previouse view, you can add a link_to helper, passing the tab you want to make active, like:

  View the terms & conditions on our info page
  <%= link_to 'here', root_path(tab: 'terms') %>, thanks.

Then in the view where are the tabs, add an script which take the params[:tab] and check if they're sent or not, if so then get your li and div elements, remove the class active from the first li and add active to the new elements:

Make sure the id terms-tab and all the identifiers for each div with role tabpanel are equal to the href attributes in their anchor tags.
You can see here a working demo.

A: Posting my solution here in case someone needs it.
I wanted to have a default option in case there was no parameter. I am using Bootstrap's Navs.
# Passing a params on 'link_to' method

# View with links

<%= link_to "Tab Index", tabs_path %>
<%= link_to "Tab 1", tabs_path(tab: 'tab_1') %>
<%= link_to "Tab 2", tabs_path(tab: 'tab_2') %>
<%= link_to "Tab 3", tabs_path(tab: 'tab_3') %>

# Adding 'active' class to navs based on params

# View with tabs

<%# Tabs %>

    <a href="#tab_index" data-toggle="tab" role="tab" class="nav-link <%= "active" unless params.has_key?(:tab) %>">Tab Index

    <a href="#tab_1" data-toggle="tab" role="tab" class="nav-link <%= "active" if params[:tab] == "tab_1" %>">Tab 1

    <a href="#tab_2" data-toggle="tab" role="tab" class="nav-link <%= "active" if params[:tab] == "tab_2" %>">Tab 2

    <a href="#tab_3" data-toggle="tab" role="tab" class="nav-link <%= "active" if params[:tab] == "tab_3" %>">Tab 3

<%# Tab content %>

  <div class="tab-pane <%= "active" unless params.has_key?(:tab) %>" id="tab_index">Tab Index Content

  <div class="tab-pane <%= "active" if params[:tab] == "tab_1" %>" id="tab_1">Tab 1 Content

  <div class="tab-pane <%= "active" if params[:tab] == "tab_2" %>" id="tab_2">Tab 2 Content

  <div class="tab-pane <%= "active" if params[:tab] == "tab_3" %>" id="tab_3">Tab 3 Content


text:
Q: What does the "Q" in "Clock-to-Q delay" stand for?
Possible Duplicate:
Why is the output of stateful elements often named Q?

A register has D (data) as input and Q as output.
What does the Q stand for? I'm having a hard time searching for it.

A: Q represents the output of a flip-flop or register. For an edge-triggerred flip-flop, the clock-to-Q time is the time it takes for the register output to be in a stable state after a clock edge occurs.


text:
Q: Maximum number if the GCD is known if it is known that the GCD(a,2008) = 251, and a<4036 whats  the biggest number for a?
a. 3263
b. 4016
c. 2259
d. 3765
e. 3514
i know that the answer is d, after a long math. but does anybody have any other ways to do it?

A: Well, you know it is a multiple of $251$.
$4036 = 16*251+20$ so $a$ is at most $256*16$.
So $a = 251*b$ where $b \le 16$.
$2008 = 8*251$.  So $b$ and $8$ can not have any factors in common so $b \ne 16$.  (Note: $\gcd(2008, 251*16) = 2008$)
If $b=15$ then $b$ and $8$ don't have any factors in common.  ANd if we test it:  $\gcd(15*251, 2008)= \gcd(15*251, 8*251) = 251$.
So that's it.  $a = 15*251 = 3765$

A: Since $2008 = 8 \times 251$ you are looking for a multiple of $251$ which has no factor (other than $1$) in common with $8$ - so it can't be even. [$251$ has to be a factor of $2008$ for the question to make sense]
You are therefore looking for the highest odd multiple of $251$ less than $4036$.
Well $4016=251 \times 16$ (twice what you started with, so nice and easy to work with) so you are looking for $251\times 15$


text:
Q: How to have class loaded without using "use" but call it as if I used it I have studied these 2 sources, but none of those works for me.
http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html
Yii2 - How do I AutoLoad a custom class?
I have created custom helper class which I want to include in every model, controller and view in my application. I am using Yii2 advanced app version 2.0.11, IDE I am using is PHPStorm
QUESTION:
What I want to achieve is to not use use keyword at the beggining of every class but still be able to simply call AppHelper::myMethod() in models, controllers and views.
How is that possible?
Closest I got it working was using this solution https://stackoverflow.com/a/35160997/5395463
All other solutions did not work for me. I am getting errors like:
PHP Fatal Error – yii\base\ErrorException
Class 'frontend\controllers\AppHelper' not found

when I simply dont include  use commons\commands\AppHelper;
or when not using namespace as they suggest there with other settings:
Fatal error: Uncaught exception 'yii\base\UnknownClassException'
with message 'Unable to find 'common\commands\AppHelper'
in file: C:\xampp\htdocs\domain.com\web\common/commands/AppHelper.php.
 Namespace missing?' in ...

SOLUTION:
Thanks for your responses, I got it working finaly. https://stackoverflow.com/a/42330631/5395463 solution works best for me.
So I removed namespace from that class, but left it in common\commands folder, added require to frontend/web/index.php and backend/web/index.php files (not sure if I should add it to yii file in root too, I didnt, so far it is working good anyways), and changed calls of class from AppHelper::myMethod() to \AppHelper::myMethod() looks like eveything is working now.

A: In Yii2  You can  use an explicit way    adding \  to full namespaced  name
 \frontend\controllers\AppHelper

so you can sue your method
 \frontend\controllers\AppHelper::yourMethod();

A: Solution for not lazy coders:

*

*create component with your class so you can use it like \Yii::$app->my_component

*if even this is too much and your IDE is better than Windows Notepad prepare macro that will print this for you

Solution for lazy coders:

*

*Save your class in single PHP file without namespace.

*Modify you entry script to include this class - i.e. for Basic Project Template it's /web/index.php; add there
require(__DIR__ . '/path/to/MyClass.php');

For Advanced Project Template modify it properly.

*Now you can use your class by calling it like \MyClass (yes, \ is required and yes, your IDE probably will modify it anyway to MyClass with use MyClass; added at the beginning.


text:
Q: xsl:for-each select does not work with xmlns="http://www.example.com/TBD" inside XML I need some help with my XSLT-2.0 code.
This is XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:param name="today" select="format-dateTime(current-dateTime(), '[Y0001]-[M01]-[D01]T[H1]:[m01]:[s01]')"/>
        <document>
            <xsl:for-each select="//Product">
                <Product>
                    <Productdetail>
                        <DocumentID>
                            <xsl:value-of select="./ProductNr"/>
                        </DocumentID>
                        <DocumentProd>
                            <xsl:value-of select=".//Account/DebitNr"/>
                        </DocumentProd>
                        <Date>
                            <xsl:value-of select="$today"/>
                        </Date>
                    </Productdetail>
                </Product>
            </xsl:for-each>
        </document>
    </xsl:template>
</xsl:stylesheet>

Here is xml
<?xml version="1.0" encoding="UTF-8"?>
<Products refSchemaFile="V11.xsd" xmlns="http://www.example.com/TBD">
    <Product>
        <Nr/>
        <ProductNr>837228</ProductNr>
        <Account>
            <Nr/>
            <DebitNr>21549</DebitNr>
        </Account>
    </Product>
    <Product>
        <Nr/>
        <ProductNr>837227</ProductNr>
        <Account>
            <Nr/>
            <DebitNr>21547</DebitNr>
        </Account>
    </Product>
    <Product>
        <Nr/>
        <ProductNr>837226</ProductNr>
        <Account>
            <Nr/>
            <DebitNr>21544</DebitNr>
        </Account>
    </Product>
</Products>

This is XSLT Result
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xs="http://www.w3.org/2001/XMLSchema"/>

But if I delete xmlns="http://www.example.com/TBD" from XML, then I am getting:
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <Product>
        <Productdetail>
            <DocumentID>837228</DocumentID>
            <DocumentProd>21549</DocumentProd>
            <Date>2021-02-21T22:40:18</Date>
        </Productdetail>
    </Product>
    <Product>
        <Productdetail>
            <DocumentID>837227</DocumentID>
            <DocumentProd>21547</DocumentProd>
            <Date>2021-02-21T22:40:18</Date>
        </Productdetail>
    </Product>
    <Product>
        <Productdetail>
            <DocumentID>837226</DocumentID>
            <DocumentProd>21544</DocumentProd>
            <Date>2021-02-21T22:40:18</Date>
        </Productdetail>
    </Product>
</document>

Why is xmlns="http://www.example.com/TBD" a problem, and what do I have to do to create a result with xmlns="http://www.example.com/TBD" inside the XML?

A: The xmlns=".." directive in the XML sets the namespace for this element and all of its children. Namespaces are often realized using a prefix on the element's name, like xmlns:fn="http://www.w3.org/2005/xpath-functions". To use an element in this namespace, you have to use <fn:funcXY>, for example.
In your case, adding the following attribute to the xsl:stylesheet element of your XSLT will be sufficient:
xpath-default-namespace="http://www.example.com/TBD"

It sets the namespace for all XPath expressions that do not explicitly specify another namespace with the first method. Therefore the expressions will match without setting a prefix on all of your matching expressions.
You can read more about namespaces here at this link, for example.


text:
Q: Android Emulator still showing Hello World So I've set up my Eclipse to have the Android SDK and ADT plugin.
I set up my AVD to have a Galaxy Nexus and Galaxy S2 emulator.
I've created a new Android project and I get my blank MainActivity which simply displays "Hello World!" which is the problem.
In the Graphical Layout, I delete the "Hello World!" text to remove it. I check in the activity_main.xml and the script containing the "Hello World!" text is no longer there. I run in either emulator and everything works, but when the app opens, "Hello World!" is still there.
Here's the xml now
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.project.MainActivity"
tools:ignore="MergeRootFrame" />

I've changed nothing except removing that text. The MainActivity.java has not been touched. Is there something I'm missing?

A: This was a little bit odd when it happened to me, just remove the Hello World Text View from the fragment.xml file and it should be fine.

A: that xml code is just for layout when you add smthg on layout this code will be bigger,example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 <Button
        android:id="@+id/bb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="72dp"
        android:text="git" />

thats have only a button
your code has nothing only layout


text:
Q: numpy meshgrid resizing of test data I have a test dataset with a shape of (100, 49280)
I am trying to plot the data from an svm classification, based on the example in http://scikit-learn.org/0.18/auto_examples/classification/plot_classifier_comparison.html like so:
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

So I print x_min, x_max, h, y_min, y_max:
-0.6541590243577957
7.5925517082214355
0.02
-0.9953588843345642
4.58396577835083
so far so good, according to what I have found in the docs I expect to get a mesh array with these values.
just to check I print xx and yy and get:
(279, 413)
(279, 413)

which seems fishy. and when I get to the line:
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])

I get the error: ValueError: X.shape[1] = 2 should be equal to 49280, the number of features at training time
I have never used numpy's meshgrid function but everything I have read in the docs seems normal and well documented as most of numpy is. I am sure that I am missing something silly but for the life of me I can't find it. Does anyone have an idea of where I went wrong? I will try to make a more informative title for the question once I figure out what the problem is too.

A: The np.arange function does not fit to this scenario. You probably want to use np.linspace as follows
xx, yy = np.meshgrid(np.linspace(x_min, x_max), np.linspace(y_min, y_max))

The docpage for np.linspace
https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html


text:
Q: I am trying to get multi option search but I always get empty array here I am trying to make a multi-option search and only the first required and the rest are optional but it never works correctly and that is the last thing I reached
$search = ads::where('title','LIKE',"%".$keyword."%")
                    ->when($category != 0,function ($query,$category){return $query->where('category_id', $category);})
                    ->when($sub_category != 0,function ($query,$sub_category){return $query->where('sub_category_id', $sub_category);})
                    ->when($governorate != 0,function ($query,$governorate){return $query->where('governorates_id', $governorate);})
                    ->when($city != 0,function ($query,$city){return $query->where('cities_id', $city);})
                    ->when($from_year != 0,function ($query,$from_year){return $query->where('year','>=', $from_year);})
                    ->when($to_year != 0,function ($query,$to_year){return $query->where('year','<=', $to_year);})
                    ->when($min_price > 0,function ($query,$min_price){return $query->where('price','>=', $min_price);})
                    ->when($max_price > 0,function ($query,$max_price){return $query->where('price','<=', $max_price);})
                    ->when($brand != 0,function ($query,$brand){return $query->where('brand', $brand);})
                    ->when($model != 0,function ($query,$model){return $query->where('model', $model);})
                    ->when($condition != 0,function ($query,$condition){return $query->where('condition1', $condition);})
                    ->when($engine != 0,function ($query,$engine){return $query->where('engine', $engine);})
                    ->when($body_type != 0,function ($query,$body_type){return $query->where('model', $body_type);})
                    ->when($transmition != 0,function ($query,$transmition){return $query->where('transmition', $transmition);})
                    ->when($fuel != 0,function ($query,$fuel){return $query->where('fuel', $fuel);})
                    ->when($real_estate_type != 0,function ($query,$real_estate_type){return $query->where('real_estate_type', $real_estate_type);})
                    ->when($space > 0,function ($query,$space){return $query->where('space', $space);})
                    ->when($floor != 0,function ($query,$floor){return $query->where('floor', $floor);})
                    ->when($furnished != 0,function ($query,$furnished){return $query->where('furnished', $furnished);})
                    ->where('approval','Approved')->get();

I always get an empty array as a result []


text:
Q: Chi square test between samples with very different size I am to estimate the chi square between two samples of size N and M, where in general N << M (e.g. N=100,000  M=10,000,000). In turn, this affects the uncertainty of each sample. I wonder if there is a way to take this difference into account to quantify the agreement so that one can show that a good chi2/dof with N small can correspond to a large chi2/dof when N ~ M just by e.g. a statistical fluctuation.
Cheers,
Riccardo

A: Suppose you are comparing two dice to see if they have the same probabilities
of showing faces 1 through 6.
Suppose Die A is biased so that face 6 is more likely than face 1, specifically the probabilities of the six faces are given by $p_a = (1,2,2,2,2,3)/12.$
And Die B is a fair die.
If you roll Die A $m = 10,000,000$ times and you roll Die B $n = 100,000$ times, then you might get a table such as MAT below, where rows are
counts for the two dice and columns are faces 1 through 6. We use R to simulate the counts.
p.a = c(1,2,2,2,2,3)/12;  a = sample(1:6, 10^7, repl=T, prob=p.a)
b = sample(1:6, 10^5, repl=T);  # fair die
tab.a = tabulate(a)
tab.b = tabulate(b)
MAT = rbind(tab.a, tab.b);  MAT
        [,1]    [,2]    [,3]    [,4]    [,5]    [,6]
tab.a 834537 1668374 1667463 1666285 1664984 2498357
tab.b  16884   16479   16819   16791   16297   16730

Not surprisingly, a chi-squared test detects that the two dice are
not 'homogeneous' as to face probabilities. The P-value is very nearly $0,$
so the null hypothesis is overwhelmingly rejected at the 5% level.
When the data argument of the R procedure chisq.test is a matrix, the procedure performs a test of homogeneity on the counts in the matrix.
chisq.test(MAT)

        Pearson's Chi-squared test

data:  MAT
X-squared = 11284, df = 5, p-value < 2.2e-16

However, if we know the biased probabilities of Die A, the test above is almost
the same as a goodness of fit test for the data from Die B to the
probabilities in $p_a.$
When the data argument of the R procedure chisq.test is a vector of counts and a separate vector of probabilities is given, the procedure performs a test of goodness-of-fit of the data vector to the probability vector.
chisq.test(tab.b, p=p.a)

        Chi-squared test for given probabilities

data:  tab.b
X-squared = 11522, df = 5, p-value < 2.2e-16

The two chi-squared statistics, while arising from different formulas,
are very nearly the same, and the degrees of freedom are the same, so
the P-value is very nearly the same.
More broadly, in many kinds of two-sample tests where the sample sizes are grossly
unequal, it is as if the larger sample becomes (almost) a fixed standard,
and the smaller sample is judged against that standard.
For example, if we are trying to find the smaller sample size necessary to achieve a given power, when the larger sample is huge, then the power depends almost entirely on the smaller sample size.

A: You are correct that even if both of your sample sets are drawn from the exact same population, the larger sample size will have a more significant p-value for whatever your comparison happens to be. What you can compare, however, is the effect size, which you can measure using an odds ratio (OR). The OR between your large and small samples should be the same within sampling error, although your larger sample will have a smaller confidence around the OR estimate and hence the smaller p-value. You could do a hypothesis test comparing the OR from your large and small sample sets, and if there's no significant difference between them, then you've shown that the effect size is equivalent in both, even though you have a smaller p-value for the larger sample set.


text:
Q: I have an error with my return statements that I don't know to fix In a text adventure game that I am making, all the different places are run my different functions. In my diner, market, and supply store, I have a switch statement that takes numbers 1-10. All 1-9 work, but 10 doesn't. All of these methods return back to a method called TownCenter(), but on these 3, when I do return, you have to spam it in order for it to work. Here is a code example:
void Diner(){
    int answer;
    cout << "Blah, blah. Type '0' to go back to town.\n";
    cin >> answer;
    switch (answer){
         case 0:
         return;
         break;
    }
    Diner()
}

Every time you type 0, it would just go to Diner() again. It eventually works if you spam 0 over and over, but why won't it work all the time?

A: I don't think there is any error with the code, except for the following considerations:

*

*Missing semicolon after Diner() in line 10.

*The break; statement is not required as return; is being used before it.

A: I don't think you mean to use recursion here. I would suggest using while loops while people are in individual locations. By calling the same location again at the end of your case statement to go back to the same area, you are going deeper in the callstack, requiring more "exits" to "leave" the room.
A do-while loop like the following would work nicely:
int answer;
do {
    cout << "Blah, blah. Type '0' to go back to town.\n";
    cin >> answer;
    switch (answer){
         // other case statements
         case 0:
             break;
    }
} while (answer != 0);

Notice I don't call Diner() again at the end. Getting it to process the same room until the "leave" is accomplished by the loop instead of unnecessary recursion.


text:
Q: Error providing image from another site Basically what I want to do is have a section on my site, where you provide the username of a user, example: NOTCH
Where it then goes to the minecraft host and finds the user's skin. "Skin Stealer" if you like.
However I'm getting an error and have no idea how to get around it..
<?php
if ($_GET['user'])
{
$user = $_GET['user'];

if(trim($user) == '')
{
    die('No username entered!');
}

$user = preg_replace('/\s+/', '', $user);

header('Content-Type: image/png');
$picture = '';
$getpicture = file_get_contents("$picture");
echo $picture
}
?>

The HTML is just a basic form which reads the php page called 'mcskin.php'

A: If using file_get_contens you just need the url:
$picture = "http://s3.amazonaws.com/MinecraftSkins/$user.png";

Also change
$getpicture = file_get_contents("$picture");

to
$getpicture = file_get_contents($picture);

A: You don't use the right quotes:
$picture = "";

And in this line quotes are not needed:
$getpicture = file_get_contents($picture);

Also you are aplying file_get_contents() to the img tag which make no sense. Pass it the URL:
$pictureUrl = "http://s3.amazonaws.com/MinecraftSkins/$user.png";
$getpicture = file_get_contents($pictureUrl);


text:
Q: maven/apt generated classes in eclipse Using following configuration in master pom, some classes (metamodel FYI) are generated for all child projects having jpa entities under target/generated-sources, as expected.
        <plugin>
            <groupId>org.bsc.maven</groupId>
            <artifactId>maven-processor-plugin</artifactId>
            <version>2.2.4</version>
            <dependencies>
                <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-jpamodelgen</artifactId>
                    <version>4.3.10.Final</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <id>process</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>
                        <processors>
                            <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                        </processors>
                    </configuration>
                </execution>
            </executions>
        </plugin>

This works perfectly from Maven and Netbeans.
Some team members still use Eclipse. There, generated classes aren't found automatically. They can be opened if added manually to the "build path" (whatever it means as this is redundant to pom.xml). However, that's not stable and will be reset whenever they "update the project" (shouldn't even be needed but...) to reflect project's maven configuration.
My question is, how to configure Eclipse to use this project's configuration automatically? I don't want to change the project's pom.xml too much, as they are perfectly legal and work well outside of Eclipse, which I just want to be taught to behave correctly.
UPDATE: M2Eclipse is installed and doesn't solve this, which is basically our problem.

A: There ist a project/Eclipse-Plugin called M2Eclipse (link).
The plugin includes the following feature:

Dependency management for Eclipse build path based on Maven's pom.xml


text:
Q: How to have an interface over 2 .net projects using 2 different versions of a dll I have inherited a vb.net app that is a few years old now and have to update it to send orders to 2 versions of a 3rd party system.

*

*Project A (existing) uses 3rd party dll in .net framework 3.5.

*Project B (new clone of A) uses a newer version of 3rd party dll in .net 4.7.

*Project Main (new) references Projects A & B plus 3 other projects in the solution; Entities, DataAccess & Core.
Project Main has a SendTo function that either sends to the Project A or Project B SendTo function.

*Project Core (new) References Entities & Data Access projects as well as the new 3rd party dll.
It has an interface:
Imports Entities
Public Interface IOrderService
Function SendTo(...) as Order
End Interface

which references the Entities project (.net 4.7)
And another interface:
Public Interface IClientSessionProvider
Function LogonService() as LogonService
...
End Interface

etc. which references the new 3rd party dll.
If I try and use the new .dll in Project A & make that .net framework 4.7 I get an 'Error in Application' error when using one of the .dll functions.  This function works perfectly in Project B (which uses the new .dll).
How can I best organise the code so that Project A remains 3.5, everything else remains 4.7 & my solution can talk to both .dll's as required?
Is it possible to keep my interface so the code can still call the method in Project A or B as necessary, or is there another way to solve this?

A: I managed to get both dll's working by using Assembly.LoadFrom, here is an excerpt from my code:
Dim params() As Object = New Object() {configuration, orderSaverService}

Dim assembly As Assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "\\<dll name here>.dll")
Dim myType As Type = assembly.GetType("<dll name + namespace here>", True)
objOrder = System.Activator.CreateInstance(myType, params)
appDomainOrder = AppDomain.CreateDomain()
iexecute = DirectCast(objOrder, IExecute)

where IExecute is my new interface which I implement in both Projects A & B.


text:
Q: interrogate a Ruby array of hashes I need to group people by age in Ruby. I have their date of birth, and a method which returns their age in years. So a solution like this works.
case
when (0..15).cover?(age_years)
  'child'
when (16..24).cover?(age_years)
  '16 to 24'
when (25..34).cover?(age_years)
  '25 to 34'
when (35..44).cover?(age_years)
  '35 to 44'
when (45..54).cover?(age_years)
  '45 to 54'
when (55..64).cover?(age_years)
  '55 to 64'
when age_years > 64
  'really old'
else
  'unknown'
end

However, I am trying to learn Ruby and am looking for a more elegant solution. I thought about putting the age_ranges into an array of hashes like this...
age_ranges = [{ name: 'child', min_age: 0, max_age: 15 },
              { name: '16 to 24', min_age: 16, max_age: 24 }]

but am at a loss as to how to interrogate this data to return the correct name where the age_years is within the appropriate ranges, or even a range like this
age_ranges = [{ name: 'child', age_range: '0..15' },
              { name: '16 to 24', age_range: '16..24' }]

which looks neater but I have no idea if I have written gibberish as I don't know how to extract the name when the age years matches.
Can someone point me in the right direction?

A: Now that you have an map of age names and ranges (note I used range, not string as a value of age_range), you want to search the age_ranges array of hashes for such, which value of age_range includes the age:
def age_ranges
  [
    { name: 'child',    age_range: 0..15 },
    { name: '16 to 24', age_range: 16..24 }
  ]
end

def find_age(age)
  age_ranges.find { |hash| hash[:age_range].include?(age) }[:name]
end

find_age(12)
#=> "child"
find_age(17)
#=> "16 to 24"

Note, that [:name] will fail if find returns nil (meaning, no matches found).
To overcome it either add an infinite range as a last one in the array (I'd prefer this one, because it is simpler):
def age_ranges
  [
    { name: 'child',    age_range: 0..15 },
    { name: '16 to 24', age_range: 16..24 },
    { name: 'unknown',  age_range: 25..Float::INFINITY }
  ]
end

Or handle it while fetching the age in the find_age method:
def find_age(age)
  age_ranges.each_with_object('unknown') { |hash, _| break hash[:name] if hash[:age_range].include?(age) }
end

Also, make sure to handle the negative numbers passed to the method (since age_ranges do not cover negatives):
def find_age(age)
  return 'Age can not be less than 0' if age.negative?
  age_ranges.find { |hash| hash[:age_range].include?(age) }[:name]
end

P.S. After all these "note/make sure" I want to say that @mudasobwa's answer is the simplest way to go about it :)

A: Use Range#=== triple equal directly, as it is supposed to be used:
case age_years
when 0..15 then 'child'
when 16..24 then '16 to 24'
when 25..34 then '25 to 34'
when 35..44 then '35 to 44'
when 45..54 then '45 to 54'
when 55..64 then '55 to 64'
when 64..Float::INFINITY then 'really old' # or when 64.method(:<).to_proc
else 'unknown'
end

To make case to accept floats, one should use triple-dot ranges:
case age_years
when 0...16 then 'child'
when 16...25 then '16 to 24'
when 25...35 then '25 to 34'
when 35...45 then '35 to 44'
when 45...55 then '45 to 54'
when 55...64 then '55 to 64'
when 64..Float::INFINITY then 'really old' # or when 64.method(:<).to_proc
else 'unknown'
end

A: Here's how I'd do it, to avoid code repetition between 16 and 64 :
def age_range(age, offset=4, span=10, lowest_age=16)
  i    = ((age-offset-1)/span).to_i
  min  = [i*span+offset+1, lowest_age].max
  max  = (i+1)*span + offset
  "#{min} to #{max}"
end

def age_description(age)
  case age
    when 0...16 then 'child'
    when 16..64 then age_range(age)
    when 64..999 then 'really old'
    else 'unknown'
  end
end

(0..99).each do |age|
  puts "%s (%s)" % [age_description(age), age]
end

It outputs :
child (0)
child (1)
child (2)
child (3)
child (4)
child (5)
child (6)
child (7)
child (8)
child (9)
child (10)
child (11)
child (12)
child (13)
child (14)
child (15)
16 to 24 (16)
16 to 24 (17)
16 to 24 (18)
16 to 24 (19)
16 to 24 (20)
16 to 24 (21)
16 to 24 (22)
16 to 24 (23)
16 to 24 (24)
25 to 34 (25)
25 to 34 (26)
25 to 34 (27)
25 to 34 (28)
25 to 34 (29)
25 to 34 (30)
25 to 34 (31)
25 to 34 (32)
25 to 34 (33)
25 to 34 (34)
35 to 44 (35)
...

As a bonus, it also works with Floats (e.g. 15.9 and 16.0).