text:
Q: Should repositories be properties on the unit of work when using Entity Framework? I have scoured the web looking for a good implementation of the Repository/Unit of Work pattern using Entity Framework. Everything I've come across is either tightly coupled at some point in the abstraction or assumes that the DbContext used by the Unit of Work and Repositories is shared and should live for the entire HTTP request (instance per request via dependency injection).
For example, assuming you are consuming repositories from the service layer, a service constructor might look like this:
public DirectoryService(IUnitOfWork unitOfWork, ICountryRepository countryRepo, IProvinceRepository provinceRepo)
{
    /* set member variables... */
}

The unit of work constructor might look like:
public UnitOfWork(IDbContext context)
{
    _context = context;
}

And a repository constructor might look like:
CountryRepository(IDbContext context)
{
    _context = context;
}

This solution makes the blind assumption that the Dependency injection is setting up the Unit of Work and Repositories to share the same IDbContext using instance per request. Is that really a safe assumption to make?
If you are using dependency injection with instance per request, the same IDbContext will be injected into multiple units of work. The unit of work is no longer atomic, is it? I might have pending changes in one service that are then committed in another service because the context is shared across multiple units of work.
To me it seems to make more sense to set up a IDbContextFactory and get a fresh database context with each unit of work.
public interface IDbContextFactory
{
    IDbContext OpenContext();
}

public class UnitOfWork
{
    private IDbContextFactory _factory;
    private IDbContext _context;

    UnitOfWork(IDbContextFactory factory)
    {
        _factory = factory;
    }

    internal IDbContext Context
    {
        get { return _context ?? (_context = _factory.OpenContext()); }
    }
}

The problem then becomes, how do I make my Unit of Work implementation available to the injected repositories? I don't want to assume instance per request because then I'm right back in the same boat I started in.
The only thing I can think of is to follow Entity Framework's lead and make the repositories (IDbSet<T>) part of the unit of work (DbContext).
So then I might have units of work that look like this:
public class DirectoryUnitOfWork : IDirectoryUnitOfWork
{
    private IDbContextFactory _factory;
    private IDbContext _context;

    public DirectoryUnitOfWork(IDbContextFactory factory)
    {
        _factory = factory;
    }

    protected IDbContext Context
    {
        get { return _context ?? (_context = _factory.OpenContext()); }
    }

    public ICountryRepository CountryRepository
    {
        get { return _countryRepo ?? (_countryRepo = new CountryRepository(Context)); }
    }

    public IProvinceRepository ProvinceRepository
    {
        get { return _provinceRepo ?? (_provinceRepo = new ProvinceRepository(Context)); }
    }

    void Commit()
    {
        Context.SaveChanges();
    }
}

Then my Directory service starts to look like this
public class DirectoryService : IDirectoryService
{
    private IDirectoryUnitOfWork _unitOfWork;

    public DirectoryService(IDirectoryUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public GetCountry(int id)
    {
        return _unitOfWork.CountryRepository.GetById(id);
    }

    public GetProvince(int id)
    {
        return _unitOfWork.ProvinceRepository.GetById(id);
    }

    public void AddProvince(Province province)
    {
        _unitOfWork.ProvinceRepository.Create(province);
        Country country = GetCountry(province.CountryId);
        country.NumberOfProvinces++; // Update aggregate count
        _unitOfWork.Commit();
    }

    /* ... and so on ... */
}

It seems like a lot of work, but using this method leaves everything loosely coupled and unit testable. Am I missing an easier way, or is this a good way to do it if I am going to abstract away Entity Framework?

A: You should never abstract an ORM (itself an abstraction), but you should abstract the Persistence. The only UoW I'm using is a db transaction and that's a persistence detail. You don't need to use UoW and Repository together. You should think if you really need all this stuff.
Personally, I'm using the repository by default because Persistence is the last thing I do in an app. I don't care about patterns per se , I do care about decoupling my BL or the UI from DAL. Your upper layers (everything except DAL, which is the lowest layer from a dependency point of view) should always know about an abstraction, so that you can go as wild as you want in the DAL implementation.
One trick a lot of devs don't know is that design patterns (especially architectural ones) should be treated as a high level principle first and as a technical know-how second. Simply put, the thing that matters the most is the benefit a pattern is trying to achieve (the principle, the bigger picture), not its actual implementation (the "low level" details).
Ask yourself why should the BL know about a UoW in the first place. The BL only knows about an abstraction dealing with business objects. And you never work with the whole BL as once, you're always in a specific BL context. Your DirectoryService seems to be doing way to much for its own good. Updating stats doesn't look like it belongs to the same context as adding a new Province. Also why do you need UoW for queries?
One mistake I see a lot is devs rushing to write whatever code (with a design pattern attached) when they aren't doing the most important part: the design itself. When you have the improper design, problems appear and you start looking for workarounds. One of them is this UoW with Repository properties, which require a high layer like BL to know more than business concerns. Now the BL needs to know that you're using a UoW, a lower level pattern which is great for the DAL, not so great for the BL.
Btw, UoW never makes sense for quering as you're dealing with a 'read' situation, UoW is only for 'writes'. I don't mention EF or any ORM because they don't really matter, your BL service (Directory Service) is already corrupted by an infrastructural detail required by improper design. Note that sometimes you do need to compromise in order to implement a solution, but this is not the case.
Proper design means you know about your bounded context (yeah, DDD concept you can apply it regardless how much DDD you want to do) and don't put everything that might use the same data in one place. You have specific contexts for use cases and counting provinces (a presentation/reporting detail) is really a different use case than adding Province.
Adding the province and then publishing an event which signals to a handler to update stats is a more elegant, maintainable solution. No UoW required either.
Your code would look like this
public class DirectoryService : IDirectoryService
{
     public DirectoryService(IProvinceRepository repo, IDispatchMessage bus)
     {
       //assign fields
     }

      /* other stuff */

      //maybe province is an input model which is used by the service to create a business Province?
      public void AddProvince(Province province)
     {

        _repo.Save(province);
        _bus.Publish( new ProvinceCreated(province));
     }
}

  public class StatsUpdater:ISubscribeTo<ProvinceCreated> /* and other stat trigger events */
   {
       public void Handle(ProvinceCreated evnt)
       {
              //update stats here
       }
   }

In a way it simplifies things, in other way you might thing it complicates stuff. Actually, this is a maintainable approach, because the stats updater can subscribe to many events but the logic stays in one class only. And the DirectoryService does only the things that are assumed it does (what part of the name AddProvince hints you that the method also updates stats?).
In conclusion, you need to design the BL better before rushing to complicate your life with UoW, DbContext, Repositories as properties etc

A:
or assumes that the DbContext used by the Unit of Work and Repositories is shared and should live for the entire HTTP request

This is clearly wrong. Assuming that the context is shared between the UoW and Repositories doesn't mean that the context lifetime should depend on the HTTP request. Rather - you can create new instances of the context and the UoW that use it whenever you want. This is only a convenience to have a default UoW that lives for the HTTP request but creating new, local units of work could be handy.
On the other hand, if repositories are exposed from the UoW:
public class UnitOfWork
{
    ...

    public IUserRepository UserRepo
    {
        get { ... }
    }

    public IAccountRepository AccountRepo
    {
        get { ... }
    }

then not sharing the same context between repos could have unexpected results:
 UoW uow = ....

 var u1 = uow.User.FirstOrDefault( u => u.ID == 5 );
 var u2 = uow.Account.FirstOrDefault( a => a.ID_USER == 5 ).User;

You would definitely expect these two to return the same instance of the user of the id 5 and what's more, sharing the same context would mean that the second query could retrieve the user from the 1st level cache. On the other hand, two different contexts for two repos means that you get two different instances.
This also means that this would not be possible
 var u1 = uow.User.FirstOrDefault( u => u.ID == 5 );
 var a1 = uow.Account.FirstOrDefault( a => a.ID == 177 );

