text:
Q: ASP.NET - Ternary Operator not working properly? I would want to have a changing Enrollment Status depending on the existence of a record. However, my current syntax is not functioning properly. I have a record that is supposed to show "Unenrolled" as a status but it does not. It only goes to the "Not Enrolled" status.
Additional info: I tried reshuffling the ternary operators and it only works on whatever is the first and ignores the conditions in between. Like in my code below it will only apply "Enrolled" status correctly and the rest will only be "Not Enrolled" completely ignoring the other 2 conditions.
Here is the method:
    // GET: Enrollment
    public ActionResult Enrollment()
    {
        //Query for Children
        var children = from x in db.child_t
                       select new ViewModels.ChildViewModel
                       {
                           child_id = x.child_id,
                           last_name = x.last_name,
                           first_name = x.first_name,
                           middle_name = x.middle_name,
                           ext_name = x.ext_name,
                           sex = x.sex,
                           birthdate = x.birthdate,
                           sibling_status = ((from s in db.sibling_t where (s.child_id == x.child_id) select s).Count() > 0),
                           child_survey_status = ((from cs in db.child_survey_t where (cs.child_id == x.child_id) select cs).Count() > 0),
                           parent_status = ((from tp in db.tn_child_parent_t where (tp.child_id == x.child_id) select tp).Count() > 0),
                           home_status = ((from h in db.home_t where (h.child_id == x.child_id) select h).Count() > 0),
                           enrollment_status =
                            (

                              (from h in db.tn_enrollment_t
                                where (h.child_id == x.child_id && h.enrollment_date != null && h.unenrollment_date == null && h.completed_date == null)
                                orderby h.enrollment_date descending
                                select h).FirstOrDefault() != null ? "Enrolled" :

                              (from h in db.tn_enrollment_t
                               where (h.child_id == x.child_id && h.enrollment_date != null && h.unenrollment_date != null && h.completed_date == null)
                               orderby h.enrollment_date descending
                               select h).FirstOrDefault() != null ? "Unenrolled" :

                              (from h in db.tn_enrollment_t
                               where (h.child_id == x.child_id && h.enrollment_date != null && h.unenrollment_date == null && h.completed_date != null)
                               orderby h.enrollment_date descending
                               select h).FirstOrDefault() != null ? "Completed" :

                               "Not Enrolled"
                            ),
                           program_id =
                            ((from p in db.tn_enrollment_t
                                where (p.child_id == x.child_id)
                                orderby p.enrollment_date descending
                                select p.program_id).FirstOrDefault())
                       };

        return View(children.ToList());

    }

The first record in the image below should be the one with "Unenrolled" status already.

To make things clear here's the condition for my Enrollment Status:


text:
Q: These 2 function definitions have different behavior Can someone explain why these 2 functions behave differently.
Snippet 1:
function operate1(operator) {
  return function(x, y) {
    return x + operator + y;
  }
}

Snippet 2:
function operate2(operator) {
  return new Function("x", "y", "return x " + operator + " y;");
}

Usage:
adder1 = operate1("+");
adder2 = operate2("+");

adder1(5, 3);    // returns "5+3"
adder2(5, 3);    // returns 8

I am particularly curious of why operate2 evaluated the arithmetic expression when I thought it would evaluate it as a string at first glance. Does this have something to do with it being defined as a Function Object with the new operator?

A: The first does string concatenation due to the operator being a string
return x + "+" + y;

The second performs an evaluation of the content because that is how new Function works - the result is similar to eval but have a look at the differences here: Are eval() and new Function() the same thing?
So the statement
new Function("x", "y", "return x " + operator + " y;");

has the "return x " + operator + " y;" part evaluated
Here is the second version behaving like the first

function operate2(operator) {
  return new Function("x", "y", "return x +'" + operator + "'+ y;");
}
var adder2 = operate2("+");
alert(adder2(5, 3))

A: It's following the exact description in this documentation on the Mozilla site: Function - JavaScript
The constructor signature:
new Function ([arg1[, arg2[, ...argN]],] functionBody)

functionBody is to be a string containing the JavaScript statements comprising the function definition.

What if you actually wanted adder2 to return a string? This would do it:here's some code that constructs code that generates the expression.
function operate2(operator) {
  return new Function("x", "y", "return '' + x + '" + operator + "' + y;");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ProgressDialog not updating after Configuration Change (orientation turns to horizontal) ProgressDialog quits updating when orientation of screen changes.  I have put into place a fix that salvages the asynctask and sets the activity of the asynctask to the new activity after it is destroyed and rebuilt.  The percentage complete on the progressdialog stays at the percentage it was at before the orientation change.
What am I missing?
package net.daleroy.fungifieldguide.activities;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.daleroy.fungifieldguide.R;
import net.daleroy.fungifieldguide.fungifieldguideapplication;

public class FungiFieldGuide extends Activity {
    //static final int PROGRESS_DIALOG = 0;
    //ProgressThread progressThread;
    private final static String LOG_TAG = FungiFieldGuide.class.getSimpleName();
    fungifieldguideapplication appState;
    private DownloadFile mTask;
    public boolean mShownDialog;
    ProgressDialog progressDialog;
    private final static int DIALOG_ID = 1;

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);

        if ( id == DIALOG_ID ) {
            mShownDialog = true;
        }
    }

    private void onTaskCompleted() {
        Log.i(LOG_TAG, "Activity " + this + " has been notified the task is complete.");

        //Check added because dismissDialog throws an exception if the current
        //activity hasn't shown it. This Happens if task finishes early enough
        //before an orientation change that the dialog is already gone when
        //the previous activity bundles up the dialogs to reshow.
        if ( mShownDialog ) {
            dismissDialog(DIALOG_ID);
            Toast.makeText(this, "Finished..", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case DIALOG_ID:
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMessage("Loading Database (only first run)...");
            return progressDialog;
        default:
            return super.onCreateDialog(id);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        appState = ((fungifieldguideapplication)this.getApplication());

        Object retained = getLastNonConfigurationInstance();
        if ( retained instanceof DownloadFile ) {
            Log.i(LOG_TAG, "Reclaiming previous background task.");
            mTask = (DownloadFile) retained;
            mTask.setActivity(this);
            //showDialog(DIALOG_ID);
        }
        else {
            if(!appState.service.createDataBase())
            {
                Log.i(LOG_TAG, "Creating new background task.");
                //showDialog(DIALOG_ID);
                mTask = new DownloadFile(this);
                mTask.execute("http://www.codemarshall.com/Home/Download");
            }
        }
            //showDialog(PROGRESS_DIALOG);

        View btn_Catalog = findViewById(R.id.btn_Catalog);
        btn_Catalog.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(getBaseContext(), Cat_Genus.class);//new Intent(this, Total.class);
                startActivity(i);
            }
        });

        View btn_Search = findViewById(R.id.btn_Search);
        btn_Search.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(getBaseContext(), Search.class);//new Intent(this, Total.class);
                startActivity(i);
            }
        });
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
            mTask.setActivity(null);
            return mTask;
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        //progressDialog.dismiss();
        //progressDialog = null;
        appState.service.ClearSearchParameters();
    }

    private class DownloadFile extends AsyncTask<String, Integer, Boolean>{
        private FungiFieldGuide activity;
        private boolean completed;
        private String Error = null;
        private String Content;

        private DownloadFile(FungiFieldGuide activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute()
        {
            showDialog(DIALOG_ID);
        }

        @Override
        protected Boolean doInBackground(String... urlarg) {
            int count;

            try {
                URL url = new URL(urlarg[0]);
                URLConnection conexion = url.openConnection();
                conexion.setDoInput(true);
                conexion.setUseCaches(false);

                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conexion.getContentLength();

                // downlod the file
                InputStream input = new BufferedInputStream(conexion.getInputStream());
                OutputStream output = new FileOutputStream("/data/data/net.daleroy.fungifieldguide/databases/Mushrooms.db");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int)total*100/lenghtOfFile);
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
                Log.i(LOG_TAG, e.getMessage());
            }
            return null;
        }

        @Override
        public void onProgressUpdate(Integer... args){
            progressDialog.setProgress(args[0]);
        }

        @Override
        protected void onPostExecute(Boolean result)
        {
            completed = true;
            notifyActivityTaskCompleted();
        }

        private void notifyActivityTaskCompleted() {
            if ( null != activity ) {
                activity.onTaskCompleted();
            }
        }

        private void setActivity(FungiFieldGuide activity) {
            this.activity = activity;
            if ( completed ) {
                    notifyActivityTaskCompleted();
            }
        }
    }
}

A: This is not a real solution but to prevent this I just disabled orientation changes during the life of the AsyncTask with adding first:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
and when the job is done:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
Hope this helps.


text:
Q: Sudden slow down / unusable lag after high memory usage I've got a machine which has been running for a fair wile now with Kubuntu (currently 20.10, 5.8.0-29 stock). Its a well spec'd box (Ryzen 3900x, 32GB memory, Sabrent Rocket PCIe4 SSD running on an X570 Gigabyte Aorus Ultra), and on a typical day is sat running Intelij with some big java / angular / node projects (Lots of filewatchers, open file handles etc) consuming a fair amount of memory, as well as VMWare and Docker running.
I've noticed recently that when memory usage spikes sometimes (typically in intelij or one of the projects running from within it), the whole system will lag out and never come back. Today when it happened, music bluetooth kept playing a second of audio every 10 seconds or so, the text cursor in intelij would blink (although at an erratic rate) and the mouse cursor would move fine (although clicking on anything would take a minute or so to select). I've never waited more than 10 minutes, but in that time this doesn't appear to clear.
On next boot, I can see nothing suggesting any issues at all in the kernel / other logs.
Beyond a full memory test (going to run overnight), is there anything else I could be investigating to see what is causing this?
free -h output:
              total        used        free      shared  buff/cache   available
Mem:           31Gi        18Gi       556Mi       9.9Gi        12Gi       2.9Gi
Swap:          12Gi       4.1Gi       8.6Gi


text:
Q: call DLL from python I have a DLL and I want to call a function from python. The function signature is this:
StartJob(double vInp[], VARIANT vRis[], double *aOpt)

In python I'm using ctype for loading the DLL. I have never done these things so any advice will be useful to me. The question is: what are the correct types to pass to the function?
Now I'm passing
# input, output and flag array initialized
lib = ctypes.cdll.LoadLibrary('C:\\Users\\utente25\\PycharmProjects\\dll\\test.dll')
arrIn = (ctypes.c_double * len(input))(*input)
arrOut = (ctypes.c_char * len(output))(*output)
arrFlag = (ctypes.c_double * len(flag))(*flag)
#Call function
res = lib.StartJob(arrIn, arrFlag, arrOut)


text:
Q: how to read tfrecord data into tensors/numpy arrays? I have a tfrecord file where i have stored a list of data with each element having 2d coordinates and 3d coordinates. the coordinates are 2d numpy arrays of dtype float64.
these are the features i used to store them.
feature = {'train/coord2d': _floats_feature(projC),
                   'train/coord3d': _floats_feature(sChair)}

and i stored them by flattening them into a floatlist.
def _floats_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value.flatten()))

Now i am trying to recver them so i can feed them into my network to train it. I want the 2d coords to be the input and 3d to be the output for training my netwrok.
def read_and_decode(filename):
    filename_queue = tf.train.string_input_producer(filename, name='queue')
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
    serialized_example,

    features= {'train/coord2d': tf.FixedLenFeature([], tf.float32),
            'train/coord3d': tf.FixedLenFeature([], tf.float32)})

    coord2d = tf.cast(features['train/coord2d'], tf.float32)
    coord3d = tf.cast(features['train/coord3d'], tf.float32)

    return coord2d, coord3d

with tf.Session() as sess:
    filename = ["train.tfrecords"]
    dataset = tf.data.TFRecordDataset(filename)
    c2d, c3d = read_and_decode(filename)
   print(sess.run(c2d))
   print(sess.run(c3d))

this is my code but i dont really understand it since i got it from tutorials etc so i was trying to print out c2d and c3d to see what format theyre in but my program just kept running and didnt print anything at all and never terminated. do c2d and c3d contain the 2d and 3d coords for every element in the dataset? can they be directly used when training the network as input and output?
I also dont know what format they should be before they can be used as input to the network. should i convert them back into 2d numpy arrays or 2d tensors? in which case how can i do it? overall im just very lost so any guidace would be extremely helpful! thanks

A: You are on the right lines with tf.data.TFRecordDataset(filename), but the problem is that the dataset is not connected to the tensors that you are passing to sess.run().
Here's a simple example program that should produce some output:
def decode(serialized_example):
  # NOTE: You might get an error here, because it seems unlikely that the features
  # called 'coord2d' and 'coord3d', and produced using `ndarray.flatten()`, will
  # have a scalar shape. You might need to change the shape passed to
  # `tf.FixedLenFeature()`.
  features = tf.parse_single_example(
      serialized_example,
      features={'train/coord2d': tf.FixedLenFeature([], tf.float32),
                'train/coord3d': tf.FixedLenFeature([], tf.float32)})

  # NOTE: No need to cast these features, as they are already `tf.float32` values.
  return features['train/coord2d'], features['train/coord3d']

filename = ["train.tfrecords"]
dataset = tf.data.TFRecordDataset(filename).map(decode)
iterator = dataset.make_one_shot_iterator()
c2d, c3d = iterator.get_next()

with tf.Session() as sess:

  try:

    while True:
      print(sess.run((c2d, c3d)))

  except tf.errors.OutOfRangeError:
    # Raised when we reach the end of the file.
    pass


text:
Q: PHP Arrays Value i have this array
print_r of the array
Array (
  [@attributes] => Array (
    [from] => 14073377593@s.whatsapp.net
    [id] => 1346984983-2
    [type] => chat
    [t] => 1346985039
  )
  [notify] => Array (
    [@attributes] => Array (
      [name] => SISTEMA SMS
    )
  )
  [request] => Array ( )
  [body] => Hola
)

and i need this value
[body] => Hola

someone can help me

A: echo $array['body'];

Have you tried anything?

A: It lives at $array["body"]
Have a look at something like this for a whirlwind tour of associative arrays: http://phpjournal.blogspot.co.uk/2004/11/php-associative-arrays.html

A: Yet being yours a multidimensional array, the body property is on the first level:
Array (
    [@attributes] => Array (
        [from] => 14073377593@s.whatsapp.net
        [id] => 1346984983-2
        [type] => chat
        [t] => 1346985039
    )
    [notify] => Array (
        [@attributes] => Array (
            [name] => SISTEMA SMS
        )
    )
    [request] => Array ( )
    [body] => Hola
)

So as a tip, wrap your print_r calls with <pre> HTML tag in order to read properly formatted output:
 echo '<pre>';
 print_r($stuff);
 echo '</pre>';

It may seem silly, but it saves me a lot of time.


text:
Q: Can't query value from newly created column I just added a new column to the database for a project. I confirmed that the column exists the database. I've added the property to my model and my dbset is defined using that model. However, as soon as I try to query that column value, it gives me NotSupportedException.

The specified type member 'screen_icon' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Context class
public partial class dml_entities : DbContext
{
    public dml_entities() : base("name=dml_entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    // ...

    public virtual DbSet<screen> screen { get; set; }

    // ...
}

Model
public partial class screen
{
    // ...
    public string screen_icon { get; set; }
    // ...
}

Controller code
public class ScreenController : ApiController
{
    private dml_entities db = new dml_entities()

    public IQueryable<object> Get_screen()
    {
        return db.screen.Select(e => new { icon = e.screen_icon });
    }
}

Edit:
When I db.screen.ToList() before selecting from it, the error goes away, but 'screen_icon' is always null, even if there actually is a value in the db.
For whatever reason, it seems like my code doesn't believe that the column exists in the database.
Edit2:
Not sure if its relevant, but the exception does not seem to trigger in the controller code itself.  Attempting to try{} catch{} creates the same result.

A: *

*Does screen_icon has getter and setter or it is a variable? Should be a property

*What is the name and type in database? Maybe try forcing column name with attrbiute like:
[Column("screen_icon")]
public string screen_icon { get; set; }

A: It turns out that the project was using an edmx file to manage their models.  Due to the amount of noise in the file I edited and the fact that I found it through "go to definition" and the not the file explorer, I didn't realize that the model file was generated from the Entities.edmx file.
Once I updated the model in from the edmx designer, my code worked as expected.  And I learned that its important to keep an eye out for comments that inform you not to edit it manually because its an auto-generated file.

A: Try:
    return db.screen.ToList().Select(e => new { icon = e.screen_icon });


text:
Q: Traceroute: destination IP-address returned for all but first hop. (Debian 9.11) At some point in the past year, Traceroute behavior changed. Was working correctly prior.
(Debian v9.11 Traceroute 1:2.1.0-2)
Now, first traceroute result, my gateway, is correct, but all the intermediate hops list the destination ip address rather than the intermediate host. My perimeter firewall explicitly permits ICMP any.
Localhost firewall:
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable

Traceroute results:
shughes@skht5d:~$ traceroute 8.8.8.8
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets
 1  pfSense.abc.example.com (192.168.11.1)  3.222 ms  3.200 ms  3.190 ms
 2  * * *
 3  dns.google (8.8.8.8)  11.662 ms  11.656 ms  11.616 ms
 4  dns.google (8.8.8.8)  14.003 ms  16.191 ms  16.177 ms
 5  dns.google (8.8.8.8)  14.002 ms  13.981 ms  16.121 ms
 6  dns.google (8.8.8.8)  22.640 ms  16.258 ms  19.028 ms
 7  dns.google (8.8.8.8)  25.339 ms  20.188 ms  20.170 ms
 8  dns.google (8.8.8.8)  27.407 ms  25.020 ms  27.858 ms
 9  dns.google (8.8.8.8)  24.951 ms  24.472 ms  24.456 ms
10  dns.google (8.8.8.8)  23.790 ms  21.811 ms  24.017 ms
11  * * dns.google (8.8.8.8)  20.639 ms
12  dns.google (8.8.8.8)  21.437 ms  23.536 ms  22.119 ms
13  dns.google (8.8.8.8)  21.429 ms  21.181 ms  21.207 ms
shughes@skht5d:~$

shughes@skht5d:~$ traceroute a2hosting.com
traceroute to a2hosting.com (104.18.131.225), 30 hops max, 60 byte packets
 1  pfSense.abc.example.com (192.168.11.1)  11.043 ms  11.001 ms  11.006 ms
 2  * * *
 3  104.18.131.225 (104.18.131.225)  18.531 ms  18.527 ms  18.519 ms
 4  104.18.131.225 (104.18.131.225)  18.514 ms  18.508 ms  18.493 ms
 5  104.18.131.225 (104.18.131.225)  18.472 ms  18.476 ms  18.451 ms
 6  104.18.131.225 (104.18.131.225)  30.552 ms  30.868 ms  26.008 ms
 7  104.18.131.225 (104.18.131.225)  26.017 ms  30.792 ms  30.755 ms
 8  104.18.131.225 (104.18.131.225)  41.155 ms  30.765 ms  30.757 ms
 9  104.18.131.225 (104.18.131.225)  30.722 ms  30.714 ms  30.707 ms
10  104.18.131.225 (104.18.131.225)  30.703 ms  29.137 ms  28.252 ms
11  104.18.131.225 (104.18.131.225)  28.202 ms  29.162 ms  29.151 ms
shughes@skht5d:~$


text:
Q: What's the easiest way to update the units command on a Mac? What's the easiest way to update the units command on a Mac? I don't think I have any package managers installed.
I just came across the units command for the first time:
0ony:sse-py stphqu0$ units
586 units, 56 prefixes
You have: 7 miles
You want: km
    * 11.265408
    / 0.088767313
You have:

Actually I found units at this entertaining read on HN, "The 500 Mile Email".
The poster has more than 1000 units, I have less than 600. When I tried typing 3 millilightseconds as in the post, the unit was unrecognized. This is a pretty useful utility and I'd like to get more units, how do I get more?

A: Yosemite (OS X 10.10.2) provides units version 1.0
$ units -version