 a1.User = u1; // oops!

as mixing entites from different contexts would just raise an exception. But the above scenario is a common one!
The conclusion from these observations is that you should share the context between repos. But, if you need a fresh instance, you just create a local, fresh instance of the context, inject it into the UoW, from where it gets injected into repos, and dispose it at will.


text:
Q: How to open excel file using JavaScript code without using ActiveX control? How to open an Excel document using JavaScript code and without using an ActiveX control object like:
var myApp = new ActiveXObject("Excel.Application");
myApp.workbooks.open("test.xls");

A: I tried below option and it worked. Just prepend ms-excel:ofe|u before the url of xlsx file. It works in IE, Chrome other browsers I have not tested. This is what Microsoft One Drive online portal uses for opening encrypted xlxs files on client machines.
<a onclick="window.open('ms-excel:ofe|u|http://localhost/iis-server/test.xlsx')"> Open Excel </a>

A: I don't think this is possible.  JavaScript, when running in the browser, should be sandboxed to the browser's process and not able to launch other applications.
You might try relying on the browser knowing that .XLS files are opened by Excel and have it change window.location to a URL that is an Excel file.  But the user would have had to set up their browser and tell it that Excel files are opened by Excel and, yes, when I go to an Excel file, please open it in Excel rather than saving it to disk.

A: It's possible to open .xlsx files with Javascript because they are ZIP packages. This has been experimented with XForms: http://www.w3.org/community/xformsusers/2012/12/19/editing-zip-with-xforms/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting proper 'this' value in tippy.js When a tippy.js
tooltip is triggered, I want to be able to get "this" from it.
I've tried:
tippy(".sampleID",{
    arrow:true,
    placement: "bottom",
  content(reference) {
    const title = reference.getAttribute('title');
    var tid=$(this).attr("id"); // is undefined
    return title;
  }
});

How do I get "this" for class .sampleID that was hovered on?
JSFiddle

A: You can just use the reference provided as the argument, which refers to the current element matching .sampleID.
In your case I think you're trying to access the parent element though, which contains your id.
  tippy(".sampleID",{
    arrow:true,
    placement: "bottom",
    content(reference) {
      const title = reference.getAttribute('title');
      const tid = reference.parentElement.getAttribute('data-id');
      // jQuery: const tid = $(reference).parent().data('id');
      return title+"<br>"+tid;
    }
  });


text:
Q: Change language in UI on the fly Android I created an application with localized strings in Spanish and English, located at res/values (Spanish is default) and res/values-en. The application display the language as the system, but how can I change the application language separatedly of the system?
Any suggestion is welcome.

A: I think you should set Locale programatically
as explained here
https://stackoverflow.com/a/4986481/1531683


text:
Q: Is there a way to bind a specific column in a spreadsheet to a combobox in a GUI [VBA] I'm trying to use a for each loop to dynamically find which column a given populated combo box is pulling data from in an excel worksheet.  There can be more than one combobox searched (i.e find rows where cmb_year = 2018 and cmb_period = 6 and cmb_group = health.  the end goal is to search the raw data for one criteria then search that data (the one we just filtered) for the next criteria and so forth until all conditions are met.
I tried to use the property BoundColumn so the code would immediately recognize which column to look at to see if the information from the worksheet column matched the data in the combobox, but BoundColumn is a property that seems to only be used for multi-columned comboboxes.
If WorksheetExists("FilteredSheet") Then

Worksheets("FilteredSheet").Delete

Else

Dim wrksName As String
wrksName = "FilteredSheet"
Dim ws2 As Worksheet
Set ws2 = Worksheets.Add(Type:=xlWorksheet)
With ws2
    .Name = wrksName
End With

End If

Dim ws As Worksheet
Set ws = Worksheets("Sheet2")

Dim populatedBoxes As New Collection
'finds all combo boxes that are populated
Set populatedBoxes = GetPopulatedThings(Multipage1, "ComboBox")
Dim cb As MSForms.ComboBox
For Each cb In populatedBoxes
'attemps to loop through each combobox to search for values in it's corresponding column in the worksheet
    Call FilterSheet(ws, ws2, cb)
Next

End Sub

Private Function FilterSheet(wrks As Worksheet, pastewrks As Worksheet, cmb As ComboBox) As Worksheet

a = wrks.UsedRange.Rows(wrks.UsedRange.Rows.Count).Row

For i = 1 To a
    'tries to find the column in a given row that matches where the combobox was originally populated from
    If wrks.Cells(i, cmb.BoundColumn).Value = cmb.Value Then
        wrks.Rows(i).Copy
        pastewrks.Activate
        b = pastewrks.Cells(Rows.Count, 1).End(xlUp).Row
        pastewrks.Cells(b + 1, 1).Select
        ActiveSheet.Paste
        Worksheets(wrks).Activate
        'pastes to all matching values to a new worksheet
    End If
Next

Application.CutCopyMode = False

Set FilterSheet = pastewrks

End Function

I can't use boundcolumn in the for loop located in FilterSheet because when I change the boundcolumn property to anything more than 1, the value of the combobox becomes null (most likely due to it being a single column combobox)


text:
Q: Repositories not enabled on fresh boot - is this a problem? I recently created a 18.04.1 LTS Live USB. After setting it up, I noticed several repositories, including universe, were not enabled as they should be. I am aware that this is a known bug for 18.04.1 Subiquity-based Live Server Installer ISOs, however I have not seen any discussion regarding this for Desktop versions. As I am running Ubuntu to detect rootkits and possibly disinfection, is this a bug that I should be worried about? Prior to creating the live USB I ran checksum and no problems there.
For clarification, I am new to Ubuntu and Linux in general.

A: No, this is not an issue to be overly concerned about.
Your system will operate fine and you will only run into problems trying to install and update via the package manager.
The repositories are only used for updating and installing the packages on your machine via the internet. While your apt-get install commands will fail saying something about the packages not existing or found, you can still install and update via a USB storage device or Ethernet cable to another machine.
If you re-enable them permanently you are back to a normal system or you can script it to re-enable only when you want to update if you want to only update during specific times.
Or just disable automatic updates.
I was recently working on a project where this was actually part of the system design: all the base system repos were commented out and some custom update repositories were added in to update only the packages we wanted (not my design, just how it was set up before I got there).


text:
Q: Having some issues with ProgressDialog. cant make it appear Iam having some problems with the ProgressDialog in android. I thought it would be relatively easy to use but it turns out otherwise LOL. basically i have an Instance of progreesdialog in my activity "RegistrationActivity". I press a button and registration commences by showing a progressdialog when this button is pressed. this is all done on the UI thread.  below is my code which calls my presenter method which in turn calls a method in my mode, as Iam using MVP.
@Override
public void registerUser() {

    progdialog = new ProgressDialog(this);
    progdialog.setMessage("Loading...");
    progdialog.show();

    rpresenter.relayRegisterUser(emailedtxt.getText().toString(),
            passedtxt.getText().toString(), phoneedtxt.getText().toString());

}

I have a seperate thread set up in my model. In the model Iam currently faking the registration process by sleeping the thread for five seconds and using a handler to post a value back a value to the UI thread. below is the runnable i create and pass to my thread within the model "RegisterModel".
    private Runnable runnable = new Runnable() {
    @Override
    public void run() {

        //upload data to the server
                reghandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progress = 50;
                        regpresenter.updateUIProgress(progress);
                        Log.d("prog updated by :!!", String.valueOf(progress));
                    }
                });

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        reghandler.post(new Runnable() {
                            @Override
                            public void run() {
                                progress = 100;
                                regpresenter.updateUIProgress(progress);
                                Log.d("prog update 2 :!!", String.valueOf(progress));
                            }
                        });
        appstate.setRegistered(true);
    }
};

when i press the button I presumed the progressdialog would appear as it calls the registerUser() method. But it does not. updateUIProgress(progress) call my presenter. This in turn calls a method in my activity/view called UpdateProgress(). to which i post back the value of 100 after the thread in my model has slept for 5 seconds. this method is shown below.
@Override
public void updateProgress(int progress) {

    Log.d("increment progactivity:", String.valueOf(progress));
    progdialog.incrementProgressBy(progress);

    if(progress == 100)
        hideProgress();
 }

Upon recieving the progress value of 100 the "hideProgress()" method is called which is shown below. but as the progressdialog isnt appearing in the first place it doesnt do anything.
private void hideProgress()
{
    Log.d("hide prog called", "hide prg called");
    progdialog.dismiss();

}

everything to do with the progressdialog is on the UI thread so Iam not too sure what Iam doing wrong here. If anyone out there can help me id appreciate it. Thanks!
EDIT:
forgot to mention I fixed this issue! it was a silly error on my part but i used .join() on the thread which force the UI thread to wait for the registration thread to finish. therefore I was not seeing the progressdialog. oops!

A: Better to use AsyncTask.
In another cases you should post UI updates into UIThread. See that

A: Use Async Task
Try something like this..
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading..");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(false);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

class UpdateProgressbar extends AsyncTask<Void, String, Void> {

    // Show Progress Bar Dialog
    Context appContext = getApplicationContext();
    @SuppressWarnings("deprecation")
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);

        publishProgress("0");

    }

    @Override
    protected Void doInBackground(Void... result) {

        try {

            //your code
            //.........
            //.........

            publishProgress(""+(int)((count*100)/lenghtOfFile)); //update progress bar

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    // Update progress bar

   protected void onProgressUpdate(String... progress) {

        pDialog.setProgress(Integer.parseInt(progress[0]));

   }

     //Close the progress dialog

    @SuppressWarnings("deprecation")
    @Override
    protected void onPostExecute(Void result) {

        // dismiss the dialog
        dismissDialog(progress_bar_type);

    }

}


text:
Q: Need Sticky Header/Footer but CMS won't let me code in the body tag I work in an outdated content management system that doesn't give me access to the body tag. Is there any way to create a sticky footer and sticky header without using the body tag?

A: If you can put something in the head element, this should do it:
<script>
var myStickyHeader = document.createElement('div');
myStickyHeader.style.background = 'white';
myStickyHeader.style.position = 'fixed';
myStickyHeader.style.top = 0;
myStickyHeader.style.left = 0;
myStickyHeader.style.right = 0;
myStickyHeader.style.zIndex = 9999; // just in case
myStickyHeader.innerHTML = 'My sticky header';

document.body.addEventListener('load', function() {
    document.body.insertBefore(myStickyHeader, document.body.firstChild);
}, false);
</script>

switch myStickyHeader.style.top for myStickyHeader.style.bottom for a footer.


text:
Q: How to make dropdown jQuery work? I have this dropdown menu that work in jsFiddle when i test it but when i run it to my testing server, its not working like how it supposed to.
jsFiddle:
http://jsfiddle.net/cyberjo50/39bu8/2/
HTML
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

<button>Select Destinations</button>

Philadelphia
United States of America
Philippines
Long Destinations Names
Some Destination
Australia

Javascript
img_arrow = '';

$(function ()
{
var $window = $(window),
    $nav = $('nav'),
    $button = $('button');

$button.on('click', function ()
{
    $nav.slideToggle();
});

$window.on('resize', function ()
{
    if ($window.width() > 320)
    {
        $nav.show();
    }
});
});
$('#menu a').click(function(e){

$('button').html($(this).html() + img_arrow);

e.preventDefault();
});

Here is my test page:
http://t4fresponsivelandingpage.businesscatalyst.com/test.html#
Not sure why its not working on my test page. Its supposed to work like the one in Jsfiddle. the code from fiddle is exactly the one im using in my testing link.

A: You're running the click handler during page load instead of after it. $(function(){}) is shorthand for $(document).ready(). To fix the click issue, move the click handler assignment to inside the onDOMReady call:
$(function (){
    var $window = $(window),
        $nav = $('nav'),
        $button = $('button');

    $button.on('click', function (){
        $nav.slideToggle();
    });

    $window.on('resize', function (){
        if ($window.width() > 320){
            $nav.show();
        }
    });

    $('#menu a').click(function(e){
        $('button').html($(this).html() + img_arrow);

        e.preventDefault();
    });
});

http://jsfiddle.net/39bu8/4/


text:
Q: Android: dynamically create matrix of editText based on user input? I'm new to android development. I've noticed some similar questions but none of them really answered my question well enough that I could figure it out, or else they relied upon depreciated functions.
So far, I've created my main class. I want to open to a screen where the user inputs two numbers for the row and column length of a matrix they want to reduce
public class MainActivity extends AppCompatActivity {

public int numberOfRows;
public int numberOfColumns;

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

public void setRows(View v3) {
    EditText editTextRow = (EditText) findViewById(R.id.editText2);
    if ("".equals(editTextRow.getText())) {
    }
    else {
        numberOfRows = Integer.parseInt(editTextRow.getText().toString());
    }
}

public void setColumns(View v2) {
    EditText editTextCol = (EditText) findViewById(R.id.editText3);
   if ("".equals(editTextCol.getText())) {
        numberOfRows = Integer.parseInt(editTextCol.getText().toString());
    }
}

public void reduce(View view){
    if(numberOfRows != 0 && numberOfColumns != 0) {
    }
    else {
        Intent intent = new Intent(this, ReduceMatrix.class);
        Bundle bundle = new Bundle();
        bundle.putInt("rows", numberOfRows);
        bundle.putInt("cols", numberOfColumns);
        intent.putExtras(bundle);

        startActivity(intent);
    }
}

 }

I'm having trouble coming up with the next activity, where I want to dynamically create a matrix of editText...
public class ReduceMatrix extends AppCompatActivity {

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

    Intent passedIntent = getIntent();
    Bundle extras = passedIntent.getExtras();

    int rowNum = extras.getInt("rows");
    int colNum = extras.getInt("cols");

Could anyone explain how to go about doing this? I was thinking some sort of for loop, but I have a really hard time with the android layout. Should I be using tableLayout? or gridview? Whenever I have something like
    layout = new LinearLayout(this);

It tells me that my qualifier must be in an expression?

A: You need to add it programmatically. Here's my solution :
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent passedIntent = getIntent();
    Bundle extras = passedIntent.getExtras();

    EditText[][] editTexts = new EditText[rowNum][colNum];

    GridLayout gridLayout = new GridLayout(this);

    //define how many rows and columns to be used in the layout
    gridLayout.setRowCount(rowNum);
    gridLayout.setColumnCount(colNum);

    for (int i = 0; i < rowNum; i++) {
        for (int j = 0; j < colNum; j++) {
            editTexts[i][j] = new EditText(this);
            setPos(editTexts[i][j], i, j);
            gridLayout.addView(editTexts[i][j]);
        }
    }
    setContentView(gridLayout);
}

//putting the edit text according to row and column index
private void setPos(EditText editText, int row, int column) {
    GridLayout.LayoutParams param =new GridLayout.LayoutParams();
    param.width = 100;
    param.height = 100;
    param.setGravity(Gravity.CENTER);
    param.rowSpec = GridLayout.spec(row);
    param.columnSpec = GridLayout.spec(column);
    editText.setLayoutParams(param);
}

This will enable you to add EditText(s) dynamically.


text:
Q: Sending an argument to a prototype function I am trying to understand how to use a prototype with an array of objects in JavaScript.  I am trying to send an argument to each Person object by using a subscript because I was thinking of using a loop with an index.  With the current code I keep getting an error message that needsGlasses is not a function.
//class constructor
function Person (name, age, eyecolor) {
this.name = name;
this.age = age;
this.eyecolor = eyecolor;
}

//array of Person objects
var peopleArray =
[
new Person ("Abel", 16, blue),
new Person ("Barry", 17, brown),
new Person "Caine", 18, green),
];

//prototype
Person.prototype.needsGlasses=function(boolAnswer){
    if (boolAnswer ==1){
        console.log("Needs glasses.");
       }
    if (boolAnswer !=1){
        console.log("Does not need glasses.");
       }
 }

//when I try to send a '1' or '0' to an object in the array, I get an error.
peopleArray[0].needsGlasses(1);

A: You have syntax errors. To get your code working it may be defined as follows:
function Person (name, age, eyecolor) {
  this.name = name;
  this.age = age;
  this.eyecolor = eyecolor;
}
Person.prototype.needsGlasses= function(boolAnswer){
    if (boolAnswer ==1){
        console.log("Needs glasses.");
    } else {
        console.log("Does not need glasses.");
    }
}

var peopleArray =
[
  new Person ("Abel", 16, "#00f"),
  new Person ("Barry", 17, "#A52A2A"),
  new Person ("Caine", 18, "#f00"),
];

peopleArray[0].needsGlasses(1);

Furthermore, you have unnecessary if statements.
You can try to play with this code on JSBin

A: It works but you code was full of sytax errors.

function Person (name, age, eyecolor) {
  this.name = name;
  this.age = age;
  this.eyecolor = eyecolor;
}

//array of Person objects
var peopleArray =
[
  new Person ("Abel", 16, 'blue'),
  new Person ("Barry", 17, 'brown'),
  new Person ("Caine", 18, 'green')
];

//prototype
Person.prototype.needsGlasses = function (boolAnswer) {
  if (boolAnswer ==1) {
    console.log("Needs glasses.");
  } else {
    console.log("Does not need glasses.");
  }
}

//when I try to send a '1' or '0' to an object in the array, I get an error.
peopleArray[0].needsGlasses(1);


text:
Q: Post non-input fields in a form? This seems like a simple thing, and maybe I'm just not thinking straight today, but right now I don't see it: How do I post data from a form (in a PHP application) that is not an input field?
The reason I need this is I have a form where the user adds some information in input fields, and this should then update other values in the form based on what the user has entered (doing calculations on this input). This data should then on submit be posted, along with the input from the user.
I tried using form labels, but could not get it to work. For one I couldn't get the value of the form in the jQuery using either .val() or .text(). And I'm not sure if I could get the values of the label in the CodeIgniter function anyway. I also tried simple <p> tags with ids, but that didn't work. I guess it has to be an element with the name attribute...
I'm using a helper in CodeIgniter to get the form values, like so:
$this->input->post('user')

This works fine for input fields, but as explained I need it for non-input elements. Of course I could have input fields that I update in jQuery, but there's a risk that the users will think they should fill them in...
So how do you do it?

A: How about using <input name="user" type="hidden"> and use Jquery to store the value in there.

A: Why are you storing input information in non-user-interface elements? Anything you want to be POSTed should be in an input field. Labels are not input elements, they are, well, labels. They label things. What exactly are you doing that you think you can't use input fields? You can disable them, set them to read-only mode, and modify their values in a similar way that you'd modify the text in any other element.


text:
Q: Possible to make a Quiz with HTML/CSS only? I am currently studying math and thought of an idea, depending on if it is possible.
I want to add in let say 100 math equations, but only one question should be displayed at once until you type in the correct answer and click next.
Is this possible with HTML only or would I need other languages?
I will be running it locally so hiding answers in source code is not important.

A: This is not possible using HTML only as far as I know. Ideally you need a database where you store your questions, your users, their previous answers, the correctness of the answers and their overall performance. You would need to create a register/login screen using a server-side language. On the server you would need two core functionalities closely related to the question feature. The first is to randomize a question which was not asked yet, the other is to handle the answer of the user. A user would load the page, the question randomizer would run on the server and whenever the user answers a question, your client-side should send a POST request to the server with the answer to the question and handle the response of the server (display the next randomized question).
However, you might want a very quick solution before you implement the database. In that case you could store the questions in a Javascript array, on page load randomize the question, display it to the user and when the user answers the question, store the answer, display whether it was correct, add the question to another array storing answered questions and remove the item from the question array, then randomize again and display again. This is not an ideal solution, but can be a temporary quick solution to have some success before you start the longer solution.

A: If you want a basic approach, you can go with this:

var questions = [];
var loadedQuestions = [];
var questionPosition = 0;
var score = 0;

var question = {
  "title": "This is the title",
  "answers": [{
    "title": "This is not Correct",
    "correct": 0
  }, {
    "title": "This is correct",
    "correct": 1
  }, {
    "title": "This is not",
    "correct": 0
  }, {
    "title": "This either",
    "correct": 0
  }]

}
questions.push(question);
var question = {
  "title": "This is the second question",
  "answers": [{
    "title": "This is not Correct",
    "correct": 0
  }, {
    "title": "This is correct",
    "correct": 1
  }, {
    "title": "This is not",
    "correct": 0
  }, {
    "title": "This either",
    "correct": 0
  }]

}
questions.push(question);

var question = {
  "title": "This is the third",
  "answers": [{
    "title": "This is not Correct",
    "correct": 0
  }, {
    "title": "This is correct",
    "correct": 1
  }, {
    "title": "This is not",
    "correct": 0
  }, {
    "title": "This either",
    "correct": 0
  }]

}
questions.push(question);

function updateScore(result) {
  if(result){
    score++;
  }else{
    score--;
  }
  $("#score").text(score);
}

function answering() {
  var correct = $(this).data("correct");
  $(this).addClass(correct ? "correct" : "wrong");

  updateScore(correct);
}