  units version 1.0  Copyright (c) 1993 by Adrian Mariano
                    This program may be freely distributed
usage: units [-f unitsfile] [-q] [-v] [from-unit to-unit]

You can install gunits 2.01 with MacPorts
$ gunits -V
GNU Units version 2.01
with readline, with utf8, locale en_US,
Units database in /opt/local/share/units/definitions.units
Personal units file in /Users/corti/.units

Copyright (C) 2012 Free Software Foundation, Inc.
GNU Units comes with ABSOLUTELY NO WARRANTY.
You may redistribute copies of GNU Units
under the terms of the GNU General Public License.

with 2559 units, 85 prefixes and 66 nonlinear units, or gunits 2.02 with Homebrew.
You can also build it from scratch with the official distribution (version 2.11)

A: This is just a result of the version of units installed.
Version 1.88 has 2526 units it can convert.  Earler versions have less, and later versions have more.
If you have compiled it yourself, you can just download a newer version. If you have installed it via your distribution's package manager, then you probably have the latest supported version, though most flavours of GNU/Linux have ways to get newer versions.


text:
Q: Is It necessary to get a course in Algebraic Number Theory before grad studies? I am in a predicament when deciding on classes for my graduating year of my undergrad next year.
In first year I thought I wanted to be in physics so I didn't take proofs in second year, so it delayed me getting abstract algebra courses.
This means I have to take Abstract Algebra I next year.
I talked to the professor teaching Algebraic Number Theory next year and asked how under-prepared I would be for the course if I was taking Abstract Algebra 1 along side it.
He said it would be pretty difficult but he would be willing to waive the requirement as he is one of my directed studies supervisors.
I am wondering how important it is for me to take Algebraic Number Theory in my undergrad or if it is something I can take the Masters level equivalent of in my first year of grad school?
I am hoping to get into a Cryptography program for my masters if that affects the answer.
If I don't have to do it in my undergrad it would give me more time to focus on my directed studies and hopefully get honours.

A: My short answer is that if you feel you need that subject for your application to the graduate program, then do it. But if you think you need it for future studies at the graduate level, then for now it might not be very urgent.
The biggest problem that I faced when starting my Master's in maths is not any particular area of knowledge, but the level of mathematical maturity that the Master program requires. This includes things like self-discipline, and the ability to look at a problem and see different angles from which you can tackle it. Virtually all my current subjects challenge me on those skills, and I feel like getting better at them has helped me a lot with fill in the gaps in my knowledge. If you can apply yourself and have 2-3 months between your graduation and the start of your Master's program, I think you still have time to catch up by then.

A: I am a first year grad student, and am currently taking my first algebraic number theory course.
You'll be fine without taking it in undergrad.


text:
Q: Getting a Stream> from a Stream from firebase real time database Flutter I'm very new to flutter Streams/Bloc/Provider and I'm following a tutorial to understand it.
In the tutorial dough they use Firestore so they get a Stream like this:
Stream<List<Todo>> todos() {
    return todoCollection.snapshots().map((snapshot) {
      return snapshot.documents
          .map((doc) => Todo.fromEntity(TodoEntity.fromSnapshot(doc)))
          .toList();
    });
  }

Where their snapshot is List<DocumentSnapshot>, mine from RTDB is instead an Event.
I'm trying to get a Stream<List<Object>> from a RTDB node, but from the .onValue() property I get a Stream<Event>.
Inside the async map() I access the snapshot Event but I don't get access to the Dart.core's map()as in the example that uses Firestore, for it's not a List.
alerts() is the Stream that the bloc will be listening to but it's expecting a Stream<List<Object>> and I can't get it.
How would I go to map it to a Stream<List<Object>> as I need?
Thank you very much for your time and help.
My code is:
//
static UserAlert fromSnapshot(DataSnapshot snapshot) {
    return UserAlert(
        city: snapshot.value['City'],
        country: snapshot.value['Country'],
        date: snapshot.value['Date'],
        description: snapshot.value['Description'],
        id: snapshot.value['Id'],
        latitude: snapshot.value['Latitude'],
        longitude: snapshot.value['Longitude'],
        region: snapshot.value['Region'],
        timestamp: snapshot.value['Timestamp'],
        alertImageName: snapshot.value['alertImageName'],
        imageUrl: snapshot.value['imageUrl'],
        user: snapshot.value['user']);
  }

// try 1
Stream<List<UserAlert>> alerts() {
    return _databaseReference.onValue.map((snapshot) {
      // do the mapping to a Stream<List<UserAlert>>
    });
  }

 // try 2
 Stream<List<UserAlert>> alerts() {
return _databaseReference.onValue.toList(){ // Function expressions can't be named error

};

}
 // try 3
 Stream<List<UserAlert>> alerts() {
return _databaseReference.onValue.map(
    (snapshot) => UserAlert.fromSnapshot(snapshot); // wrong return type
);

}

A: Use StreamTransformer
Stream<UserAlert> alerts() {
  handleData(Event event, EventSink<UserAlert> sink) =>
      sink.add(UserAlert.fromSnapshot(event.snapshot.value));

  final transformer =
      StreamTransformer<Event, UserAlert>.fromHandlers(handleData: handleData);

  return _databaseReference.onValue.transform(transformer);
}


text:
Q: matlab quadprog constraints issue I have a portfolio of weights I am using quadprog in matlab.
I have all the inputs for the quadprog optimizer. I am just having some trouble formulating
the constraints
I would like my constraints to have a lower bound of either 0 or 1%, is there a way to do that while maintainng my objective function
Thanks!

A: I am not sure if I understand your question well.
If your weights are already defined in terms of percentage, it is directly the definition of quadprog:
x = quadprog(H, f, [], [], [], [], lb, [])

So H, e, and f should be provided by the matlab description of:

quadprog(H,f) - returns a vector x that minimizes 1/2 * x' * H * x + f' * x. H must be positive definite for the problem to have a finite minimum."

And lb is a vector of the constraints. For instance if x is a vector 3 x 1, then lb = [0.01; 0.01; 0.01] in the case of the desired percentage is 0.01 (1%)
On the other hand, lets assume the sum_{i=1}^{n} w_i is not equal to 1. Therefore, w_i is not defined in terms of percentage.
Therefore, the constraint that you need is p_i (percentage)= w_i / (sum w_i) >= 0.01 (in the case of the lower bound be 1%).
Note that the constraint in this case is
w_i >= 0.01 * (sum w_i)
Or
-0.01 * (sum_{j=1}^{i-1} w_j) + 0.99 * w_i - 0.01 * (sum_{j=i+1}^{n} w_j) >= 0
Or
0.01 * (sum_{j=1}^{i-1} w_j) - 0.99 w_i + 0.01 * (sum_{j=i+1}^{n} w_j) <= 0
Therefore, this is a constraint of the type Ax <= b.
So
A_ij = 0.01 when i is different from j
A_ij = -0.99 when i = j and b = zeros(n, 1)
In this case you are using
x = quadprog(H, f, A, b)

I hope I helped you!
Daniel


text:
Q: Android Image file path from URI My Manifest activity code
        <activity android:name="FileReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.SEND" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="image/*" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEND_MULTIPLE" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="image/*" />
        </intent-filter>
    </activity>

My Activity code :
Intent i = getIntent();
    String action = i.getAction();

if (action.equals(Intent.ACTION_SEND)) {
        Uri imageUri = (Uri) i.getParcelableExtra(Intent.EXTRA_STREAM);
        if (imageUri != null) {
            Log.i("1234567", "URI : " + imageUri);
            Log.i("123456", "path :" + imageUri.getPath());
            File source = null;
            source = new File(imageUri.getPath());
            String fileNme = "/" + source.getName();

            File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
            Log.i("123456", "destination path :" + destination);
            try {
                FileUtils.copyFile(source, destination);
            } catch (IOException e) {
                Log.i("123456", "IO Exception");
                e.printStackTrace();
            }

        }

im getting exception
01-09 16:10:09.756: W/System.err(30225): java.io.FileNotFoundException: Source 'content:/media/external/images/media/127' does not exist

how do i get the path of the image when i receive an image from DCIM folder ?

A: /**
 * helper to retrieve the path of an image URI
 */
public String getPath(Uri uri) {
        // just some safety built in
        if( uri == null ) {
            // TODO perform some logging or show user feedback
            return null;
        }
        // try to retrieve the image from the media store first
        // this will only work for images selected from gallery
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        // this is our fallback here
        return uri.getPath();
}

source:
Get/pick an image from Android's built-in Gallery app programmatically

A: I've got the same problem. Solved it using the following code:
public static String getPathFromURI(Context context, Uri contentUri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
            DocumentsContract.isDocumentUri(context, contentUri)) {
        return getPathForV19AndUp(context, contentUri);
    } else {
        return getPathForPreV19(context, contentUri);
    }
}

private static String getPathForPreV19(Context context, Uri contentUri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        try {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(columnIndex);
        } finally {
            cursor.close();
        }
    }

    return null;
}

@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getPathForV19AndUp(Context context, Uri contentUri) {
    String documentId = DocumentsContract.getDocumentId(contentUri);
    String id = documentId.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };
    String sel = MediaStore.Images.Media._ID + "=?";
    Cursor cursor = context.getContentResolver().
            query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[]{ id }, null);

    if (cursor != null) {
        try {
            int columnIndex = cursor.getColumnIndex(column[0]);
            if (cursor.moveToFirst()) {
                return cursor.getString(columnIndex);
            }
        } finally {
            cursor.close();
        }
    }

    return null;
}


text:
Q: suspicious "it" in "too adj to V" construction In the "Subject be too adj to V" construction, there seems to be no need to use a pronoun as the object to the verb:

*

*The box is too heavy to lift. (natural)
1'. The box is too heavy to lift it. (unnatural)

The subject "the box" is the semantic object of "lift". But one Australian
inserted "it" in the following:

*Life is too short to live [it] in the same way, so you should do something different once in a while.

The intended reading is "life is too short to live repetitiously." So this "it" in #2 is dubious; it doesn't pattern with #1.
Do you have an explanation?

A: These are called hollow clauses because a non-subject element such as an object is missing yet recoverable from an antecedent expression:
(1) The box is too heavy [to lift __].
(2) Life is too short [to live __] in the same way ...
The '__' marks the place where there is an element missing but understood, i.e. the objects of "lift" and "live", and the elements in bold provide an interpretation for the missing noun phrases. Thus in (1) what is too heavy to lift is "the box", and in (2) what is too short to live is "life".
Adding "it" in (1) is not really possible, though it would be acceptable if it read "The box is too heavy to lift it onto the shelf", where "it" is a pro-form referring to "the box". Adding "it" in (2) seems acceptable because of the  complement phrase "in the same way ..."; again "it" would be a pro-form referring to "Life"..


text:
Q: Java EE App Server Hello World I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server.
Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks.
If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e.

*

*Download XX

*Write some code to do YY

*Change file ZZ

*Other steps...

Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.

A: I would choose JBoss AS or GlassFish for a start. However I'm not sure what you mean by Java EE "Hello World". If you just want to deploy some JSP you could use this tutorial (for JBoss):
http://www.centerkey.com/jboss/
If you want to get further and do the EJB stack and/or deploy an ear-file, you could read the very good JBoss documentation:
Installation Guide
Getting started
Configuration Guide
In general you could also just do the basic installation and change or try the pre-installed example applications.
I currently have JBoss installed (on windows). I develop with Eclipse and use the Java EE server integration to hot deploy or debug my code. After you get your first code running you realy should have a look at the ide integration since it makes development/deploy roundtrips so much faster.