function loadQuestions() {
  $.each(questions, function() {
    var question = $("

");
    question.addClass("question");

    var title = $("

");
    title.addClass("title");
    title.text(this.title);

    var answers = $("

");
    answers.addClass("answers");

    $.each(this.answers, function() {
      answer = $("

");
      answer.addClass("answer");
      answer.text(this.title);
      answers.append(answer);
    });

    question.append(title);
    question.append(answers);

    loadedQuestions.push(question);
  });
}

function displayQuestion() {
  $("#questions").empty();
  $("#questions").append(loadedQuestions[questionPosition]);
  $("li.answer").click(answering);
}

$(document).ready(function() {
  loadQuestions();
  displayQuestion();

  $("#next").click(function() {
    if (questionPosition < (loadedQuestions.length - 1)) {
      questionPosition++;
      displayQuestion();
    }
  });

  $("#prev").click(function() {
    if (questionPosition > 0) {
      questionPosition--;
      displayQuestion();
    }
  });
});
.correct {
  background-color: #61e02b;
  color: #FFF;
}

.wrong {
  background-color: #e34d45;
  color: #FFF;
}

The ultimate quiz

  This is a test. Please, click on the "next" o "prev" button to move across questions.

<button id="prev">Prev</button>
<button id="next">Next</button>

  Your score is:
  <spam id="score">0</spam>


text:
Q: How can i use .load function to insert content into different Div I am kind of a newbie to jQuery so sincere apologies if my question seems very superficial. I wanted to know how i can use buttons in one div to place content in another div when any one of the buttons is clicked on using jQuery. Each button of course will be loading its own content in the specific div that i want changed.
Thank you in anticipation

A: Following jquery can help
$('#buttonid').click(function(){
$('#div2id').load('page.html');
}

A: That's pretty simple:
$("#buttonA").on("click", function() {
    $("#theDiv").load("http://theUrl");
});

$("#buttonB").on("click", function() {
    $("#theDiv").load("http://theOtherUrl");
});

Replace #buttonA, #buttonB, #theDiv with your specific selectors.
A better way would be to use data attributes:
<button class="link-btn" data-url="http://theUrl">load A</button>
<button class="link-btn" data-url="http://theOtherUrl">load B</button>

And...
$(".link-btn").on("click", function() {
    $("#theDiv").load($(this).data("url"));
});

A: Here's the code:
$('#yourDivId').load('content.html');   // Your content source


text:
Q: Append items dynamically to ListView I am new to Dart and Flutter and try to append a new item to my ListView. I created a button that increments this.value but nothing happens. Am I missing an update call on the UI and is this even the correct approach?
Since I return the value of ListView.builder directly to the caller of build I am not sure how to get the list to add more items. Thanks a lot!
class MyList extends State<MyList> {

...
int value = 2;

@override
Widget build(BuildContext context) {
return ListView.builder(
    itemCount: this.value,
    itemBuilder: (context, index) => this._buildRow(index)
);

TL;DR: Is calling setState the correct way to trigger an UI update?

A: Calling setState is the correct way of triggering an UI update.
From the docs:

Calling setState notifies the framework that the internal state of
  this object has changed in a way that might impact the user interface
  in this subtree, which causes the framework to schedule a build for
  this State object.
If you just change the state directly without calling setState, the
  framework might not schedule a build and the user interface for this
  subtree might not be updated to reflect the new state.

Here is a small example of a ListView with a Button that appends items to it.
import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(home: MyList()));

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  int value = 2;

  _addItem() {
    setState(() {
      value = value + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("MyApp"),
      ),
      body: ListView.builder(
          itemCount: this.value,
          itemBuilder: (context, index) => this._buildRow(index)),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem,
        child: Icon(Icons.add),
      ),
    );
  }

  _buildRow(int index) {
    return Text("Item " + index.toString());
  }
}


text:
Q: How can I deploy my next js web application automatically from github to cpanel? I want to deploy my next js web application by Cpanel automatically from GitHub.
So, when I push any new code to github it should be automatically deployed by cpanel to my hosting.
I need to know the process for-

*

*Next js application

*React js application

Kindly guide me through this.
thank you


text:
Q: Some Contacts not showing up but are still stored in iPhone 4 I noticed today that several of my recent contacts are not in my contacts. However, I have been texting them and their info shows up when I go to contact from a text message or recent call.
When I am in my address book and go to groups only All Contacts is an option, and that's where they are not. How do I get them all back into my contact list?

A: Had a similar problem after doing a restore on my iPhone 4.  I just tried something that seemed to work.  Went to contacts and selected groups.  Selected Hide All Contacts and immediately selected Show All Contacts again.  The missing contacts re-appeared along with duplicate entries for the one's I recreated.

A: I just went to 'Settings'> 'Mail, Contacts, Calendars'> scroll down to 'Contacts> select 'Import SIM Contacts'. All my contacts were restored to my Address Book.

A: Go to Contacts, then click on Groups and make sure the "all iCloud" section is selected.

A: Have you already tried to reboot your iPhone? (Push and hold the power button for 5 seconds, then slide to power off. Once your iPhone is shut down hold the power button for a few seconds to restart your iPhone)
That might solve you issue.
If that doesn't solve your contact list issue go to 'settings' > 'Mail, Contacts, Calendar' > scroll down to 'Contacts' and play with the 'Sort Order', 'Display Order' and My Info' options. That might do the trick.

A: It looks like you're not the only one suffering from this issue (I know this topic is from 2010, but is describes perfectly your situation). I guess you've added those contacts to you list by using a 3th party app.
As of today, there isn't a fix for this issue, so I suggest you only add contacts by using the official contact app on your iPhone and add the ones not listed in your contact list manually.

A: I made an an app which should help with this. Here's how to use it.

*

*download contact duster from iTunes Store which is free

*go to settings

*In settings go to contact duster and prefix your country code for eg +91 for India

*go to contact duster, it will prompt you to apply country code to all your contacts. Click on sure. Please backup ur contacts before this process.

*check your messages and call register as in recent calls. Your contacts names will be displayed.

A: Navigate to Settings > iCloud then turn Contacts off. It this was causing the problem you will notice that your contacts come back. Then go back to the same place (Settings > iCloud) then turn Contacts back on then select Merge.

A: I actually figured it out playing with it today, the contact would not appear in my contacts but if I searched my phone they would appear, so if I couldn't find them within contacts...I would first search for the contact...open it...and then edit the contact, then they would show up...
Seemed strange but it works and new contacts are now being added as normal, must have been a glitch at one point as all the contacts that I cannot see were added in about a 2 month span.


text:
Q: Missing custom headers in webview' goBack() requests I'm adding custom headers to all webview's requests by calling:
webview.loadUrl(url, myHeaders)

and overloading webview client's:
shouldOverrideUrlLoading()

When browsing and going deep-linking, all requests have custom headers but all webview's goBack() requests don't. shouldOverrideUrlLoading() is not invoked when goBack() is called.
I'm wondering how to ensure that custom headers are always included in goBack() requests?

A: Normally WebView re-sends extra headers when going back in navigation history, I have briefly tested that and it seems to work. However, there are several moments that can be confusing, so I would advise to re-check what is really happening in your scenario:

*

*WebView may not even re-contact the server in order to load the page when you call goBack() -- it can just restore the page from the cache. In order to force re-querying the page from the server, the latter must disable caching of the page using cache-control header: cache-control: no-cache,no-store. And in that case, if the page was loaded via loadUrl with extra headers, these headers will be re-sent.

*If the user clicks a link on a page loaded with extra headers, these headers are not "inherited" by the page you are navigating to (the same is true for navigations done by JS code). Thus, if you are calling goBack and the previous page has been loaded from a user click, it will not have any extra headers of the starting page loaded via loadUrl.

*shouldOverrideUrlLoading is only called for loads caused by user or server actions, not for loads initiated via WebView API methods, like loadUrl or goBack, because the app already knows that it is about to navigate WebView somewhere. For example, if you are loading google.com via loadUrl, the original navigation will not be intercepted by shouldOverrideUrlLoading, but the redirect that the server does, e.g. to the https page, will be.
Hope it helps. If you still suspect WebView in not re-sending extra headers, I would strongly advise preparing a simple repro case that would demonstrate it.


text:
Q: using if() in php to see if date in array is equal to date stored in variable I have the following code in my index.php:
$d1 = date('Y-m-d', strtotime("-4 days"));
$newrecord = [];
  for($i = 1; $i <= sizeof($methods); $i++) {
      $keys = ["Email", "FirstName", "LastName"];
      $newrecord[$i][0] = $methods[$i][1];
      $newrecord[$i][1] = $methods[$i][2];
      $newrecord[$i][2] = $methods[$i][3];
      $newrecord[$i][3] = explode(" ", $methods[$i][6]);
      $newrecord[$i][3] = $newrecord[$i][3][0];

      $newrecord[$i][4] = $d1;
      if ($newrecord[$i][3] == $newrecord[$i][4]){
        $newrecord[$i][5] = "New Entry";
      }
}

I am expecting to loop through my entire $methods array, and after assigning new values to each of my $newrecord[$i] entries, I need to check whether the value of $newrecord[$i][3] equals the date of 4 days ago.
The problem is that it doesn't look like the if() check is successful, because none of my arrays contain the [5] => "New Entry" array component.
However, I know that there are 120 instances in the array when these do equal each other. For instance:

[23] => Array ( [3] => 2018-07-15 [4] => 2018-07-15 [Email] =>
  me@example.com [FirstName] => John [LastName] => Doe )

Returns for record [23] when I print the output of all the arrays, and there are 120 of them that are like this in total (out of around 8000).
This same thing happens when i just put if($newrecord[$i][3] == $d1) in the if statement.
Any advice on what I'm missing? I appreciate the help.
Note: the values for ["Email"] ["FirstName"] ["LastName"] occur later in the function, this is just a snippet of it to keep it more concise.

A: The reason the if() statement isn't working is because the true value of the date within the array was not the same as was returned with the $d1 variable.
This was discovered when I clicked "view page source" on my Chrome browser and inspected the arrays being returned by the var_dump call. Specifically, there were spaces between the characters (i.e. 2018-07-15 became 2 0 1 8 - 0 5 - 0 6).
Further investigation revealed little black diamonds with "?" inside them in the CSV file so I'm assuming the character code was wrong when importing these.
The solution, after much trial and error, was to use preg_replace() in the following format:
$newrecord[$i][3] = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newrecord[$i][3]);

Where /[\x00-\x1F\x7F-\xFF]/ is the search for unwanted characters, I took from this question
When ran, the if() statement executed just fine.


text:
Q: My Javascript code for form validation won't work I created simple form validation but nothing is working. Below is my code for the form and javascript. I took it right from a textbook. I have a submit button. When I click it nothing happens. I am using an external .js file and did include the link the  section on the page. I would really appreciate your input.
<form name="reservation" onsubmit="return validate(this);">
<fieldset>
<legend>Reservation</legend>

Name*

<input type="text" name="txtName" id="txtName" size="60">

Date and Time*

<input type="text" id="txtDate" name="txtDate" size="40">

Party Size*

<input type="text" id="txtParty" name="txtParty" size="20">

Phone*

<input type="text" id="txtPhone" name="txtPhone" size="40">

Email*

<input type="text" id="txtEmail" name="txtEmail" size="60">

<input type="submit" id="button" value="Submit"/>

*=required

</fieldset>
</form>

Javascript:
function validate(form){

    var returnValue=true;

    var name = form.txtName.value;
    var date = form.txtDate.value;
    var party = form.txtParty.value;
    var phone = form.txtPhone.value;
    var email = form.txtEmail.value;

        if (name=="") {
        returnValue = false;
        alert("Name is a required field");
        document.reservation.txtName.focus();
    }

    if (date=="") {
        returnValue = false;
        alert("Date is a required field");
        reservation.txtName.focus();
    }

    if (party=="") {
        returnValue = false;
        alert("Party Size is a required field");
        document.reservation.txtName.focus();
    }

    if (phone=="") {
        returnValue = false;
        alert("Phone is a required field");
        document.reservation.txtName.focus();
    }

    if (email=="") {
        returnValue = false;
        alert("Email is a required field");
        document.reservation.txtName.focus();
    }
    alert("Thank for providing your information.\n
    We will get back you as soon as possible.");
    return returnValue;
}

A: I think you should look into using jQuery It's so much more effective and easy to use! You should also look into using else if() statements.
var name = $('#txtName').val();
var email = $('#txtEmail').val();
    if(name == ""){ alert("Please fill in the name field");
        $('#txtName').focus();
        return false;
     }
     else if(email == ""){ alert("Please fill in the email field");
     $('#txtName').focus();
     return false;
     }else{
      alert("All good");
      return true;
    }


text:
Q: Taking partial derivatives to the thousand times. I was just wondering how I would solve a question like this?
$$\frac {\partial^{1000}f}{\partial x^{500}\partial y^{500}}$$ Where the partial derivative is $$e^{2x-4/y}-y^{12}x^{21}$$

A: As said by eyeballfrog, the derivatives on $x$ are easy as the first term is separable and the derivatives of the exponential are immediate. The polynomial term quickly vanishes.
On the opposite the derivatives of $e^{-4/y}$ on $y$ are problematic as they involve a complex recurrence relation on the coefficients. They are of the form
$$P\left(\frac1y\right)e^{-4/y}$$ where $P$ is a polynomial with terms of degree $501$ to $1000$ and integer coefficients.

A: Considering
$$f_n=\frac{\partial ^n\left(e^{-\frac{a}{y}}\right)}{\partial y^n}$$ we have
$$\frac 1a\,{y^{2n}}\, e^{\frac{a}{y}} f_n=a^{n-1}+ P_{n-1}(y)$$
The first polynomials are listed below
$$\left(
\begin{array}{cc}
 1 & 0 \\
 2 & -2 y \\
 3 & -6 a y+6 y^2 \\
 4 & -12 a^2 y+36 a y^2-24 y^3 \\
 5 & -20 a^3 y+120 a^2 y^2-240 a y^3+120 y^4 \\
 6 & -30 a^4 y+300 a^3 y^2-1200 a^2 y^3+1800 a y^4-720 y^5 \\
 7 & -42 a^5 y+630 a^4 y^2-4200 a^3 y^3+12600 a^2 y^4-15120 a y^5+5040
   y^6
\end{array}
\right)$$ where we can notice clear patterns.
For example

*

*the first term corresponds to $-n(n+1)a^{n-2}y$

*the second term corresponds to $\frac 12 n^2(n^2-1)a^{n-3}y^2$

*the last term corresponds to $(-1)^{n-1} n! y^{n-1}$
You could find most of them in $OEIS$.
Edit
We can also write
$$\frac 1a\,{y^{2n}}\, e^{\frac{a}{y}} f_n=a^{n-1}\left(1+ z\, Q_{n-2}(z)\right) \qquad z=a y$$ and the polynomials are
$$
\left(
\begin{array}{cc}
 1 & 0 \\
 2 & -2 \\
 3 & -6+6 z \\
 4 & -12+36 z-24 z^2 \\
 5 & -20+120 z-240 z^2+120 z^3 \\
 6 & -30+300 z-1200 z^2+1800 z^3-720 z^4 \\
 7 & -42+630 z-4200 z^2+12600 z^3-15120 z^4+5040 z^5
\end{array}
\right)$$

A: Only the computation of ${d^n\over dy^n}e^{-4/y}$ causes difficulties. I claim that
$${d^n\over dy^n}e^{-4/y}=y^{-2n}\>Q_n(y)\>e^{-4/y}\qquad(n\geq0)\tag{1}$$
where $Q_0(y)\equiv1$, and $Q_n$ is a polynomial of degree $n-1$ $\,(n\geq1)$. For $(1)$ to be true we need
$${d\over dy}\left(y^{-2n}\>Q_n(y)\>e^{-4/y}\right)=y^{-2(n+1)}Q_{n+1}(y)\>e^{-4/y}\ .$$
This amounts to
$$-2n y^{-2n-1}Q_n(y)+y^{-2n}Q_n'(y)+y^{-2n}Q_n(y)\>4y^{-2}=y^{-2n-2} Q_{n+1}(y)\ ,$$
where we have omitted the nonzero factor $e^{-4/y}$. In this way we obtain the recursion
$$Q_{n+1}(y)=(4-2n y)Q_n(y)+y^2 Q_n'(y)\ .$$
This shows that $Q_1(y)=4$, and that for $n\geq1$ the function $Q_{n+1}$ is a polynomial of degree $n$ when $Q_n$ had degree $n-1$.


text:
Q: DesignAutomationClient() object creation fails with System.TypeLoadException I'm thinking I must be missing something obvious, but im trying to create a new DesignAutomationClient object like follows:
private void runDAButton_Click(object sender, EventArgs e)
        {
            createWorkItem();
        }

        private async Task createWorkItem()
        {
            var forgeConfig = new Autodesk.Forge.Core.ForgeConfiguration();
            forgeConfig.ClientId = clientID;
            forgeConfig.ClientSecret = clientSecret;

            var apiInstance = new DesignAutomationClient();

            // Code to create work item will go here

        }

but when I do, the following error appears in my Visual Studio Debug/Immediate window after trying to execute the var apiInstance = new DesignAutomationClient(); line:

Exception thrown: 'System.TypeLoadException' in mscorlib.dll

Am i missing something obvious? The design automation client was downloaded using NuGet so i should have all the required depencies, but searches of forums for this kind of error all say it means I'm either missing a DLL file, or the type I'm looking for doesn't exist within a DLL, neither of which I believe are true.
This code is in a simple windows form application written in C#
There are no web servers or ASP.NET involved.
The user clicks a button on the form which runs the runDAButton_Click function(which in turn runs the createWorkItem() function). That function should create an instance of the API, and then use it to create my work item.
Can anyone help?

A: We need more information to troubleshoot, is it a ASP .NET core? how you are handling DI
but if your app is .NET core console app from the code as it appears.
The right way to do is.
dotnet new console
dotnet add package Autodesk.Forge.DesignAutomation --version 3.0.3

Code:
namespace daconsole
{
    using Autodesk.Forge.Core;
    using Autodesk.Forge.DesignAutomation;
    using Autodesk.Forge.DesignAutomation.Model;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Options;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Defines the <see cref="ConsoleHost" />.
    /// </summary>
    class ConsoleHost : IHostedService
    {
        /// <summary>
        /// The StartAsync.
        /// </summary>
        /// <param name="cancellationToken">The cancellationToken<see cref="CancellationToken"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// The StopAsync.
        /// </summary>
        /// <param name="cancellationToken">The cancellationToken<see cref="CancellationToken"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// Defines the <see cref="App" />.
    /// </summary>
    internal class App
    {
        /// <summary>
        /// Defines the api.
        /// </summary>
        public DesignAutomationClient api;

        /// <summary>
        /// Defines the config.
        /// </summary>
        public ForgeConfiguration config;

        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        /// <param name="api">The api<see cref="DesignAutomationClient"/>.</param>
        /// <param name="config">The config<see cref="IOptions{ForgeConfiguration}"/>.</param>
        public App(DesignAutomationClient api, IOptions<ForgeConfiguration> config)
        {
            this.api = api;
            this.config = config.Value;
        }

        /// <summary>
        /// The CreateWorkItem.
        /// </summary>
        /// <returns>The <see cref="Task"/>.</returns>
        private async Task CreateWorkItem()
        {
            //step1:
            var forgeEnginesApi = api.EnginesApi;
            ApiResponse<Page<string>> engines = await forgeEnginesApi.GetEnginesAsync();
            if (engines.HttpResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(JsonConvert.SerializeObject(engines.Content, Formatting.Indented));
            }

            //step2:
            Console.WriteLine("\nActiviy Start");
            var activitiesApi = api.ActivitiesApi;
            ApiResponse<Page<string>> activitiesResp = await activitiesApi.GetActivitiesAsync();
            List<string> listOfActivities = new List<string>();

            string activityName = null;
            if (activitiesResp.HttpResponse.IsSuccessStatusCode)
            {
                var page = activitiesResp.Content.PaginationToken;
                activitiesResp.Content.Data.ForEach(e => listOfActivities.Add(e));
                while (page != null)
                {
                    activitiesResp = await activitiesApi.GetActivitiesAsync(page);
                    page = activitiesResp.Content.PaginationToken;
                    activitiesResp.Content.Data.ForEach(e => listOfActivities.Add(e));
                }
                var activities = listOfActivities.Where(a => a.Contains("PlotToPDF")).Select(a => a);
                if (activities.Count() > 0)
                {
                    activityName = activities.FirstOrDefault();
                }

            }

            //step3:
            Console.WriteLine("\nWorkItem Start...");
            var workItemsApi = api.WorkItemsApi;
            ApiResponse<WorkItemStatus> workItemStatus = await workItemsApi.CreateWorkItemAsync(new Autodesk.Forge.DesignAutomation.Model.WorkItem()
            {
                ActivityId = activityName,
                Arguments = new Dictionary<string, IArgument>() {
                              {
                               "HostDwg",
                               new XrefTreeArgument() {
                                Url = "http://download.autodesk.com/us/samplefiles/acad/blocks_and_tables_-_metric.dwg",
                                Verb = Verb.Get
                               }
                              }, {
                               "Result",
                               new XrefTreeArgument() {
                                Verb = Verb.Put, Url = "azure blob storage url",
                                Headers = new Dictionary<string,string>()
                                {
                                    { "Content-Type","application/octet-stream" },
                                    { "x-ms-blob-type","BlockBlob" }
                                }
                               }
                              }
                             }
            });

            Console.Write("\tPolling status");
            while (!workItemStatus.Content.Status.IsDone())
            {
                await Task.Delay(TimeSpan.FromSeconds(2));
                workItemStatus = await workItemsApi.GetWorkitemStatusAsync(workItemStatus.Content.Id);

                Console.Write(".");
            }
            Console.WriteLine(JsonConvert.SerializeObject(workItemStatus.Content, Formatting.Indented));
        }

        /// <summary>
        /// The RunAsync.
        /// </summary>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task RunAsync()
        {
            await CreateWorkItem();
        }
    }

    /// <summary>
    /// Defines the <see cref="Program" />.
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// The Main.
        /// </summary>
        /// <param name="args">The args<see cref="string[]"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureAppConfiguration(builder =>
                {
                    builder.AddEnvironmentVariables();
                    builder.AddForgeAlternativeEnvironmentVariables();
                }).ConfigureServices((hostContext, services) =>
                { // add our no-op host (required by the HostBuilder)
                    services.AddHostedService<ConsoleHost>();

                    // our own app where all the real stuff happens
                    services.AddSingleton<App>();

                    // add and configure DESIGN AUTOMATION
                    services.AddDesignAutomation(hostContext.Configuration);
                    services.AddOptions();
                })
                .UseConsoleLifetime()
                .Build();
            using (host)
            {
                await host.StartAsync();
                // Get a reference to our App and run it
                var app = host.Services.GetRequiredService<App>();
                await app.RunAsync();
                await host.StopAsync();
            }
        }
    }
}

add Forge Env to your launchSettings.json
{
  "profiles": {
    "daconsole": {
      "commandName": "Project",
      "environmentVariables": {
        "FORGE_CLIENT_SECRET": "",
        "FORGE_CLIENT_ID": ""
      }
    }
  }
}

To run:
dotnet run --launch-profile daconsole


text:
Q: Unboxing of hashmap.get() is producing a NullPointerException I'm using a hashmap to get data from another class. I check the logcat and the data for hashmap has been set and it contains the key. But when I try to get the hashmap from the other class I'm getting NullPointerException and when I try to check if the map contains the key it doesn't

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.continueItem:
                CustomAdapter a = new CustomAdapter();
                CustomAdapter.InputTextListener i = a.new InputTextListener();
                HashMap<String, Integer> hashMap = i.getHashMap();
                inputTime = hashMap.get("EDITTEXT VALUE");
                Log.d(TAG, "onOptionsItemSelected: " + hashMap.get("EDITTEXT VALUE"));
                Log.d(TAG, "onOptionsItemSelected: " + hashMap.containsKey("EDITTEXT VALUE"));
                retrieveInputTime(inputTime);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private static final String TAG = "CustomAdapter";
    private ArrayList<Integer> mWorkTW = new ArrayList<>();
    private ArrayList<Integer> mWorkET = new ArrayList<>();
    private ArrayList<Integer> mRestTW = new ArrayList<>();
    private ArrayList<Integer> mRestET = new ArrayList<>();
    private Context mContext;
    private int numberOfIntervals;

    public CustomAdapter() {

    }

    public CustomAdapter(Context context, ArrayList<Integer> mWorkTW, ArrayList<Integer> mWorkET, ArrayList<Integer> mRestTW, ArrayList<Integer> mRestET, int numberOfIntervals) {

        this.mWorkTW = mWorkTW;
        this.mWorkET = mWorkET;
        this.mRestTW = mRestTW;
        this.mRestET = mRestET;
        this.mContext = context;
        this.numberOfIntervals = numberOfIntervals;
        //this.inputTimeIntegerWET = inputTimeIntegerWET;

        Log.d(TAG, "CustomAdapter: " + numberOfIntervals);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View customView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.time_row, viewGroup, false);
        ViewHolder holder = new ViewHolder(customView, new InputTextListener());
        return holder;

    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
        Log.d(TAG, "onBindViewHolder: called");
        viewHolder.workTextView.setText(R.string.work_text_view);
        viewHolder.restTextView.setText(R.string.rest_text_view);
        viewHolder.workEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    viewHolder.workEditText.setHint("");
                else
                    viewHolder.workEditText.setHint(mWorkET.get(viewHolder.getAdapterPosition()));
            }
        });

        viewHolder.restEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    viewHolder.restEditText.setHint("");
                else
                    viewHolder.restEditText.setHint(mRestET.get(viewHolder.getAdapterPosition()));
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.d(TAG, "" + numberOfIntervals);
        return numberOfIntervals;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public InputTextListener inputTextListener;
        TextView workTextView;
        EditText workEditText;
        TextView restTextView;
        EditText restEditText;
        ConstraintLayout parentLayout;

        public ViewHolder(@NonNull View itemView, InputTextListener inputTextListener) {
            super(itemView);
            workTextView = itemView.findViewById(R.id.workTextView);
            workEditText = itemView.findViewById(R.id.workEditText);
            restTextView = itemView.findViewById(R.id.restTextView);
            restEditText = itemView.findViewById(R.id.restEditText);
            parentLayout = itemView.findViewById(R.id.parentLayout);
            this.inputTextListener = inputTextListener;

            workEditText.addTextChangedListener(inputTextListener);
        }
    }

        class InputTextListener implements TextWatcher {
        String inputTimeString;

        int inputTime;
        HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

            public HashMap<String, Integer> getHashMap() {
                return hashMap;
            }

            public InputTextListener() {
            }

            public void setHashMap(HashMap<String, Integer> hashMap) {
                this.hashMap = hashMap;
            }

            /*public int getInputTime() {
            return inputTime;
        }*/

        public void setInputTime(int inputTime) {
            this.inputTime= inputTime;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
             try {
                 Log.d(TAG, "onTextChanged: I've made it to here!");
                 inputTimeString = s.toString().trim();
                 inputTime = Integer.parseInt(inputTimeString);
                 setInputTime(inputTime);
                 hashMap.put("EDITTEXT VALUE", inputTime);
                 Log.d(TAG, "onTextChanged: " + inputTime);

                 int bla = inputTime + 2;
                 Log.d(TAG, "onTextChanged: " + bla);
                 Log.d(TAG, "onTextChanged: " + hashMap.containsKey("EDITTEXT VALUE"));
                 Log.d(TAG, "onTextChanged: " + hashMap.get("EDITTEXT VALUE"));
                 setHashMap(hashMap);

             } catch (NumberFormatException NFE) {
                 mWorkET = null;
             }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }

    }
}