A: The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is the one from Sun. For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See here for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler.

A: Another option is to get Oracle JDeveloper (free to download and use - it's a full featured IDE that includes some neat extras like the SQL workbench and BPEL designer).
As a learning tool, it is quite good, not only for the tutorials available from Oracle, but it includes a range of "cue-card" lessons in the tool itself to teach many common techniques.
cue card view http://tardate.heroku.com/images/jdev-cuecards.jpg

A: If you haven't gone near NetBeans in a while its catching up with Eclipse very fast and worth a look, especially when starting Java EE.
Version 6.x installs Tomcat and/or Glassfish for you and then provides wizards to create/deploy/redeploy applications.
The initial tutorial on Web Applications is here and a more complex example here.

A: As JeroenWyseur puts it, Java EE is a fairly big space. In addition to what he said, you should try to get more details of what exactly you'll be doing: servelts & co, EJB (entity, session, message beans?) and try to get familiar with that.
It should be clear for you that your code runs in a managed environment, which imposes a lot of constraints. in order to make sure you understand what happens you should get familiar with the concept of deployment. Then, if you do EJBs, transaction management is important too. If you don't understand exactly what happens when a bean or a servlet is deployed, how transactions are managed, how beans are invoked, you're going to have a hard time.
A book that helped me a lot back in the time is Mastering EJB, by Ed Roman.
Also, getting familiar with RMI will help you understand EJBs.


text:
Q: Reliably Accessing Pointer Accounting Data I have read in: How does free know how much to free? that when one has some memory allocation denoted with a pointer such as
float (*ptr)[10]=malloc(sizeof(float)*100)

for a 10x10 array, ptr has a "head" to it with "accounting" information telling of the "step size" and what not so that you can properly perform pointer arithmetic and use free and whatnot.
Is there a consistent (not architecture dependent) and reliable (defined behavior) that can allow one to get their hands on this information?
I have read elsewhere that the de facto way to track array length when there are casts and dynamic memory allocations about is to manually allocate a slot to store the size. This naturally leads me to believe the answer to my question is 'no' yet I think I'd rather not make assumptions or I'll get my own sort of memory leakage.

A: Converting comments into an answer.
There is no defined standard way to get at the 'size of the block of allocated memory'. Each implementation has to have a way of knowing the size of each block it allocates, but there's no way for a programmer using the implementation to know the size (in general).

So it is dependent on some number of things, but if all is known, system, architecture, compiler, you're saying there is no resource to find out how things are formatted in memory?

There is no standard (neither de jure nor de facto standard) way to get at the information about the size of a block of memory allocated. All else apart, the size allocated by the library is usually bigger than the size requested (definitely because of the housekeeping data, but even the data portion may be rounded up to a multiple of 8 or a multiple of 16) — should the code report the size requested or the size allocated?
And, as 1201ProgramAlarm noted, one option on open source systems is to look at the C library's implementation of malloc() and free() to see what it does and devise a mechanism to provide the answer to the programmer.  However, any such research is specific to that system — different systems will do it differently, in general — and the whole idea runs into a stone wall if the system is a closed source system.


text:
Q: How to select occurrences that respect Find panel's flags in Sublime Text 3? Currently, pressing CMD+D is selecting partial matches, regardless of Find panel's "whole word" or "case sensitive" toggles.
Example:
job.findJob('something');
job.done();

If I select job and press CMD+D with the Find panel visible and "whole word" and "case sensitive" enabled, unfortunately the Job in findJob gets added to my selection.
How can I instruct Sublime Text to respect the Find panel's flags?


text:
Q: Database mail not working properly I am bit confused sending e-mail via SQL Server 2008 Management Studio. I tried all remedies discussed in most threads, but unfortunately still having the issues. Can someone help me to resolve the matter? Much appreciated!
I am getting following error, when trying to send e-mail via SSMS

The mail could not be sent to recipient because of the mail server failure...(SMTP server requires a secure connection or the client was not authenticated. The server response was 5.7.0. Must issue a STARTTLScommand first

I checked my GMail user name and password, and properly defined profile and account, port used 587.
SMTP E-mail setup done at IIS (Windows 7 PC)
Kindly advise, how can I overcome the e-mail sending issue using SSMS?

A: It's better to share the configuration which you have set for database mail, but anyways:

*

*STARTTLS means the Gmail server is asking for authentication, and xp_smtp_sendmail  does not provide ways for getting authenticated with Gmail or Yahoo.

*Check these links ... link and link as I guess you have something wrong in your configuration there.


text:
Q: bubble sort in vhdl Can anyone help me in writing VHDL code for bubble sort given an array of data as input?
I have declared in_array as input which contains 15 array elements. i want to bubble sort them in descending order.
in_array is input array.
sorted_array is out put array.
in_array_sig is signal of type in_array
I am facing problem with statements inside process
Below is my code:
architecture behav of Bubblesort is
  signal in_array_sig : bubble;
  signal temp : std_logic_vector(3 downto 0);
  signal i : integer := 0;
begin

  in_array_sig <= in_array;

  proc1 : process(clk, reset)
  begin
    if reset = '0' then
      if (clk'event and clk = '1') then
        while (i <= 15) loop
          if (in_array_sig(i) < in_array_sig(i + 1)) then
            temp <= in_array_sig(i);
            in_array_sig(i) <= in_array_sig(i + 1);
            in_array_sig(i + 1) <= temp;
          end if;
          i <= i + 1;
        end loop;
      end if;
    end if;
  end process;

  sorted_array <= in_array_sig;

end behav;

I am beginner in VHDL coding. Kindly help me with this.

A: The lack of a Minimal Complete and Verifiable example makes it hard to provide an answer about all the the things stopping your code from bubble sorting accurately. These can be described in the order you'd encounter them troubleshooting.
  proc1 : process(clk, reset)
  begin
    if reset = '0' then
      if (clk'event and clk = '1') then
        while (i <= 15) loop
          if (in_array_sig(i) < in_array_sig(i + 1)) then
            temp <= in_array_sig(i);
            in_array_sig(i) <= in_array_sig(i + 1);
            in_array_sig(i + 1) <= temp;
          end if;
          i <= i + 1;
        end loop;
      end if;
    end if;
  end process;

Before starting note that the clock is gated with reset. You could qualify assignments with reset making it an enable instead.
Problems
The first thing we'd find producing an MCVe and a testbench is that the process never suspends. This is caused by the condition in the while loop depending on i and i a signal being updated within the process. i shouldn't be a signal here (and alternatively you could use a for loop here).
This also points out that temp is a signal and suffers the same problem, you can't use the 'new' value of temp until the process has suspended and resumed. Signals are scheduled for update, a signal assignment without a waveform element containing an after clause have an implicit after clause with zero delay.  Signal updates do no occur while any process scheduled to resume has yet to resume and subsequently suspend. This allows the semblance of concurrency for signals who's assignments are found in sequential statements (a concurrent statement has an equivalent process containing equivalent sequential statements). So neither i nor temp can update during execution of a processes sequence of statements and both want to be variables.
We'd also get bitten using a signal for in_array_sig. As you increment i the previously indexed in_array_sig(i + 1) becomes the next loop iteration's in_array_sig(i). Without an intervening process suspend and resume the original value is available. in_array_sig wants to be a variable as well.
If we were to fix all these we'd also likely note that i is not initialized (this would be taken care of in a for loop iteration scheme) and we might also find that we get a bound error in a line using an (i + 1) index for in_array_sig. It's not clear without the author of the question providing an MCVe whether the array size is 16 (numbered 0 to 15) or 17.  If the former i = 15  + 1 would be out of the index range for the undisclosed array type for in_array, in_array_sig, and sorted_array.
If we were to insure the index range is met noting that we only need 1 fewer tests and swaps than the number of elements in an array we'd find that what the process isn't a complete bubble sort. We would see the largest binary value of in_array_sig end up as the right most element of sorted_array. However the order of the remaining elements isn't guaranteed.
To perform a complete bubble sort we need another loop nesting the first one. Also the now 'inner' for loop can have a decreasing number of elements to traverse because each iteration leaves a largest remaining element rightmost until the order is assured to be complete.
Fixes
Fixing the above would give us something that looks like this:
architecture foo of bubblesort is
    use ieee.numeric_std.all;
begin

BSORT:
    process (clk)
        variable temp:      std_logic_vector (3 downto 0);
        variable var_array:     bubble;
    begin
        var_array := in_array;
        if rising_edge(clk) then
            for j in bubble'LEFT to bubble'RIGHT - 1 loop
                for i in bubble'LEFT to bubble'RIGHT - 1 - j loop
                    if unsigned(var_array(i)) > unsigned(var_array(i + 1)) then
                        temp := var_array(i);
                        var_array(i) := var_array(i + 1);
                        var_array(i + 1) := temp;
                    end if;
                end loop;
            end loop;
            sorted_array <= var_array;
        end if;
    end process;
end architecture foo;

Note the loop iteration schemes are described in terms of type bubble bounds, the outer is one shorter than the length and the inner is one shorter for each iteration. Also note the sorted_array assignment is moved into the process where the in_array_sig variable replacement var_array is visible.
Also of note is the use of the unsigned greater than operator. The ">" for std_logic_vector allows meta-values and 'H' and 'L' values to distort relational comparison while the operator for unsigned is arithmetic.
Results
Throw in package and entity declarations:
library ieee;
use ieee.std_logic_1164.all;

package array_type is
    type bubble is array (0 to 15) of std_logic_vector(3 downto 0);
end package;

library ieee;
use ieee.std_logic_1164.all;
use work.array_type.all;

entity bubblesort is
    port (
        signal clk:             in  std_logic;
        signal reset:           in  std_logic;
        signal in_array:        in  bubble;
        signal sorted_array:    out bubble
    );
end entity;

along with a testbench:
library ieee;
use ieee.std_logic_1164.all;
use work.array_type.all;

entity bubblesort_tb is
end entity;

architecture fum of bubblesort_tb is
    signal clk:             std_logic := '0';
    signal reset:           std_logic := '0';
    signal in_array:        bubble :=
                   (x"F", x"E", x"D", x"C", x"B", x"A", x"9", x"8",
                    x"7", x"6", x"5", x"4", x"3", x"2", x"1", x"0");
    signal sorted_array:    bubble;
begin

DUT:
    entity work.bubblesort(foo)
        port map (
            clk => clk,
            reset => reset,
            in_array => in_array,
            sorted_array => sorted_array
        );
CLOCK:
    process
    begin
        wait for 10 ns;
        clk <= not clk;
        if now > 30 ns then
            wait;
        end if;
    end process;

end architecture;

and we get:

something that works.
The reset as enable has not been included in process BSORT in architecture and can be added in, inside the if statement with a clock edge condition.
And about here we get to Matthew Taylor's point in a comment about describing hardware.
Depending on the synthesis tool the process may or may not be realizable as hardware. If not you'd need intermediary variables holding the array portions used in each successive iteration of the inner loop.
There's also the issue of how much you can do in a clock cycle. Worst case there is a delay depth comprised of fifteen element comparisons and fifteen 2:2 selectors conditionally swapping element pairs.
If you were to pick a clock speed that was incompatible with the synthesized delay you'd need to re-architect the implementation from a software loop emulation to something operating across successive clocks.
That could be as simple as allowing more clock periods by using that enable to determine when the bubble sort is valid for loading into the sorted_array register. It could be more complex also allowing different and better performing sorting methods or a modification to bubble sort to say detect no more swaps can be necessary.


text:
Q: Use Webmatrix Razor to Replace Classic ASP Site I have been looking at ASP.Net Web Pages and I think it would be a good replacement for some classic asp sites I am working on.  There is a lot about them that is similar to how classic asp did things, so I believe there is a chance I can drag the other programmers into the present.  My problem is that I have yet been able to find any indepth documentation to see if there is any "gotchas" I need to be aware of if I choose to go down this path.  So if anyone knows of any, I could really use that information.  I think going straight to MVC and Web Forms would be a bridge too far for the others at the moment.  Thanks.
Wade
I found a link from Mike Brind - should I use WebMatrix to build a real-world website?

A: I'd suggest that Web Pages as a framework is probably the best next step you can take, but I would also advise that at least one person in the team takes time to understand the basics behind the MVC pattern. You may decide it's too much for the majority of the team at the moment, and that's fair enough, but you can use your knowledge to plan the development of the Web Pages site so that it can be more easily converted to MVC at some stage in the future, should you decide that's the way to go.
The things I would look at (coming from a classic ASP background myself) are functions and helpers. Decide on a data access strategy - The Entity Framework works well with Web Pages and can be transferred to MVC easily. Avoid the Database helper. Use Visual Web Developer 2010 SP1 for the Intellisense option.
As Knox said, you have the whole of the ASP.NET framework available to you so there should be no Web Pages specific "gotchas", and it's a massive step up from classic ASP.

A: I've been using Webmatrix/WebPages/Razor for a while now and like it.  It's been a while since I used Classic ASP, but WebPages to me feels like a true successor to classic asp and what ASP.net should have been from the start.  I'm actually moving most of my smaller sites to the WebPages framework from WebForms.  Here are some things I've encountered.
I'm not sure if this is a gotcha or not, but I thought I would mention that with WebPages the scope of your variables may behave differently.  I know a lot of Classic ASP sites that used to use include files to run snippets of code.  Many of them depended on global variables set in the parent document.  In WebPages, if you use RenderPage or Helpers to replace includes they run mostly outside of the Parent's scope.  If you used Server.Execute instead of includes then you might not notice much difference, but if you did use includes and lots of global variables you may notice it.
Another possible gotcha is in ClassicASP <%=%> doesn't encode output, but in WebPages the Razor syntax @ encodes output by default.
Another thing to consider is using C# vs VB.net with Webpages.  Although vb.net works you'll find that most samples, tutorials and people in forums use C#.
Finally something that bothers me is that it is named the "webpages" framework.  I've found it hard to do a good Google search using the term "webpages".  Even "asp.net webpages" brings back mostly webform results.  I have more success using "webmatrix" or "razor".

A: Can't recommend any documentation but here is an introduction to Web Matrix on mikesdotnetting.com blog where he has blogged quite a lot about Web Pages with Web Matrix.

A: We have two production sites, developed using Web Matrix.  One serves our customers, the other is an intranet for our staff.  They've been running in production for almost a year.  I'd say about 95% of the sites were developed purely in WebMatrix IDE with about 5% going into Visual Studio, especially for the occassional obscure debugging.  We're happy with WebMatrix / Web Pages.  I didn't use WebForms because I was concerned about WebForm's ability to do really lightweight pages, since many of our users are using cellular data on iPads or iPhones.  I didn't use MVC because of the additional complexity, since many of our pages are just showing the user read-only data from our production database.  Because WebMatrix gives you access to the complete ASP.NET library, I haven't felt held back at all.

A: We are currently converting our ASP pages to Web Matrix.  We tried to do conversions using WebForms a few years ago, only ending in frustration.  After a small learning curve on the C# and Razor syntax, our development staff feel that we made a correct decision in going with Web Matrix.


text:
Q: Refactoring Javascript for Angular 2 I've created a simple tool for adding and removing heroes to and from a list using a select.
When a hero is selected, it is added to the array myheroes and displayed as a list item. The selected hero is also disabled in the select.
When a hero is deleted from the list, it is enabled in the select so it can be selected again.
This works as expected but I sense there must be a better and more elegant approach using the features of Angular 2. E.g. an attribute directive that listens for changes to myheroes.
All advice/guidance is welcome.
Plnkr
@Component({
  selector: 'my-app',
  template: `

My heroes:

      {{ myhero }}
      x

  <select id="hero" #hero (change)=addItem(hero)>
   <option>Select a hero</option>
   <option *ngFor="let hero of heroes">{{ hero }}</option>
  </select>
`
})
export class AppComponent {
  heroes = ['Windstorm','Bombasto','Magneta','Tornado'];
  myheroes= [];

  deleteItem(item: string) {
    const index = this.myheroes.indexOf(item);
    this.myheroes.splice(index, 1);
    //TODO enable item in select options
    const output = document.getElementById('hero').options;

    for(const i=0;i<output.length;i++) {
      if(output[i].value == item){
        output[i].disabled = false;
      }
    }
  }

  addItem(item: HTMLSelectElement) {
    if(item.value != 'Select a hero') {
      this.myheroes.push(item.value);
      item.options[item.selectedIndex].disabled = true;
    }
  }
}

A: Html options have a disabled attribute that you can bind to [disabled]="<condition>", so this would be the preferred way of handling the enabling/disabling of select options rather that using a document selector.
If you were to change to using this then there would be no question that there is no need to separate out the handling of this functionality.
Also, an added point about your code example - you might want to reset the value inside the select inside your handling for the change event as there is a bug where if you select an item and then immediately remove it from the list, you then can't add that item back into the list without first selecting another one as the change event is only fired when the model bound to the select changes.


text:
Q: How do I split a value using the split function from javascript to split checking only the first and last occurence So I need to split an regex that's coming from my database. The value is like the following
regexValue = '/^([0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}|[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2})$/ig'

if you analyze throughly this regex you can see that it have an forward slash '/' between the regex. So if I wanted to split it, using
values.split('/');

It would generate more strings than I would like to. For example a simple regex
//would generate three values("", \w+ , ig)
regexValue = '/\w+/ig'
regexValue.split('/');

Is there a way so I could only split getting the first and last values?

A: If you want to split that string into the regular expression bodyand its flags, you can do that easily with...a regular expression.
const parts = /^\s*\/(.*)\/(?:([a-z]*))\s*$/.exec(regexString);
//           A ^
//           B  ^^^
//           C     ^^
//           D       ^^^^
//           E           ^^
//           F             ^^^^^^^^^^^^
//           G                         ^^^
//           H                            ^

*

*A: Start of input

*B: Optional whitespace

*C: Leading slash of regex "literal"

*D: Body of the expression

*E: Ending slash of regex "literal"

*F: Optional flags

*G: Optional whitespace

*H: End of input

Live Example:

const regexString = '/^([0-9]{3}\\.?[0-9]{3}\\.?[0-9]{3}\\-?[0-9]{2}|[0-9]{2}\\.?[0-9]{3}\\.?[0-9]{3}\\/?[0-9]{4}\\-?[0-9]{2})$/ig';

const parts = /^\s*\/(.*)\/(?:([a-z]*))\s*$/.exec(regexString);
if (!parts) {
    console.log("No match");
} else {
    const [, body, flags] = parts;
    console.log(`body:  ${body}`);
    console.log(`flags: ${flags}`);
}

Note that I escaped the backslashes in the string literal, since you said you're reading this from your database, you don't have it in a string literal in your code. It's just that inside a string literal, a backslash is an escape character, so \. and . mean exactly the same thing. To write a string literal defining a string with backslashes in it, you have to escape them as I've done in the snippet above. Again, you've said it comes from your database, so you're fine, but I figured I should escape them in the example to avoid being misleading.


text:
Q: JavaScript function to be executed in the last after all other scripts I have a modal which automatically opens up after certain time period. The code to open the modal is written in a js file.
- xyz.js

 var timehandle

 //setTimeout function

        timehandle=window.setTimeout("func()",x);

  //function to open the modal

      func(){

       $('#modal').show();
     }

i am clearing the timer from a jsp in order to avoid modal being opened.
 - abc.jsp

   <script>

      head.ready(function() {

         $(document).ready(function () {

                window.clearTimeout(timehandle);

         });

      });
   </script>

however, document.ready in the jsp is called earlier than the function to load the modal based on setTimeout. Can anyone tell me how do I make sure that the clearTimeout is called after the js file has been executed?

A: You should use <body onload="myFunction()"> since what you really want it to execute your js code after the page has loaded.

Execute a JavaScript immediately after a page has been loaded

Documentation


text:
Q: How to select all records that match with the concatenation of (name, surname) OR (surname, name) I'm using an ajax live search to select all users whose concatenation of name and surname match with the text entered, and it works fine:
$sql = "SELECT * FROM users WHERE concat(name,' ',surname ) LIKE ?";

Now, I would like to match the same users also with the opposite concatenation that is surname - name. I've tried this but it doesn't work.
$sql = "SELECT * FROM users WHERE (concat(name,' ',surname ) LIKE ?) or (concat(surname,' ',name ) LIKE ?)";

if(isset($_REQUEST["term"])){
  // Prepare a select statement
  $sql = "SELECT * FROM users WHERE (concat(name,' ',surname ) LIKE ?) or (concat(surname,' ',name ) LIKE ?)";

  if($stmt = mysqli_prepare($conn, $sql)){
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "s", $param_term);

    // Set parameters
    $param_term = $_REQUEST["term"] . '%';

    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)){
      $result = mysqli_stmt_get_result($stmt);

      // Check number of rows in the result set
      if(mysqli_num_rows($result) > 0){
        // Fetch result rows as an associative array
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
          echo "
" . $row["name"] . " " . $row["surname"] .  "
"
        }
      } else{
        echo "
No matches found
";
      }
    } else{
      echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
  }

  // Close statement
  mysqli_stmt_close($stmt);
}

I expext to match the same users but I receive the message:

ERROR: Could not able to execute SELECT * FROM users WHERE
  (concat(name,' ',surname ) LIKE ?) or (concat(name,' ',surname ) LIKE
  ?).

A: You got two placeholders ? in your query-string but only binding one variable to the statement. Try to bind it a second time, so the count matches.
mysqli_stmt_bind_param($stmt, "ss", $param_term, $param_term);


text:
Q: Disk partition showing "Low Disk Space" but cannot delete Windows Backup files Windows 7 desktop PC that has been using Windows Backup on a schedule. Unfortunately it has been backing up to the Recovery partition where the original factory software is located. Windows Backup has filled the remaining space in this Recovery partition then crashed and now the Recovery partition continually shows "Low Disk Space" and causes frequent pop-ups from Windows that it needs attention. When I examine the Recovery partition there is only the factory software present (well within the partition size) and there is no sign of the Windows Backup files. This is the case even if "Show hidden files and folders" is switched on and "Hide protected operating system files" is switched off. How can I delete the offending Windows Backup files and hence get rid of the Low Disk Space warning messages? Windows Backup does not list any old Backups for deletion.

A: Go to Control Panel, under System and Security, go to Backup and Restore. Click on "Change Settings", on that screen, there will be a button to "View backups..." click on that and you can click on specific backups to delete.


text:
Q: MYSQL query to count descendants of items by finding its id in a comma separated string My MYSQL database uses a tree-like system where each item can have an arbitrary number of descendants.  Each item has a regular INT 'parent' column containing its parent as well as a VARCHAR 'parents' column which consists of a comma-separated string containing all of its ancestor's ids.
id    parent    parents
-------------------------------
1     0         0
2     1         0,1
3     1         0,1
4     3         0,1,3

I need to get a list of all items, each of them with their total number of descendants counted up.  Here is the query I have so far:
SELECT items.id AS item_id,
COUNT(children.id) AS children
FROM items items
LEFT JOIN items children ON (items.id IN (children.parents))

This just sends back one row, with a child count of 0.  How do I do this properly?
EDIT:
After fixing the query so it appears like this:
SELECT
  i.id AS item_id,
  COUNT(*) AS children
FROM
  items i
LEFT JOIN
  items c
  ON (i.id IN (c.parents))
GROUP BY i.id;

the results show the rows, but each has only one child.  This does not reflect the data, presumably something is wrong with the IN statement (FIND_IN_SET does the same thing).
EDIT2:
After changing the IN statement to the following
ON LOCATE(i.id, c.parents) > 0

item 1 has the correct number of children (3) but the remaining items all show up as having 1 child.  Items 2 and 4 should have 0, and 3 should have 1.

A: You need to GROUP BY items.id for COUNT()to work as intended.
With aliases changed to something less ambiguous:
SELECT
  i.id AS item_id,
  COUNT(*) AS children
FROM
  items i
LEFT JOIN
  items c
  ON FIND_IN_SET(i.id, c.parents) > 0
WHERE c.id <> i.id
GROUP BY i.id;

For more complex COUNT()/GROUP BY examples, see this question or MySQL documentation. For FIND_IN_SET(), nice example here.
See sqlfiddle here


text:
Q: Renaming columns in pandas dataframe using regular expressions    Y2010  Y2011  Y2012  Y2013  test
0  86574  77806  93476  99626  2
1  60954  67873  65135  64418  4
2    156    575    280    330  6
3   1435   1360   1406   1956  7
4   3818   7700   6900   5500  8

Is there a way to rename the columns of this dataframe from Y2010... to 2010.. i.e. removing the initial 'Y'. I want to use regular expressions since I have quite a few such columns. I tried this:
df.rename(df.filter(regex='^Y\d{4}').columns.values, range(2010, 2013 + 1, 1))

--EDIT:
The dataframe doees include columns which do not start with a 'Y'

A: I'd use map:
In [11]: df.columns.map(lambda x: int(x[1:]))
Out[11]: array([2010, 2011, 2012, 2013])

In [12]: df.columns = df.columns.map(lambda x: int(x[1:]))

In [13]: df
Out[13]:
    2010   2011   2012   2013
0  86574  77806  93476  99626
1  60954  67873  65135  64418
2    156    575    280    330
3   1435   1360   1406   1956
4   3818   7700   6900   5500

Edit: I forgot the most-popular pandas question:
In [21]: df.rename(columns=lambda x: int(x[1:]))
Out[21]:
    2010   2011   2012   2013
0  86574  77806  93476  99626
1  60954  67873  65135  64418
2    156    575    280    330
3   1435   1360   1406   1956
4   3818   7700   6900   5500

If you have additional columns, I would probably write a proper function (rather than a lambda):
def maybe_rename(col_name):
    if re.match(r"^Y\d{4}", col_name):
        return int(col_name[1:])
    else:
        return col_name

In [31]: df.rename(columns=maybe_rename)
Out[31]:
    2010   2011   2012   2013  test
0  86574  77806  93476  99626     2
1  60954  67873  65135  64418     4
2    156    575    280    330     6
3   1435   1360   1406   1956     7
4   3818   7700   6900   5500     8


text:
Q: How to remove chapter numbering without removing it from table of contents It seems I have spent two days trying to find out the solution to my problem. I have just finished typing my M.Sc thesis using Latex (MIKTEX 2.9). Unfortunately, all my chapters begin with the chapter number at the top left corner of a page. My supervisor asked me to remove that numbering of the chapters without removing them from the table of contents.
I have tried my best to do that but I failed. The last attempt I made is \chapter*{chapter title}, the moment I compiled my work, I found out that it began sectioning from 0.1, 0.2, and so on, which I don't like.

I have this code inside my thesis:
\chapter*
{\quad \quad \quad \quad \quad\quad \large{CHAPTER ONE}}
\addcontentsline{toc}{chapter}{CHAPTER ONE}

%Introduction}{}
\pagenumbering{arabic}
\onehalfspacing
\begin{center}
\textbf{\large \quad INTRODUCTION}
\end{center}