I'm expecting for the hashmap being able to access the data from the other class.

A: Here is some of the code you posted:

CustomAdapter a = new CustomAdapter();
CustomAdapter.InputTextListener i = a.new InputTextListener();
HashMap<String, Integer> hashMap = i.getHashMap();

What this is going to do is create a new instance of your CustomAdapter class, then create a new instance of your InputTextListener class, and finally retrieve the HashMap stored inside the text listener.
Again, this is all happening with new instances of these classes. Therefore, the HashMap is empty (since nothing has populated it).
You are probably assuming that i would be the "same" listener instance as you're using elsewhere in your app. This is not the case. You will need to access that listener somehow rather than creating a new instance.
Looking at your code, this doesn't really seem feasible. Each ViewHolder has its own instance of InputTextListener... how will your options menu know which ViewHolder you're trying to interact with?
Chances are good that you're going to need to go back to the drawing board and come up with a different way to solve whatever problem you're attempting.


text:
Q: Symfony2 Gedmo Translatable with APY DataGrid and KNP Paginator I have a few problems using Gedmo\DoctrineExtensions Translatable.
First is APY DataGrid - can't make it to show translated strings in grid on non default locale. If I use Translatable with default settings, all strings in grid are displayed in default language. If I implement Translatable in Entity and add annotations for table and other stuff, then I can see translated strings in grid, BUT after switching locales these stays the same. Seems like QueryCache is used, but can't find how to set not to use it. Here's a part for grid:
use APY\DataGridBundle\Grid\Source\Entity;