\section{Introduction} This chapter gives a brief highlight on the concept of the Newton and quasi-Newton methods for solving nonlinear system of equations. The chapter contains motivation of the study, the aim and objectives, scope and limitations, methodology of the research. It includes some basic fundamentals and definitions of some basic terms.

After compiling, it gives me this:
CHAPTER ONE

INTRODUCTION

0.1 Introduction
This chapter gives a brief highlight on the concept of the Newton and quasi-
Newton methods for solving nonlinear system of equations. The chapter contains
motivation of the study, the aim and objectives, scope and limitations, methodol-
ogy of the research. It includes some basic fundamentals and definitions of some
basic terms.

NB: Please observe how the section "Introduction" is numbered. I want it to be numbered 1.1 not 0.1.

A: I don't think that you want to remove the numbering: You want to use words (one, two) instead of numbers in the heading. This can be done (for english) e.g. with the numname package. The exact code depends on your class, here is an example for book:
\documentclass{book}
\usepackage{numname}
\makeatletter
%Redefine chapterheading:
\def\@makechapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright \normalfont
    \ifnum \c@secnumdepth >\m@ne
      \if@mainmatter
        \huge\bfseries \@chapapp\space \numtoName{\c@chapter}
        \par\nobreak
        \vskip 20\p@
      \fi
    \fi
    \interlinepenalty\@M
    \Huge \bfseries #1\par\nobreak
    \vskip 40\p@
  }}
\makeatother
\begin{document}
\tableofcontents
\chapter{abc}
\section{abc}
\end{document}

A: None of the other solutions worked for me. Here's what worked:
\tableofcontents

\phantomsection
\chapter*{Introduction}
\addcontentsline{toc}{chapter}{Introduction}

This is the beginning

Note the use of \phantomsection. Thanks to this old thread on LaTeX.org from '08.

A: You can do something as is done in here.
Use code similar to the following:
\documentclass{report}
\begin{document}
\tableofcontents
\chapter*{Acknowledgments}
\addcontentsline{toc}{chapter}{Acknowledgments}
\chapter*{Introduction}
\addcontentsline{toc}{chapter}{Introduction}
\chapter{Experiments}
\chapter{Conclusion}
\end{document}

The idea is to use \chapter*{} for unnumbered chapters and then add them to the toc explicitly with the \addcontentsline.
Which gives this result:

A: By adding \setcounter{chapter}{n} before the nth chapter seems to fix the numbering of subsections issue. Also though, you have to reset the numbering of sections. An easy way to do this would to just define a new command. For example:
\documentclass{report}
\newcommand{\mychapter}[2]{
    \setcounter{chapter}{#1}
    \setcounter{section}{0}
    \chapter*{#2}
    \addcontentsline{toc}{chapter}{#2}
}
\begin{document}
\tableofcontents
\mychapter{0}{Acknowledgments}
\mychapter{1}{Introduction}
\section{Introduction}
\section{Further Introduction}
\mychapter{2}{Experiments}
\section{Experiment One}
\section{Experiment Two}
\end{document}

A: If I read that correctly, you want chapters to have numbers. These numbers should be shown in the ToC. But the numbers should not be printed in the chapter heading. This can be achieved with the titlesec package:
\documentclass{report}
\usepackage{titlesec}

\titleformat{\chapter}
  {\Large\bfseries} % format
  {}                % label
  {0pt}             % sep
  {\huge}           % before-code

\begin{document}
\tableofcontents
\chapter{Acknowledgments}
\chapter{Introduction}
\section{Introduction}
\section{Further Introduction}
\chapter{Experiments}
\section{Experiment One}
\section{Experiment Two}
\end{document}

The ToC then looks like

while the chapter heads in the text look like


text:
Q: GeoDjango WebMapping Application Update According to the below GIS.SE questions, GeoDjango was the preferred framework for creating simple and quick webmap applications. But these questions are now all 2-3 years old.  Can we verify whether or not consensus says that GeoDjango still remains top among webmapping application frameworks?
What are the advantages of using Rails for a GIS/mapping application?
What are the Python tools/modules/add-ins crucial in GIS?
I'm new to GIS and I'm looking for a developer-friendly web GIS


text:
Q: How to add product manufacturer detail in checkout page oscommerce I am searching to display product manufacturer detail in checkout page for Oscommerce.
Anyone can help me how to fix this issue?

A: Finally i got solution friends, go to /includes/classes/order.php, in that file check below line
'id' => $products[$i]['id']);
replace with
'id' => $products[$i]['id'],
'manufacturer' => $products[$i]['manufacturer']);
then add $order->products[$i]['manufacturer'] in checkout.php file or any where in checkout file


text:
Q: Design an active bandpass filter to get 1.5MHz peak frequency and 300KHz band I have this question in Linear Circuit Analysis course where I need to find the values of R1, R2, C1, C2, of the given bandpass filter circuit in order to get a peak frequency wp = 1.5 MHz and a bandwidth Bw = 300 kHz.
the first step is to find the transfer function of the circuit, to compare it to the general TF of the bandpass filter:
\$H(s) = \frac{Ks}{s^{2} + 2\sigma s +\omega p^{2}}\$  (1)
and this is what I get :
\$H(s) = \frac{\frac{-1}{C2R1} s}{S^{2} + (\frac{1}{R2C2} + \frac{1}{R1C1})s + \frac{1}{R1R2C1C2}}\$ (2)
by comparing the two functions, we get these 2 equations (Bw and wp) with 4 unknowns:
\$\frac{1}{R1C1} + \frac{1}{R2C2} = 6\pi \ast 10^{5}\$    (I)
\$ \frac{1}{R1R2C1C2} = 9\pi ^{2}\ast 10^{12}\$ (II).
I am allowed to assume 2 unknowns out of the four, so, I went with C1 = C2 = 1uF.
now I'm supposed to solve a system of 2 equations with 2 unknowns, but for some reason, it is not working with me; I tried solving for R1 in eq 2, and the substitute in eq 1 and I got a negative R2 resistance, what could be wrong?? is there another way to solve it that I am not aware of??
Edit 1: fixed the equation format.

A: It won't make a very sharp or precise filter using the configuration shown but, to make life simpler (given that it is a really sloppy filter) you can regard C1 and R1 as forming a high-pass network and C2 and R2 as forming a low-pass network.
The two filter points need to be different to obtain a 300 kHz bandwidth so,

*

*make the low-pass network cut-off at 1.5 MHz + 150 kHz (1.65 MHz) and

*make the high-pass network cut-off at 1.5 MHz - 150 kHz (1.35 MHz).

That allows you to calculate both resistors based on both capacitors being 1 uF. However, what you will find is that 1 uF is too high in value for an op-amp to work with at circa 1.5 MHz and you will need to choose a much lower default value.
For instance, using a 100 pF capacitor, it will form a 3 dB point at 1.65 MHz when R = 964 ohms.
If you'd have used 1 uF, R would be 0.096 ohms and that isn't practical for any op-amp.
However, you will never get a centre frequency to bandwidth ratio as required by the question using a simple op-amp and high-pass and low-pass networks. To get a centre frequency if 1.5 MHz and a bandwidth of 300 kHz implies a Q factor of 1500/300 = 5. This cannot be achieved by the op-amp configuration shown because the maximum Q factor is limited to 0.5. You can try it of course, but you'll get just a sloppy band pass filter like this: -

It just won't deliver what you want. Bandwidth is approximately 3.53 MHz - 610 kHz = 2.92 MHz and centre frequency is 1.47 MHz hence, Q = 0.503.

A: To achieve a controlled bandwidth (here Q = 5), you'll need a different topology.
The inverting opamp topology ensures there is NO INTERACTION between the input series RC network and the output parallel RC network.
By the way, for a successful 1.5MHz active filter, you'll need an opamp with 20Mhz or 50MHz or 100MHz Unity Gain Band Width.
Walt Jung discussed this, decades ago, explaining the stop_band attenuation requires accurate cancellation of charges. To achieve accuracy, the opamp must have lots of amplification at the high (stop_band) frequencies.
If you want -40dB at 100MHz, you'll need a gain of 100X (+40dB) at 100MHz inside the opamp.
Even the topology you are using will demonstrate this demand.
Change the opamp UGBW, and notice how the high_frequency attention is directly affected by that change.


text:
Q: Reverse proxy replace folder with subdomain? I'm trying to expose Jenkins build status externally via Nginx reverse proxy.  I have created a subdomain buildstatus.ourcompany.com, but I don't want the url to be buildstatus.ourcompany.com/buildstatus/icon?... so I'm trying the following, without luck:
server {
    listen              80;
    server_name         buildstatus.company.com;
    location / {
        proxy_pass      $scheme://192.168.1.5:8080/buildStatus/;
    }
}

This results in the following error when I visit buildstatus.companyname.com/icon?job=projectname:

HTTP ERROR 404 Not Found
URI:  /buildStatus/
STATUS:   404
MESSAGE:  Not Found
SERVLET:  Stapler

I have confirmed that visiting 192.168.1.5/buildStatus/icon?job=projectname works as expected.
I tried a couple other things, including one that used url_rewrite, but just got other errors.
How can I have buildstatus.companyname.com/icon?job=projectname produce the same result as 192.168.1.5/buildStatus/icon?job=projectname?

A: Your configuration sends all requests to $scheme://192.168.1.5:8080/buildStatus/ URL.
You need to use
proxy_pass $scheme://192.168.1.5:8080/buildStatus$request_uri;

to add the original URI to the upstream request.


text:
Q: Same div height with Flex not working I'm working in a software with angularjs and bootstrap.
I need the <divs class="well"> have the same height, but they have dinamical information, so I cannot know the height.
I've found this example with flex:
http://www.bootply.com/126437
But It does'nt work for me.
This is my tpl.html code:

TOP 10 ARTÍCULOS - Anual

                            {{entry.CONCEPTO}}
                            {{entry.FCT_DESCUENTO | number}}€

BOTTOM 10 ARTíCULOS - Anual

                            {{entry.CONCEPTO}}
                            {{entry.FCT_DESCUENTO | number}}€

And this is the css code:
    div#salesdashboard {
        color: #a6a6a6;
        background-color: #292929;
        /* background-color: rgb(51, 51, 51); */

    .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
      position: relative;
      min-height: 1px;
      padding-left: 2px;
      padding-right: 2px;
    }

    .bgcolorgrey {
     background-color: rgb(51, 51, 51);
     outline: 3px solid #808080;
    }

    .tdlightblue {
        color: #538dd5;
    }

    .tdsweetblue {
      color: #b7dee8;
    }

    .tdlightgreen {
        color: #5c863d;
    }

    .tdgrayyear {
        color: #808076;
    }

    .tdright {
        text-align: right !important;
    }

    button {
            appearance:none;
            -webkit-appearance:none;
            margin:0;
            border:0;
            width: 40px;
            height:40px;
            box-sizing:border-box;
            background: #4f81bd;
            color: white;
            font-weight:bold;
            font-size:20px;
             outline: none;
            &:active {
                box-shadow: inset 0 2px 2px rgba(0, 0, 0, 0.25);

           }
        }

    .table th, .table td {
        border-top: 0px  !important;
    }

    td.stretch {
        padding-top: 0px !important;
        padding-bottom: 0px !important;
    }

    .table tbody+tbody {
        border-top: 0px;
    }

    small {
        font-size: 80%;
    }

    .table > thead > tr > th,
    .table > tbody > tr > th,
    .table > tfoot > tr > th,
    .table > thead > tr > td,
    .table > tbody > tr > td,
    .table > tfoot > tr > td {
      padding: 5px;
    }

    .well {
        background-color: #3e3e3e;
        padding: 19px;
        margin-bottom: 5px;
        border: 1px solid #3e3e3e;
        /*-webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;*/
        /*-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
        -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
        box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);*/
      }

      .highonecolumn {
        min-height: 260px;
      }

      .hightwocolumn {
        min-height: 315px;
      }

       .highthreecolumn {
        min-height: 240px;
        height: 100%;
      }

     .row-flex, .row-flex {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
        display: flex;
        flex:1 1 auto;
    }

        .row-flex-wrap {
          -webkit-flex-flow: row wrap;
            align-content: flex-start;

 flex:0;
    }

    .row-flex > div[class*='col-'], .container-flex > div[class*='col-'] {
       margin:-.2px; /* hack adjust for wrapping */
    }

    .container-flex > div[class*='col-'] div,.row-flex > div[class*='col-'] div {
      width:100%;
    }

    .flex-col {
        display: flex;
        display: -webkit-flex;
        flex: 1 100%;
      flex-flow: column nowrap;
    }

    .flex-grow {
      display: flex;
        -webkit-flex: 2;
        flex: 2;
    }

    }