<...>

$source = new Entity('MainBundle:Entity');
$source->addHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');

Of course it would be better to have translations without making annotations and separate entities for them.
Second problem is KNP pagination. Actually didn't dig into it, but similar problem.
The main problem is, when I run some query by translatable field of an entity. Let's say I have an Entity with name Krepšinis (it's basketball in Lithuanian) and I have translated this string to Basketball. Default language is LT. When in default language I perform a search, everything is ok, but if I change locale to EN and try searching for basket, it doesn't return any results and if I search for krep, it returns me Basketball. Code for search:
// Controller

$repository = $this
    ->getDoctrine()
    ->getManager()
    ->getRepository('MainBundle:Entity');

$query = $repository
    ->search($term)
    ->getQuery()
    ->useQueryCache(false)
    ->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');

// Repository

public function search($query)
{
    $qb = $this->createQueryBuilder('t');
    $term = $qb->expr()->literal('%' . $query . '%');
    $query = $qb->where($qb->expr()->like('t.name', $term));

    return $query;
}

Any help is appreciated

A: if content is translated, you need to use query hints as you have already went through. But in order to have it cached for different locales, you need to set the locale hint to the query:
<?php
// hint the locale in order to make query cache id unique
$query->setHint(
    \Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
    'en' // take locale from session or request
);

Which is described in the documentation read it carefully.
ORM query cache is based on DQL, query parameters and query hints.


text:
Q: How can I keep an ssh connection open on windows and use it with perl? I am trying to work on a old script of mine that I was writing to backup file on my VMware server.
Originally the script was going to run on Linux only, but now I trying to figure out how to make it run on Windows. Most of the modules I need for perl will run on Windows and Linux which is good. But there is one module that I can't seem to find, which is an SSH module.
My plan was to use putty or plink to send commands to the server and return them to the script. But the problem that I see is every time I call putty in the script its going to open new connection to server and close it when it has finished. What I am looking for is a way to open a connection once its open leave it open and then send and receive from that one connection. Only having it close when the script calls a close function or something.
Any idea where I could being with something like this?
Unless someone else has a much better idea because I am open to anything.

A: There's quite a few SSH client modules from CPAN, such as Net::SSH, Net::SSH::Perl, and Net::SSH2.

A: You can also try using Expect
http://metacpan.org/pod/Expect


text:
Q: Find extreme values of implicit function $x^2+2y^2+4z^2-2x+12y+8z+19=0$ Find extreme values of implicit function $x^2+2y^2+4z^2-2x+12y+8z+19=0$
I have found partial derivative with respect to x and y and they are:
$\frac{dz}{dx}=\frac{2-2x}{8z-8} => x=1$
$\frac{dz}{dy}=\frac{-4y-12}{8z+8} => y=-3$
$\frac{d}{dz}=8z+8 => z=-1$
Now my critical point would be $A(1,-3,-1)$ is this correct?

A: Note: Do not say that the expression is zero. Instead, say find max/mim value of T
Let $T=x^2+2y^2+4z^2-2x+12y+8z+19=(x-1)^2+2(y+3)^2+4(z+1)^2-4$
$$\implies T+4\ge 0\implies T_{min}=-4$$
The min occurs when $x=1, y=-3,z=-1$.

A: I'm not sure if "critical point" is applicable here because you have an equation $f(x,y,z)=0$ rather than a function $f(x,y,z)$. Indeed, $(1,-3,-1)$ is an extreme for $f(x,y,z)$ but it is not at the surface $f(x,y,z)=0$.
The implicite function could be written as :
$$
(x-1)^2+2(y+3)^2+4(z+1)^2 = 4
$$
Assume that you want to find extreme value of $z$ w.r.t. $x$ and $y$, it is clear that the $(z+1)^2 \in [0,1] $ so $z+1 \in [-1,1]$, and then $z \in [-2,0]$. So we have

*

*$z_{min} = -2$, with $x=1$ and $y=-3$

*$z_{max} = 0$, with $x=1$ and $y=-3$
Same logic could be used to find $x_{min/max}$ w.r.t. $y$ and $z$, and $y_{min/max}$ w.r.t. $x$ and $z$.
Hope this could help you.