Thanks in advance.


text:
Q: Microsoft.EntityFrameworkCore.Relational namespace (using) won't resolve I'm using EF as my ORM, and I need to execute some raw SQL against my postgres DB, to offload some JSON (jsonb) processing.
I'm using EntityFramework Core 1.1.0, with the npgsql provider for postgres.  Per the latest docs on executing SQL, I need to use context.[entity].FromSql() - where FromSql is in the Microsoft.EntityFrameworkCore.Relational namespace.
So, I added that package via NuGet...  The screenshot shows the problem - the reference is added, but it won't resolve in my code:

I've tried uninstalling and reinstalling the Core SDK and VS developer tools (VS 2015).  Any help appreciated.
Edit, showing full reference:
Full reference screenshot

A:
Reference and namespace are different things. The
  RelationalQueryableExtensions class you are seeking is located in the
  showed referenced assembly under Microsoft.EntityFrameworkCore
  namespace.

@IvanStoev was correct.  The reference added the .FromSql extension to my entities after including the base Microsoft.EntityFrameworkCore namespace.


text:
Q: gtag.js user timing doesn't appear in report I created a web page, tracked with Google's gtag.js, and I added a timing event using the syntax as per docs:
gtag('event', 'timing complete', {
  'name' : 'staring_blankly_into_space',
  'value' : 3549
});

The event is fired and sent properly.
When I look at my Analytics' reports:

*

*there is no trace of my time-tracking events in the User Timings section,

*I can find them in the Events section with:

Event category -> general,
Event Action -> timing complete,
Event Label -> not set
No trace of the 'name' field to be found.
Any insight on this? (I could try and use the 'event_label' field to set my timing description, but it's not how it's supposed to work.)