text:
Q: change the button only after click. angularjs Here is the codepen. I have a text box and two button on the page.  I am getting the clientId from database and putting it in sessionStorage.clientId and assigning it to the  $scope.ssclientID.
The problem I am having is as soon I enter the text into the text box the "TurnOff" button shows up. I want to show the "TurnOn" till i click on it.
HTML :

       Client ID

           <input type="text" name="clientID" class="form-control input-md" ng-model="ssclientID" />

        <button ng-if="ssclientID != 'null' && ssclientID != '0' && ssclientID != ''" type="button"  class="btn btn-danger col-xs-3" ng-click="saveEverifyOption(0)">
       Turn Off E-Verify
              </button>
          <button ng-if="ssclientID == '0' || ssclientID == 'null' || ssclientID == ''" type="button" class="btn btn-success col-xs-3" ng-click="saveEverifyOption(clientID)">
        Turn On E-Verify
       </button>

js :
//$scope.ssclientID = sessionStorage.clientId;
     $scope.Model = {
                compId: 0,
                clientID: ''
            }

;

A: Just add another variable to your scope, which stores the click status.
$scope.clicked = false;

In your $scope.saveEverifyOption function add
if (clientID == 0) $scope.clicked = false;
else $scope.clicked = true;

Finally, change the ng-ifs on your buttons:
<button ng-if="ssclientID != 'null' && ssclientID != '0' && ssclientID != '' && clicked" type="button"  class="btn btn-danger col-xs-3" ng-click="saveEverifyOption(0)">
     Turn Off E-Verify
</button>
<button ng-if="ssclientID == '0' || ssclientID == 'null' || ssclientID == '' || !clicked" type="button" class="btn btn-success col-xs-3" ng-click="saveEverifyOption(clientID)">
     Turn On E-Verify
</button>


text:
Q: Is there an open source C# library for command line/console programs? I often write consoles for various things (and I've made my own library - but it's quite limited), I do this mainly because the Windows command line sucks. Is there an open source library I can use for writing such command line applications? By console, I mean a command prompt with auto-complete (tab) and copy/paste.
Update:
Please do not recommend that I use something other than cmd.exe (e.g. PowerShell), since PowerShell may not always be available. Also, I'm looking for a library that makes my application behave like a command line interpreter; I'm not looking for a library that helps me parse command arguments.

A: I think I wrote pretty much exactly what you asked for :)
It's open source on github, is dead simple to use, and has a bunch of examples.

A: I used Command Line Parser before and it's really good for getting the command line params in a nice, configurable way. Have a look, maybe it'd do what you want.

A: You may find this one-file-with-demo library useful.

A: For tab completion/hinting, i wrote the following lib:
https://github.com/fjunqueira/hinter
It might be helpful to someone.

A: You may be interested in this article:
http://kamimucode.com/Home.aspx/C-sharp-REPL/1
Maybe you need to implement a REPL:
http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop
Regards,
Giacomo

A: You might want to use PowerShell instead of cmd.


text:
Q: How do I ignore exceptions during deserialization of bad JSON? I am consuming an API that is supposed to return an object, like
{
    "some_object": {
        "some_field": "some value"
    }
}

when that object is null, I would expect
{
    "some_object": null
}

or
{
    "some_object": {}
}

But what they send me is
{
    "some_object": []
}

...even though it's never an array.
When using
JsonSerializer.Deserialize<MyObject>(myJson, myOptions)

an exception is thrown when [] appears where null is expected.
Can I selectively ignore this exception?
My current way of handling this is to read the json and fix it with a regex before deserialization.
I prefer to use System.Text.Json, and not introduce other dependencies, if possible.

A: This solution uses a custom JsonConverter in System.Text.Json.
If some_object is an array then it will return an empty object (or null if you prefer), and no exception will be thrown.  Otherwise it will correctly deserialize the json.
public class EmptyArrayToObjectConverter<T> : JsonConverter<T>
{
    public override T Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        var rootElement = JsonDocument.ParseValue(ref reader);

        // if its array return new instance or null
        if (reader.TokenType == JsonTokenType.EndArray)
        {
            // return default(T); // if you want null value instead of new instance
            return (T)Activator.CreateInstance(typeof(T));
        }
        else
        {
            var text = rootElement.RootElement.GetRawText();
            return JsonSerializer.Deserialize<T>(text, options);
        }
    }

    public override bool CanConvert(Type typeToConvert)
    {
        return true;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize<T>(writer, value, options);
    }
}

Decorate your property with the JsonConverter attribute. Your class might look something like this:
public class MyObject
{
    [JsonPropertyAttribute("some_object")]
    [JsonConverter(typeof(EmptyArrayToObjectConverter<SomeObject>))]
    public SomeObject SomeObject { get; set; }

    ...
}

A: You can use [OnError] attribute to conditionally suppress exception related with a particular member. Let me try to explain it with an example.
The example class which represents JSON file. It contains a nested class SomeObject.
public class MyObject
{
    public int TemperatureCelsius { get; set; }
    public SomeObject SomeObject { get; set; }

    [OnError]
    internal void OnError(StreamingContext context, ErrorContext errorContext)
    {
        //You can check if exception is for a specific member then ignore it
        if(errorContext.Member.ToString().CompareTo("SomeObject") == 0)
        {
            errorContext.Handled = true;
        }
    }
}

public class SomeObject
{
    public int High { get; set; }
    public int Low { get; set; }
}

If sample JSON stream/file contains text as:
{
  "TemperatureCelsius": 25,
  "SomeObject": []
}

then exception is handled and suppressed as exception is raised for SomeObject member. The SomeObject member is set as null.
If input JSON stream/file contains text as:
{
  "TemperatureCelsius": 25,
  "SomeObject":
  {
    "Low": 1,
    "High": 1001
  }
}

then object is serialized properly with SomeObject representing expected value.

A: Here is a solution using a custom JsonConverter and Newtonsoft.Json.
This will set SomeObject to null in MyObject if it is an array.  You can return a new instance of SomeObject instead by returning (T)Activator.CreateInstance(typeof(T)).
public class ArrayToObjectConverter<T> : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            // this returns null (default(SomeObject) in your case)
            // if you want a new instance return (T)Activator.CreateInstance(typeof(T)) instead
            return default(T);
        }
        return token.ToObject<T>();
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

Note that Newtonsoft.Json ignores CanConvert (since the property is decorated with JsonConverter attribute) it assumes it can write and convert so does not call these methods (you could return false or throw NotImplementedException instead and it will still serialize/deserialize).
In your model, decorate some_object with the JsonConvert attribute. Your class might look something like this:
public class MyObject
{
    [JsonProperty("some_object")]
    [JsonConverter(typeof(ArrayToObjectConverter<SomeObject>))]
    public SomeObject SomeObject { get; set; }
}

I know you said you'd prefer to use System.Text.Json but this might be useful for others using Json.Net.
Update: I did create a JsonConverter solution using System.Text.Json and it is here.

A: Solutions above work fine, I'll give mine for .NET Core 3 and above, which is just a reader, not a writer (no need). The source json, is buggy, and gives an empty array, when it should be 'null'. So, this custom converter does the correction work.
so: "myproperty":{"lahdidah": 1} is [] when it actually should be: "myproperty": null
Note, the TrySkip, we don't need to eat bogus elements.
public sealed class JsonElementOrArrayFixerConverter<T> : JsonConverter<T>
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.StartArray)
            {
                reader.TrySkip();
                return default;
            }
            return JsonSerializer.Deserialize<T>(ref reader, options);
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            throw new NotImplementedException();
        }
    }

A: Exception handling is a pet peeve of mine. And I have two articles from other people that I link often on the mater:

*

*https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/

*https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I consider them required reading and use them as basis of any discussion on the topic.
As a general rule, Exception should never be ignored. At best they should be caught and published. At worst, they should not even be caught. It is too easy to cause followup issues and make debugging impossible to be careless or overly agressive.
That being said, in this case (deserialisation) some Exceptions could be classified as either a Exogenous or Vexing Exception. Wich are the kind you catch. And with Vexing, you might even swallow them (like TryParse() kinda does).
Usually you want to catch as specific as possible. Sometimes however you got a very wide range of Exceptions with no decent common ancestors, but shared handling. Luckily I once wrote this attempt to replicate TryParse() for someone stuck on 1.1:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case.
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;
}


text:
Q: FBLPromise crash with CocoaPods and SwiftPM implemented in both We've been migrating away from CocoaPods since a while, but not every dependency has made the switch. Like Firebase.
I've had a similar question regarding duplicate symbols, but now I'm facing something new, which is probably because I'm using a dependency in both SwiftPM as in CocoaPods.
After running my (sample) project it crashes:
-[FBLPromise firebaseInstallationID]: unrecognized selector sent to instance 0x600003f5a430

with a warning at the top:
objc[93047]: Class FBLPromise is implemented in both
/xxx/SampleProject.app/Frameworks/FBLPromises.framework/FBLPromises (0x10b3f09a8) and
/xxx/SampleProject.app/SampleProject (0x10af736f0).
One of the two will be used. Which one is undefined.

Prior to my update to Firebase SDK v6.26.0 I would only get the first warning, but since the update it crashes.
I saw a doc about how to use Firebase within libraries and a GitHub issue regarding a similar crash. But nothing seems to work to resolve this crash, other then downgrading.
I uploaded a sample project: https://github.com/basvankuijck/SampleProjectFirebaseCrash.
Removing the SwiftPM Promises dependency is not an option, since the actual project is using a SwiftPM dependency that has a dependency to Promises.
The Podfile is nothing that fancy, and the SampleProject just uses one single SwiftPM dependency.
Anyone who has an idea how to let SwiftPM and CocoaPods play nicely together especially with Firebase in the middle?

A: I faced the exact same problem with Firebase and FBLPromise. For me it arose because I added Firebase/FireStore in podfile but the rest of the FIrebase dependencies from SPM. Among my other SPM dependencies was FBLPromise as well.
To fix it I had to remove the FIrebase package from SPM and then add it again with FIrestore and other dependencies that I could need from Firebase.
No other solution worked for me.


text:
Q: Visual Studio Code - Arduino Programming Identifier A8 - A15 (PIN_A8 to PIN_A15) is Undefined I am attempting to use VSCode to write my Arduino programs (MEGA2560), My issue arises when I try to setup
    const int CurrentPin = A9;

the A9 is underlined and problems say
    identifier "A9" is undefined [7,24]

I have tried changing the .vscode/arduino.json .vscode/c_cpp_properties.json
I believe it might be part of the defines in c_cpp_properties
edit: on occasion where I have something being defined by the pin it kicks the can down to the use of it i.e.
line 22
#define ONE_WIRE_BUS A13

line 24
OneWire oneWire(ONE_WIRE_BUS);

identifier "A13" is undefined [24,17]

also when I use the "Go to Definition on the instance of A13 on line 22 it leads back to pins_arduino.h where they are all defined
arduino.json
{
    "board": "arduino:avr:mega",
    "configuration": "cpu=atmega2560",
    "port": "/dev/ttyAMC0",
    "output": "build",
    "sketch": "Project/MyProject.ino",
    "programmer": "AVRISP mkII"
}

c_cpp_properties.json
{
    "enableConfigurationSquiggles": true,
    "env", {},
    "configurations": [
        {
             "name": "Linux",
             "includePath": [
                 "{$workspaceFolder}",
                 %Arduino and library folders%
             ],
             "browse": {
                 "limitSymbolsToIncludeHeaders": false,
                 "path": [
                     "{$workspaceFolder}",
                     %Arduino and library folders%
                 ]
             },
             "defines": [
                 "_DEBUG",
                 "UNICODE",
                 "_UNICODE",
                 "USBCON",
                 "ARDUINO_ARCH_AVR",
                 "ARDUINO_AVR_MEGA2560",
                 "ARDUINO=10800"
             ],
             "compilerPath": "/usr/bin/avr-gcc",
             "cStandard": "c11",
             "cppStandard": "c++17",
             "intelliSenseMode": "clang-x64",
             "forcedInclude": [
                 "...Arduino.h"
             ]
         }
    ],
    "version": 4

}

MyProject.ino
#include <Arduino.h>
#include <Libraries.h>

const int currentPin =A9;

void setup(){
//stuff
}
void loop(){
//do stuff
}

I expected to uses the defines for the  "ARDUINO_ARCH_AVR" and the "ARDUINO_AVR_MEGA2560", to define the analog pins but they do not


text:
Q: What's the most efficient container for insertion from the back and removal from the front and back? In terms of runtime, what is the most efficient container for storing a large amount of data through the back and removing from the front or back?

A: A std::deque or Double Ended Queue.
Unlike a std::vector, it isn't guarenteed to be stored in contiguous memory. You should benchmark your particular need though, since the cache is becoming ever more important and general complexity statements less so; however, in this case, a deque is where I would start.

A: It depends on the implementation, the size of the container, the
types involved, and probably other things as well, so the only
real answer one can give is to measure.  std::deque was
designed for these types of operations, and for very large
containers with expensive to copy types, it will doubtlessly be
the fastest, but the one time I measured (with a container of up
to 8 char—small and cheap to copy), std::vector beat
std::deque` hands down.


text:
Q: How get data from loop in sql function I need get data as text and return as array from postgresql function. I have a clips media table with files and for each clip id i wanna get all files from media clips. I created function like this:
CREATE OR REPLACE FUNCTION clips_media_array(INT)
RETURNS text[] AS $$
  DECLARE
    r clips_media%ROWTYPE;
    t text[];
  BEGIN
  FOR r IN
    SELECT file_name
    FROM clips_media WHERE id_clips = $1 AND file_type = 2
  LOOP
    t := t.file_name;
  END LOOP;

  END;
$$
LANGUAGE plpgsql;

and i have an error:
ERROR:  invalid input syntax for integer: "bfeO4RbZ5R1CUT8.jpg"
CONTEXT:  PL/pgSQL function clips_media_array(integer) line 6 at FOR over SELECT rows

Could anyone help me with this ?

A: You are overcomplicating things.
You don't need a loop - you don't even need a PL/pgSQL function.
You can put that into a simple SQL function with a single SQL query:
CREATE OR REPLACE FUNCTION clips_media_array(INT)
RETURNS text[] AS
$$
  SELECT array_agg(file_name)
  FROM clips_media
  WHERE id_clips = $1
    AND file_type = 2;
$$
LANGUAGE sql;

Of course you can use that SQL query directly in your code without the overhead of a function.

If you want a PL/pgSQL function you would need to concat the values from the cursor variable inside the loop:
The following code is wrong:
LOOP
   t := t.file_name;
END LOOP;

and should be:
LOOP
  t := t || R.file_name;
END LOOP;

To reference the column from the loop record you need to use R.file_name and to add an element to an array you need to use ||.
You also need to initialize your result variable, otherwise it's null:
DECLARE
  r clips_media%ROWTYPE;
  t text[] := array[]::text[];

And finally you are missing a return statement:
  LOOP
    t := t || r.file_name;
  END LOOP;
  return t; --<< required to return something from a PL/pgSQL function
END;
$$


text:
Q: Excel vba Underscore .Delete_ I can't seem to find the right answer that fits to my code.
I'm trying to delete the first row on Sheet1
I'm sure my code below would work
But throws me a Run time error '438'. Object doesn't support this property or method.
Worksheets("Sheet1").Range("1:1").Delete_

The following is my code:
Option Explicit
Sub C2P()
        Worksheets("Sheet1").Range("C:C,F:F").Replace _
            What:=",", replacement:=".", LookAt:=xlPart
        Worksheets("Sheet1").Range("1:1").Delete_
End Sub

Any feedback would be appreciated. Thank you!

A: You have an extra character in the Delete method name.
Worksheets("Sheet1").Range("1:1").Delete_
Remove the underscore.
Learn to use the "F1" key to bring up the built in help system.  It is there for a reason.


text:
Q: How to add a class to the selected span in jQuery? I'm trying to set a class (highlighted) to the span been selected and removing it when another span has been selected. Where do I need to set this class?
This is for a king of telephone keypad I'm working on. I'm basically working on a code that someone just answered on a previous question I posted. I've been trying to set this class, but I can't make it work as I wish.
Here is the code: http://jsfiddle.net/b6wfeaxz/3/
JS / jQuery
var index     = 0;
var direction = 1;

$(".button").on("click", function () {

  var $this = $(this);

  if ($this.hasClass("selected")) {
    if (index >= $this.find(".letter").length - 1) {
        direction *= -1;
    } else if (direction == -1 && index == 0) {
        direction *= -1;
    }

        $(this).children(".letter").eq(index).addClass('highlighted');
    index += direction;
  } else {
    $(".button").removeClass("selected");
    $this.addClass("selected");

    index = 0;
  }

  var result = $(this).children(".letter").eq(index).text();

  $(".result").text(result);

});

HTML
    -

1

    A
    B
    C

2

    D
    E
    F

3

    G
    H
    I

CSS
 .highlighted {
   border: 1px solid red;
 }

I expect the span to be selected by adding the class highlighted and be removed when another letter has been selected.

A: From what I could understand the problem is removing the class from the unselected letters, right?
Try using the each function to remove the class from all letters first.
Like this:
$('.letter').each(function(){
    $(this).removeClass('highlighted');
})
$(this).children(".letter").eq(index).addClass('highlighted');
index += direction;

A: This is a quick fix. Basically you keep an array of all the directions and indexes for each of the buttons. Then you select which one you need to edit by the index of the button clicked. This is not an ideal solution but it works. Hopefully that helped.
var index     = [0,0,0];
var direction = [1,1,1];

$(".button").on("click", function () {

  var $this = $(this);
    if (index[$this.index()] >= $this.find(".letter").length - 1) {
        direction[$this.index()] *= -1;
    } else if (direction[$this.index()] == -1 && index[$this.index()] == 0) {
        direction[$this.index()] *= -1;
    }
    $('.letter').each(function(){
        $(this).removeClass('highlighted');
    })
    $(this).children(".letter").eq(index[$this.index()]).addClass('highlighted');

  var result = $(this).children(".letter").eq(index[$this.index()]).text();
  $(".result").text(result);
  //you have to add to the index after the result
  index[$this.index()] += direction[$this.index()];

});

A: This is a different approach, but seems easier to separate the highlight logic from the selected click event.

var index     = 0;
var direction = 1;

$(".button").on("click", function () {

  var $this = $(this);

  if ($this.hasClass("selected")) {
   if (index >= $this.find(".letter").length - 1) {
     direction *= -1;
    } else if (direction == -1 && index == 0) {
     direction *= -1;
    }
   index += direction;
  } else {
    $(".button").removeClass("selected");
    $this.addClass("selected");

    index = 0;
  }

  removeHighlight();
  $(this).find('span.letters').addClass('highlighted');

  var result = $(this).find(".letter").eq(index).text();

  $(".result").text(result);

});

function removeHighlight() {
 var $letters = $('div.keypad').find('.letters');
  $letters.each(function() {
   $(this).removeClass('highlighted');
  });
}
.button {
  float: left;
  width: 100px;
  height: 100px;
  margin: 20px 20px;
}
.num {
  font-size: 50px;
}
.result {
  font-size: 100px;
  color: blue;
  padding: 50px;
}
.highlighted {
  border: 1px solid red;
}
div.num {
  cursor: pointer;
}

A

1

      A
      B
      C

2

      D
      E
      F

3

      G
      H
      I

A: Hi I have change your code a bit the changes are :

*

*Add a counter to detect each click.

*Add a num variable and actual_number in order to reset the counter between buttons.

    var counter = 0;
    var num = "";
    $(".button").on("click", function (e) {
      var $this = $(this);
      actual_number  = $(this).children(".num").text();
      if(counter < 3 && num == actual_number ){
      $(".letter").removeClass('highlighted');
      $(this).children(".letter").eq(counter).addClass('highlighted');
       var result = $(this).children(".letter").eq(counter).text();
      $(".result").text(result);
      counter++;
      }else{
       counter=0;
       num =  $(this).children(".num").text();
       $(".letter").removeClass('highlighted');
      $(this).children(".letter").eq(counter).addClass('highlighted');
       var result = $(this).children(".letter").eq(counter).text();
      $(".result").text(result);
      counter++;
      }

    })
    .button {
      float: left;
      width: 100px;
      height: 100px;
      margin: 20px 20px;
    }
    .num {
      font-size: 50px;
    }
    .result {
      font-size: 100px;
      color: blue;
      padding: 50px;
    }
    .highlighted {
      border: 1px solid red;
    }

A

1

        A
        B
        C

2

        D
        E
        F

3

        G
        H
        I

Hope it helps