A: Your code should be (with underscore, see documentation):
gtag('event', 'timing_complete', {
  'name' : 'staring_blankly_into_space',
  'value' : 3549
});


text:
Q: how marge each value from the same array onto each key I have this array and I can't figure out how to dissect it and get it to built onto itself.
I have compiled my array to what I think might be the easiest to keep track of:
Array
(
    [domain.com] => Array
        (
            [dev] => Array
                (
                    [path] => /var/www/config/
                    [ini] => Array
                        (
                            [0] => db
                            [1] => common
                        )

                )

            [theme] => Array
                (
                    [path] => /var/ww/themes/
                    [ini] => theme
                )

        )

)

My whole thing is that I want to make a helper class to parse ini files. So I have through a couple of methods been able to build my array like above.
My end goal is have something like this parse_ini_file($ini[$domain][$nick][path] . $ini[$domain][$nick][ini] . ".ini", true)
where $nick is either 'dev' or 'theme' its just a way for me to distinguish paths and ini that belong together.
I have tried to do a foreach loop through each key value pair but I'm stuck on the fact that one of my values holds an array.
foreach (self::$ini[$domain] as $k => $v) {
    //if (self::$ini[$domina][$nick]['path'][$k] === self::$ini[$domain][$nick]['ini'][$k])
        foreach (self::$ini[$domain][$k] as $i => $l) {

            foreach ($l as $m => $n)
                //if (!is_array($i)) {

                   // (strlen($i) - 1 === '/' ? $i : $i . '/');
                    echo $n;
                    //self::$built = parse_ini_file($i . $j, true);
                //}
            }
}

It may seem like a mess, but i didn't bother with making meaningful variable names until I am able to make a solid code block. But In my attempt I have done a foreach loop through the $domain array to extract each $nick from there I thought doing another foreach to then break it down to get the path and ini key => values to then built the parse ini file function. But like I said, one of my ini key's holds an array so I'm not sure how to loop through that while still being able to parse an ini file and not overwriting the holder variable $built
Any help would really be appreciated!

A: You must first go and read about recursion. Just type the word into Google or even Wikipedia, you'll get the idea. Or just look for array_merge and array_merge_recursive at http://php.net, that's what you need. But first read about recursion anyway, you should know such basic things if you are going to write code further.


text:
Q: Do I need to use using pattern for Font, Brush etc When programming with GDI+, do I need to stick to using pattern to all kinds of objects like Brush, Font, it can make code very cluttered.
Any suggestions?

A: Yes, you should do that for all (IDisposable) objects that  you create.
The exceptions are the stock objects (Brushes.Blue, Pens.Black, e.Graphics, ...) because you don't create them.

it can make code very cluttered.

using is not as cluttered as a full try/finally. Note that you can economize the nesting:
using (Pen p = ...)
using (Brush b = ...)
{
   // draw with p and b
}

But if the choice is between cluttered code or the possibility of the program failing, is there really a choice?

A: Yes, you should. These objects could contain unmanaged resources (e.g., GDI+ handles) that need to be disposed of properly. So, either use a using block or wrap everything thing in a try / finally statement where in the finally block you invoke IDisposable.Dipose.
Please see these previous answers on this topic:
What Happens if I Don't Call Dispose
Wrapping MemoryStream in a using

A: If you created the brush using new you should dispose of it.
If you got the brush from the Brushes collection, do not dispose of it. See the remarks section of http://msdn.microsoft.com/en-us/library/system.drawing.brushes.aspx for more info.
The same holds true of fonts, if you created it with new, dispose of it. If you got it from something else, look at the documentation to see if you should dispose if it or not.

A: Yes, you have to.
Alternative is using default brushes and fonts such as Brushes.Black, ...


text:
Q: Ruby rails - how to find_by multiple options? I want to find records based on more than one parameters. And those parameters are of mupltiple options.
As "SELECT something FROM mytable WHERE user_name="xyz" and status=("Active" OR "Deleted")

How do I translate this to rails statement?
Person.find_by_user_name_and_status(user_name, status) # this doesn't take the OR operator

A: I can't test it right now, but did you try this?
Person.find_all_by_user_name_and_status(user_name, ["active", "deleted"])

if the above does not work, this should...
Person.where(:user_name => "xyz", :status => ["active", "deleted"])
# translates to:
# "select * from persons where username = 'xyz' and status in ('active', 'deleted')"

You should take a look into the Rails Guide for Active Record: http://guides.rubyonrails.org/active_record_querying.html


text:
Q: How can I center component with Flexbox with "fixed width" I´m making my component with the next code (App.component, the highest parent):
app.component.html

    <app-feed></app-feed>

app.component.css
.wrapper_flex {
    display: flex;
    justify-content: center;
    max-width: 100%;
    min-width: 0;
}

This is my "app-feed":
feed.component.html

Inicio

        <app-tweet [division]="true" [tweet]=tweet [retweets]="retweets" [likes]="likes" *ngFor="let tweet of tweets"></app-tweet>

feed.component.css
.container {
    display: flex;
    width: 100%;
    flex-direction: column;
    background-color: red;
}

.header {
    box-sizing: border-box;
    padding: 0 16px 16px 16px;
}

But when I refresh the page, the container moves a little.
How can I can make my component "Feed" stays in the center of my flexbox without moving, stay fixed (with a fixed width)
Live demo:
https://gifyu.com/image/Sw9fN
Buf if i remove the "h4" tag in feed.component.html, the container not moves, as i want to expect from the another approach.
Expected result (with h1 tag):
https://gifyu.com/image/Sw9fK
I´m using Angular 11

A: html {
    width: 100%;
    overflow-y: scroll;
}

The initial shifting can be prevented
Found out that the problem happens when the page has no scrollbar but you expand some element and the browser shows the scrollbar.

A: {

          <app-feed>

                    hello

        <app-tweet [division]="true" [tweet]=tweet [retweets]="retweets" [likes]="likes" *ngFor="let tweet of tweets"></app-tweet>

hello this is Ravi

          </app-feed>

}
using this code you can edit your post as like in link(which is sended by you)
.wrapper_flex {
    display: flex;
    justify-content: center;
    max-width: 100%;
    min-width: 0;
}
.container {
    display: sticky;
    width: 100%;
    color: white;
    background-color: red;
}


text:
Q: Add array values into map using javascript? I have an array value as a with key:value pair. I wanted to map the same key array values as below format:
Expected Output: [abc: 1],[def:2,42,40]

Please find my code below:
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
    array_keys.push(key);
    array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);

It returns the values as
My output : [abc:def] [1,40]

Any help on this?

A: You can achieve something like what you want if you play around with your initial data structure:
Have an array of objects:
var a = [{abc: 1}, {def: 2}, {def: 42}, {def: 40}];

Set up a new object
var o = {};

And then loop over the data. For each object: if the key doesn't exist in o, the output object, add it and set its value to an array, otherwise just push the value of the object to the array.
for (var i = 0, l = a.length; i < l; i++) {
  var key = Object.keys(a[i]);
  if (!o[key]) { o[key] = []; }
  o[key].push(a[i][key]);
}

And you end up with an object the values of which are arrays:
console.log(o); // {abc: [1], def: [2,42,40] }

Demo

A: var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
This is not possible. Object keys must be unique in javascript, so you can't add 3 different items with the same key ("def"). If you define multiple elements with the same key, at least chrome will take the last added value.
So answering your question: With the input provided there is no way to get you Expected output.


text:
Q: Android NPE TypeFace I set a font from the assets folder for each present the Activity button, I do not understand why I get a NPE at line 56 which is this:pswET.setTypeface(tf);where am I wrong?
04-25 18:18:49.983: E/AndroidRuntime(1853): Caused by: java.lang.NullPointerException
    enter code here
    -25 18:18:49.983: E/AndroidRuntime(1853):   at main.Login.onCreate(Login.java:56)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences sharedPrefs = getSharedPreferences("SharedPrefName", MODE_PRIVATE);
    boolean value;
    String name = getPackageName() + "_PREFERENCES";
    SharedPreferences sp = getSharedPreferences(name, MODE_PRIVATE);
    //control if there is no password
    if (!sp.contains(Util.PREF_PSW) || "".equals(sp.getString(Util.PREF_PSW, null))) {

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
        //check if the key is stored yes / no for the password
    } if (value = sharedPrefs.getBoolean("check", true)) {
        setContentView(R.layout.tastiera_password);
    }else {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
    Typeface tf=Typeface.createFromAsset(getAssets(),"roboto.ttf");
    pswET = (TextView) findViewById(R.id.psw);
    pswET.setTypeface(tf);
    bb1 = (Button) findViewById(R.id.b1);
    bb1.setTypeface(tf);
    bb2 = (Button) findViewById(R.id.b2);
    bb2.setTypeface(tf);
    bb3 = (Button) findViewById(R.id.b3);
    bb3.setTypeface(tf);
    bb4 = (Button) findViewById(R.id.b4);
    bb4.setTypeface(tf);
    bb5 = (Button) findViewById(R.id.b5);
    bb5.setTypeface(tf);
    bb6 = (Button) findViewById(R.id.b6);
    bb6.setTypeface(tf);
    bb7 = (Button) findViewById(R.id.b7);
    bb7.setTypeface(tf);
    bb8 = (Button) findViewById(R.id.b8);
    bb8.setTypeface(tf);
    bb9 = (Button) findViewById(R.id.b9);
    bb9.setTypeface(tf);
    bb0 = (Button) findViewById(R.id.b0);
    bb0.setTypeface(tf);
      // Set the listener for all the buttons
    int numberButtons[] = { R.id.b1, R.id.b2, R.id.b3,
      R.id.b4, R.id.b5, R.id.b6, R.id.b7,
      R.id.b8, R.id.b9, R.id.b0
    };
    NumberButtonClickListener numberClickListener = new NumberButtonClickListener();
    for(int id : numberButtons) {
     View v = findViewById(id);
     v.setOnClickListener(numberClickListener);
    }
    }
private class NumberButtonClickListener implements OnClickListener {
    @Override
    public void onClick(View v)  {
        String text = (String) ((Button)v).getText();

            setCurrentString(getCurrentString()+text);

    }
     public void setCurrentString(String s) {
            currentString = s;
            pswET.setText(s);
        }
        public String getCurrentString() {
            return currentString;
        }

}

A: Your findViewById failed, either because you didn't set the content view or because you use an id that doesn't exist.  Remember that finish() does not end execution of the function-  to do that you need to return, so if you go into that branch of your if/else you'll never have sent a content view and findViewById will always return null.