text:
Q: Multiple contructor params by cause of inject dependency in WPF Desktop C# I have a problem that a would like that help me. I have some service class for example, I show a part of one of them:
public class CategoriesService : ICategoriesService
{
    public List<Categories>? getAll()
    {
        return RYCContextService.getInstance().BBDD.categories?.ToList();
    }
    .
    .
    .
}

Then, I have this class:
public class TransactionsService : ITransactionsService
{
    private readonly ISplitsService splitsService;
    private readonly ICategoriesService categoriesService;
    private readonly IAccountsService accountsService;

    public TransactionsService(ISplitsService splitsService,ICategoriesService categoriesService,
        IAccountsService accountsService)
    {
        this.splitsService = splitsService;
        this.accountsService = accountsService;
        this.categoriesService = categoriesService;
    }

    public List<Transactions>? getAll()
    {
        return RYCContextService.getInstance().BBDD.transactions?.ToList();
    }
    .
    .
    .
}

That uses the category class and others, I am using injected dependencies on them, and through constructor params, I pass the services for resolving those dependencies.
This class service is used in a form, for example this:
public partial class FrmTransaction : Window
{
    private Transactions? transaction;
    private readonly int? accountidDefault;
    private readonly IAccountsService accountsService;
    private readonly ICategoriesService categoriesService;
    private readonly IPersonsService personsService;
    private readonly ITagsService tagsService;
    private readonly ISplitsService splitsService;
    private readonly ITransactionsService transactionsService;
    private readonly ITransactionsStatusService transactionsStatusService;

    public FrmTransaction(IAccountsService accountsService, ICategoriesService categoriesService,
        IPersonsService personsService, ITagsService tagsService,ITransactionsService transactionsService,
        ITransactionsStatusService transactionsStatusService, ISplitsService splitsService)
    {
        this.accountsService = accountsService;
        this.categoriesService = categoriesService;
        this.personsService = personsService;
        this.tagsService = tagsService;
        this.transactionsService = transactionsService;
        this.transactionsStatusService = transactionsStatusService;
        this.splitsService = splitsService;
        InitializeComponent();

    }
    . . . . .
    . . . .
    . . . .
}

This form is called from the principal form:
public partial class MainWindow : Window
{
    private readonly IAccountsService accountsService;
    private readonly IAccountsTypesService accountsTypesService;
    private readonly ICategoriesService categoriesService;
    private readonly ICategoriesTypesService categoriesTypesService;
    private readonly ITransactionsService transactionsService;
    private readonly ITransactionsRemindersService transactionsRemindersService;
    private readonly IExpirationsRemindersService expirationsRemindersService;
    private readonly ISplitsService splitsService;
    private readonly ISplitsRemindersService splitsRemindersService;
    private readonly IPeriodsRemindersService periodsRemindersService;
    private readonly IPersonsService personsService;
    private readonly ITagsService tagsService;
    private readonly ITransactionsStatusService transactionsStatusService;

    public MainWindow(IAccountsService accountsService, ITransactionsService transactionsService,
        ISplitsService splitsService, IExpirationsRemindersService expirationsRemindersService,
        ICategoriesService categoriesService,ICategoriesTypesService categoriesTypesService,
        IAccountsTypesService accountsTypesService,IPersonsService personsService,
        ITagsService tagsService, ITransactionsRemindersService transactionsRemindersService,
        ITransactionsStatusService transactionsStatusService, ISplitsRemindersService splitsRemindersService,
        IPeriodsRemindersService periodsRemindersService)
    {
        InitializeComponent();
        this.accountsService = accountsService;
        this.transactionsService = transactionsService;
        this.splitsService= splitsService;
        this.expirationsRemindersService = expirationsRemindersService;
        this.categoriesService = categoriesService;
        this.categoriesTypesService = categoriesTypesService;
        this.accountsTypesService = accountsTypesService;
        this.personsService = personsService;
        this.tagsService = tagsService;
        this.transactionsRemindersService = transactionsRemindersService;
        this.transactionsStatusService = transactionsStatusService;
        this.periodsRemindersService = periodsRemindersService;
        this.splitsRemindersService = splitsRemindersService;
    }

    private void gvTransactions_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (gvTransactions.CurrentItem != null)
        {
            FrmTransaction frm = new FrmTransaction((Transactions)gvTransactions.CurrentItem,accountsService,categoriesService,
                personsService,tagsService,transactionsService,transactionsStatusService,splitsService);
            frm.ShowDialog();
            loadAccounts();
            loadTransactions();
            refreshBalance();
        }
    }
    ....
    ....
    .....
}

I think that there is some thing that is not correct because the code for me is very ugly, for each form that I call from the principal class increment class variables and constructor params, that it don't use on the principal form, only for passing on to the next form.

A: Your code has some design issues that lead to your current situation of smelling code that is difficult to maintain. Depending on how clean you like code to be and on how big the application is (and on how much extensibility it needs) you could classify the design issues as serious:
Problem
Your constructor probably has too many parameters. This is an indicator that your class probably has too many dependencies, which means it has too many responsibilities. You should revisit your class design. This problem will make your code hard to understand, even for yourself.
Solution
Apply the Single Responsibility Principle (the 'S' in SOLID) and split up your big class into many smaller classes. Move the functionality out of the class that defines too many dependencies and has too many responsibilities. This will also help to understand your code better.
Problem
You spread RYCContextService.getInstance all over the place. It seems like you have implemented the Singleton pattern here. You should always avoid it.   Especially in an environment that uses dependency injection (or any form of IoC) you don't need the Singleton.
You typically use dependency injection to make your application extensible. Adding a tight coupling to a static instance defeats the goal. It also introduces several serious issues, like degrading testability of the depending classes and therefore of your application.
You also create a potential memory leak (all references and resources of this static reference will be alive for the entire application lifetime. Reason: a static reference is treated as object root for of a reference (aka object) tree. The garbage collector can't collect a static object tree).
Solution
Instead use the lifetime management of your IoC container.
For example, the globally shared instance should be injected like every other dependency. But configure the IoC container to always return the same instance (shared instance). For most IoC containers this lifetime is called Singleton like the pattern.
Problem
You create instances explicitly. This explicit creation requires the creator to know all the dependencies of the created type.
In an dependency injection context you don't want to create instances explicitly. Your code highlights the downsides:
a) introduction of tight coupling (new MyType())
b) the instantiating class declares dependencies that are only needed to internally construct other types. Those created types are not visible to the outside of the creating class (dependency hiding)
c) loss of extensibility: changing the explicitly constructed type or modifying its dependencies will require to modify the creating type.
Example:
class ClassA
{
  public ClassA(IClassC classCInstance)
  {
    this.ClassBDependency = classCInstance;
  }

  private void OnButtonClick(object sender, EventArgs e)
  {
    string userName = "Some User";
    IClassB dynamicInstance = new ClassB(userName, this.ClassBDependency);
  }
}

Solution
The solution is to make the dependency visible by defining it as a class dependency. In other words, let the IoC container instantiate the type for you.
If the dependency needs to be instantiated dynamically, you would have to use the Abstract Factory pattern:
Version A that uses a Func<T> delegate as factory. Func<T> also allows to pass dynamic parameters, like user input data:
class ClassA
{
  private Func<IClassB> ClassBFactory { get; }

  public ClassA (Func<string, IClassB> classBFactory)
  {
    this.ClassBFactory = classBFactory;
  }

  private void OnButtonClick(object sender, EventArgs e)
  {
    string userName = "Some User";
    IClassB dynamicInstance = this.ClassBFactory.Invoke(userName);
  }
}

Version B implements the Abstract Factory pattern:
interface IClassBFactory
{
  IClassB Create(string userName);
}

// The concrete type that the IoC container will inject later
class ClassBFactory : IClassBFactory
{
  private IClassC ClassBDependency { get; }

  // The factory alone knows the dependencies of the product.
  // A factory can also depend on other abstract factories.
  public ClassBFactory(IClassC classCInstance)
  {
    this.ClassBDependency = classCInstance;
  }

  public IClassB Create(string userName)
    => new ClassB(this.ClassBDependency);
}

// The type that depends on ClassB and needs to create instances of it dynamically
class A
{
  private IClassBFactory ClassBFactory { get; }

  public ClassA(IClassBFactory classBFactory)
  {
    this.ClassBFactory = classBFactory;
  }

  private void OnButtonClick(object sender, EventArgs e)
  {
    string userName = "Some User";
    IClassB dynamicInstance = this.ClassBFactory.Create(userName);
  }
}


text:
Q: RecyclerView notifyItemRemoved(position) not working properly I have a RecyclerView with its RecyclerView.Adapter and view holder. I am trying to delete an item from list, code as follows inside onClick() on delete button in the ViewHolder
int position = getAdapterPosition();
if(position > -1)
{
Place place = placeList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}

Despite removing the view and doing the animation (list also gets affected), the old view (or lower one) still exist or drawn again.
For example, if the list starts with size = 5, then i try to remove index 4, he remove 4, then still draw 5 views.
EDIT
If i remove notifyItemRangeChanged() then it does that bug only if i do the following
1- click on delete
2- click button very quickly that takes me to new view
3- going back to the list where i can delete
4- start deleting, and bug happens. 1 item still remain even though the List size = 0 (getItemCount is called with 0).
If i only call NotifyDataSetChanged(), then it removes item, but view just stays there !!
Any help or suggestion is appreciated.
Thanks.
EDIT complete class LINK

A: Try this:
placeList.remove(position);
notifyItemRemoved(position);

A: use below code it will solve your problem.
 holder.deleteImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(list.size()!=0){
                list.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,list.size());
            }

         }
    });

A: I've had the same problem, notifyItemRangeChanged() call didn't help while notifyDataSetChanged() did (though stopped the animation). But I am using the ItemTouchHelper on the RecyclerView (to allow for moving items around), and it became obvious that this class was causing the trouble.
The only difference in my case is that to reproduce this overlap-after-delete bug, user has to long press on an item while deleting it.
After I modified the overriden isLongPressDragEnabled() method of ItemTouchHelper.Callback to return false instead of true, the issue was solved.

A:   lastImages.remove(position); (lastImages equals your array list)
  newContentAdapter.notifyDataSetChanged();

it is works. You have to remove it in your array not item. then notify adapter. Thats all

A: for me notifyItemRemoved and notifyDataSetChanged doesnt work. I tried everything , only solution that worked for me is calling or reloading recycler view inside onSwiped method!

A: you don't have to create new reference of place list.that need to declared  as array list. you can't add or remove a object from list. you can do that only with arraylist.
change this lines
private List<Place> placeList;

Place place = placeList.remove(position);

to
   private ArrayList<Place> placeList;
// other codes
   placeList.remove(position);
// print placeList to confirm
   notifyItemRemoved(position);

A: I had this issue
when I'm using notifyDataSetChanged() it works fine but I wanted the animation so I used notifyItemRemoved(position) for animation then I used notifyDataSetChanged() but I delayed the interval between those functions
I made extension for it you can use it on any RecylcerView
fun RecyclerView.removeItem(position: Int){
   adapter?.notifyItemRemoved(position)
   handler.postDelayed({
       adapter?.notifyDataSetChanged()
   },300)
}

A: You need to update you adapter;
Create method in Adapter class where you will be put your data.
For example : setData(List<Place> data);
When last item in list you need to write: adapter.setData(null);
I had the same problem. Just set list = null. It's all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ WinApi CreateProcess Unable To Create Child Process With Environment Block I need help with creating child process inheriting the new temporary Path environment variable then using the child process, it will run the process inside new folder specified in the Path.
Example, I add C:\Test into Path environment variable,and then i wan't to run a program by using cmd.exe as the child process
I'm having problem to create process by using the line below,it will pop up message unable to run the child process
Utilities::createProcess(_T("C:\\Windows\\system32\\cmd.exe"),_T(""),txtbuff);
// txtbuff is a WCHAR with size of 4096
// it contains the concatenation of _T("Path=C:\\Test;\0"); and pszOldPath
// pszOldPath get its value from GetEnvironmentVariable(_T("PATH"), pszOldPath,4096);
// The concantenated string will have the form of _T("Path=path1\0path2\0....\0\0");

If i pass NULL as my environment block,I'll be able to execute my child process but it won't inherit the new Path environment variable thus cmd.exe cannot run a program that is not specified in current path environment
Utilities::createProcess(_T("C:\\Windows\\system32\\cmd.exe"),_T(""),NULL);

This is my code:
// Utilities.h
namespace Utilities
{
    bool createProcess(LPCWSTR filename,LPWSTR arg,LPTSTR envpath)
    {
        DWORD dwRet;
        LPTSTR pszOldVal;
        TCHAR pszDest[BUFSIZE] = _T("");
        pszOldVal = (LPTSTR) malloc(BUFSIZE*sizeof(TCHAR));
        if(envpath != NULL)
        {
            dwRet = GetEnvironmentVariable(_T("PATH"), pszOldVal, BUFSIZE);
            if(!dwRet)
            {
                MessageBox(NULL,_T("Get environment variables failed."),_T("Error"),MB_OK);
                return false;
            }
            else
            {
                StringCchCat(pszDest,BUFSIZE,_T("Path="));
                StringCchCat(pszDest,BUFSIZE,envpath);
                StringCchCat(pszDest,BUFSIZE,_T(";\0"));
                StringCchCat(pszDest,BUFSIZE,pszOldVal);
                //MessageBox(NULL,pszDest,_T("Environtment Variables"),MB_OK);
            }
        }
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory(&si, sizeof(si));
        si.cb= sizeof(si);
        ZeroMemory(&pi, sizeof(pi));
        if(!CreateProcess(filename,arg,NULL,NULL,NULL,NULL,pszDest,NULL,&si,&pi))
        {
            MessageBox(NULL,_T("Unable to create process."),_T("Error"),MB_OK);
            return false;
        }
        //WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        free(pszOldVal);
        return true;
    }
}
// Main.cpp
// At Wnd Proc
LRESULT CALLBACK(......)
{
case WM_COMMAND:
    switch(wParam)
    {
        case ID_TEST:
            Utilities::getDlgText(hWnd,ID_INPUT_CPP,txtbuff);
            if(_tcscmp(txtbuff, _T("")) == 0)
            {
                MessageBox(NULL,_T("Please make sure you select folder."),_T("Error"),MB_OK);
                break;
            }
            // Environtment variable"MyVar=MyValue\0MyOtheVar=MyOtherValue\0\0"

// This is where Im having problem right now
            Utilities::createProcess(_T("C:\\Windows\\system32\\cmd.exe"),_T(""),txtbuff,NULL);
            break;
    }
    return true;
}

Really need someone to enlighten me with the answer

A: // Utilities.h
namespace Utilities
{
    bool createProcess(LPCWSTR filename, LPWSTR arg, LPWSTR envpath)
    {
        std::vector<WCHAR> oldPath;
        std::vector<WCHAR> newPath;
        DWORD dwOldLen = 0;

        if(envpath != NULL)
        {
            DWORD dwLen = GetEnvironmentVariable(L"PATH", NULL, 0);
            if (dwLen) {
                oldPath.resize(dwLen);
                dwOldLen = GetEnvironmentVariable(L"PATH", oldPath.data(), dwLen);
                if(dwOldLen + 1 != dwLen)
                {
                    MessageBox(NULL,_T("Get environment variables failed."),_T("Error"),MB_OK);
                    return false;
                }
            }
            size_t newLen = dwOldLen + wcslen(envpath) + 8; //8 for "path=" ";" and double null terminating
            newPath.resize(newLen);
            std::fill(newPath.begin(), newPath.end(), 0);
            memcpy(newPath.data(), L"Path=", 5 * 2);
            memcpy(newPath.data() + 5, oldPath.data(), dwOldLen * 2);
            memcpy(newPath.data() + 5 + dwOldLen, L";", 2);
            memcpy(newPath.data() + 6 + dwOldLen, envpath, wcslen(envpath) * 2);
        }
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory(&si, sizeof(si));
        si.cb= sizeof(si);
        ZeroMemory(&pi, sizeof(pi));
        if(!CreateProcess(filename,arg,NULL,NULL,NULL,CREATE_UNICODE_ENVIRONMENT,newPath.data(),NULL,&si,&pi))
        {
            MessageBox(NULL,_T("Unable to create process."),_T("Error"),MB_OK);
            return false;
        }
        //WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return true;
    }
}


text:
Q: Error trying to manage remote computers on a domain I am having trouble managing a computer that is within my domain.
Login to our DC, I right click the computer, and select Manage:
After connecting to a domain joined computer(windows 7), on the Local Users and Groups I have a Red cross, with an error that I do not have access to it.
I suspect that the local user (whom have local admin rights - don't ask!  ) has done some configurations to it.
What are my options? if I do NOT have physical access to this computer?

*

*If I disable the computer from the domain - will that be good?

*any startup script?

My DC is W2K3 R2
His system is either W7 64bit

A: It's possible that the user removed the default nesting of "DOMAIN\Domain Admins" into the local "Administrators" group. Since the user has "Administrator" rights on the PC they can do that.
You could use "Restricted Group" policy to "force" this nesting, but the user could always take a virtual "crowbar" to their machine's registry and break Group Policy processing (since they have Administrator rights). Odds are good they won't do this, but they could.
Disabling the Computer Object would prevent anyone from logging-on with a domain account on the PC while attached to the network. It would be trivial to disconnect the network cable, logon with cached credentials, and re-connect the network cable, though.
This sounds like a management problem and not a technical problem. Assuming the user actually has done this I would think that running this problem up the management chain (since the user is, in effect, "breaking" an IT resource) is probably your best course of action. Trying to "fix" it with a technical "arms race" is a lose / lose scenario for you and the company. The computer doesn't belong to the user and they shouldn't be treating it like it does.

A: I know this thread is extremely old but this is actually a very simple fix.  RPC has many spokes to its wheel. One of them allows the Computer Management remote access but this is linked to the Remote Registry . Simply enable remote registry on your workstation in your domain.


text:
Q: A problem with FindRoot I have the following
With[{p2 = 0.75}, FindRoot[1/(64 (p1 - p2)^2 (-(-1 + p2) p2)^(
 3/2) (-1 + p1 + p2)^2) (1 - p1) p1 (-128 (-(-1 + p1) p1)^(3/2) (-1 + p2)^2 p2^2 + (384 (-1 + p1)^3 p1^3)/Sqrt[1/(p2 - p2^2)] + 128 Sqrt[-(-1 + p1) p1] (-1 + p2)^3 p2^3 (-3 + 2 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)]) + 128 Sqrt[1/(p1 - p1^2)] (3 (-1 + p1) p1 (-1 + p2)^3 p2^3 - (-1 + p2)^4 p2^4 + (2 (-(-1 + p2) p2)^(7/2))/Sqrt[1/(p1 - p1^2)] + ((-1 + p2)^4 p2^4)/(((-1 + p2) p2)/((-1 + p1) p1))^(3/2) + 3 (-1 + p1)^4 p1^4 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)] - 6 (-1 + p1)^4 p1^4 (((-1 + p2) p2)/((-1 + p1) p1))^(3/2)) + 4 (1 - p1) p1 (-128 (-(-1 + p2) p2)^(5/2) - 96/(1/(p2 - p2^2))^(5/2)) + 256 (-1 + p1)^2 p1^2 ((-(-1 + p2) p2)^(3/2) + 3/(1/(p2 - p2^2))^(3/2))) == 0, {p1, 0.5}]]

which produces the solution
{p1 -> 0.882142}

Now, I try to generate a series of such solution. I start by creating the equation
eqn = 1/(64 (p1 - p2)^2 (-(-1 + p2) p2)^(3/2) (-1 + p1 + p2)^2) (1 - p1) p1(-128 (-(-1 + p1) p1)^(3/2) (-1 + p2)^2 p2^2 + (384 (-1 + p1)^3 p1^3)/Sqrt[1/(p2 - p2^2)] + 128 Sqrt[-(-1 + p1) p1] (-1 + p2)^3 p2^3 (-3 + 2 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)]) + 128 Sqrt[1/(p1 - p1^2)] (3 (-1 + p1) p1 (-1 + p2)^3 p2^3 - (-1 + p2)^4 p2^4 + (2 (-(-1 + p2) p2)^(7/2))/Sqrt[1/(p1 -p1^2)] + ((-1 + p2)^4 p2^4)/(((-1 + p2) p2)/((-1 + p1) p1))^(3/2) + 3 (-1 + p1)^4 p1^4 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)] - 6 (-1 + p1)^4 p1^4 (((-1 + p2) p2)/((-1 + p1) p1))^(3/2)) +4 (1 - p1) p1 (-128 (-(-1 + p2) p2)^(5/2) - 96/(1/(p2 - p2^2))^(5/2)) + 256 (-1 + p1)^2 p1^2 ((-(-1 + p2) p2)^(3/2) + 3/(1/(p2 - p2^2))^(3/2))) == 0 /. p1 -> p1[p2]

and attempt to setup an initial condition so that I can then use NDSolveValue. However, something goes wrong. The following initial condition should output {p1 -> 0.882142} (or should it?). It seems to do nothing.
p11 = p1[0.75] /. FindRoot[eqn /. p2 -> .75, {p1[.75], .75}]

What am I doing wrong?

A: If I understand your question right you want to solve an equation depending on tw0 variables p1,p2.
expr[p1,p2]:=((1 - p1) p1 (-128 ((1 - p1) p1)^(3/2) (-1 + p2)^2 p2^2 + (
  384 (-1 + p1)^3 p1^3)/Sqrt[1/(p2 - p2^2)] +
  128 Sqrt[(1 - p1) p1] (-1 + p2)^3 p2^3 (-3 +
     2 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)]) +
  128 Sqrt[1/(
   p1 - p1^2)] (3 (-1 + p1) p1 (-1 + p2)^3 p2^3 - (-1 +
        p2)^4 p2^4 + (2 ((1 - p2) p2)^(7/2))/Sqrt[1/(
     p1 - p1^2)] + ((-1 +
        p2)^4 p2^4)/(((-1 + p2) p2)/((-1 + p1) p1))^(3/2) +
     3 (-1 + p1)^4 p1^4 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)] -
     6 (-1 + p1)^4 p1^4 (((-1 + p2) p2)/((-1 + p1) p1))^(3/2)) +
  4 (1 - p1) p1 (-128 ((1 - p2) p2)^(5/2) - 96/(1/(p2 - p2^2))^(
     5/2)) + 256 (-1 + p1)^2 p1^2 (((1 - p2) p2)^(3/2) +
     3/(1/(p2 - p2^2))^(3/2))))/(64 (p1 - p2)^2 ((1 - p2) p2)^(
3/2) (-1 + p1 + p2)^2)

ContourPlot shows the possible solutions p1[p2] in the range 0<p1,p2<1
ContourPlot[Evaluate[expr[p1,p2] == 0], {p1, 0, 1}, {p2, 0, 1}, Exclusions -> None,MaxRecursion -> 5, FrameLabel -> {p1, p2},WorkingPrecison->50]

A: Clear["Global`*"]

expr = ((1 -
        p1) p1 (-128 ((1 - p1) p1)^(3/2) (-1 +
            p2)^2 p2^2 + (384 (-1 + p1)^3 p1^3)/Sqrt[1/(p2 - p2^2)] +
        128 Sqrt[(1 - p1) p1] (-1 + p2)^3 p2^3 (-3 +
           2 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)]) +
        128 Sqrt[1/(p1 -
             p1^2)] (3 (-1 +
              p1) p1 (-1 + p2)^3 p2^3 - (-1 +
               p2)^4 p2^4 + (2 ((1 - p2) p2)^(7/2))/
            Sqrt[1/(p1 -
                p1^2)] + ((-1 +
                 p2)^4 p2^4)/(((-1 + p2) p2)/((-1 + p1) p1))^(3/2) +
           3 (-1 + p1)^4 p1^4 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)] -
           6 (-1 + p1)^4 p1^4 (((-1 + p2) p2)/((-1 + p1) p1))^(3/2)) +
        4 (1 - p1) p1 (-128 ((1 - p2) p2)^(5/2) - 96/(1/(p2 - p2^2))^(5/2)) +
        256 (-1 + p1)^2 p1^2 (((1 - p2) p2)^(3/2) +
           3/(1/(p2 - p2^2))^(3/2))))/(64 (p1 - p2)^2 ((1 - p2) p2)^(3/
         2) (-1 + p1 + p2)^2) // Simplify;

The domain over which expr is real is given by FunctionDomain
fd = FunctionDomain[expr, {p1, p2}]

(* 0 < p1 < 1 && 0 < p2 < 1 && p1 - p2 != 0 && p1 + p2 != 1 *)

Simplifying expr within the specified domain
expr2 = expr // FullSimplify[#, fd] &;

The effect of the simplification is significant
LeafCount /@ {expr, expr2}

(* {335, 184} *)

Since you are interested in expr2 == 0, it is equivalent to Numerator@expr2 == 0
LeafCount[Numerator@expr2]

(* 166 *)

The simplified form plots more efficiently and precisely
ContourPlot[Numerator@expr2 == 0, {p1, 0, 1}, {p2, 0, 1},
  Exclusions -> {p1 == p2, p1 + p2 == 1},
  MaxRecursion -> 5,
  FrameLabel -> {p1, p2}] // Quiet

**EDIT:**

Clear["Global`*"]

expr[p1_, p2_] = ((1 -
       p1) p1 (-128 (-(-1 + p1) p1)^(3/2) (-1 +
           p2)^2 p2^2 + (384 (-1 + p1)^3 p1^3)/Sqrt[1/(p2 - p2^2)] +
       128 Sqrt[-(-1 + p1) p1] (-1 + p2)^3 p2^3 (-3 +
          2 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)]) +
       128 Sqrt[1/(p1 -
            p1^2)] (3 (-1 +
             p1) p1 (-1 + p2)^3 p2^3 - (-1 +
              p2)^4 p2^4 + (2 (-(-1 + p2) p2)^(7/2))/
           Sqrt[1/(p1 -
               p1^2)] + ((-1 + p2)^4 p2^4)/(((-1 + p2) p2)/((-1 + p1) p1))^(3/
              2) + 3 (-1 + p1)^4 p1^4 Sqrt[((-1 + p2) p2)/((-1 + p1) p1)] -
          6 (-1 + p1)^4 p1^4 (((-1 + p2) p2)/((-1 + p1) p1))^(3/2)) +
       4 (1 - p1) p1 (-128 (-(-1 + p2) p2)^(5/2) -
          96/(1/(p2 - p2^2))^(5/2)) +
       256 (-1 + p1)^2 p1^2 ((-(-1 + p2) p2)^(3/2) +
          3/(1/(p2 - p2^2))^(3/2))))/(64 (p1 - p2)^2 (-(-1 + p2) p2)^(3/
        2) (-1 + p1 + p2)^2);

expr2[p1_, p2_] =
  FullSimplify[expr[p1, p2], FunctionDomain[expr[p1, p2], {p1, p2}]];

LeafCount /@ {expr[p1, p2], expr2[p1, p2]}

(* {341, 184} *)

Manipulate[
 Plot[expr2[p1, p2], {p1, 0.9, 1}], {p2, 0.9001, 0.9999, 0.0001,
  Appearance -> "Labeled"}]
(* *)


text:
Q: Tikz for sections. How to make box length scale with its text inside Problem description
I am trying to make some custom Tikz sections, but I am lost at finding a way to make the Tikz box stretch accordingly to its text inside. In this example "Professional Experience" is too long for the lengths I have defined.

with associated code:
\documentclass{article}
\usepackage{geometry}
\usepackage[explicit]{titlesec}
\usepackage{tikz}
\usetikzlibrary{shapes,shadows,calc}
\usetikzlibrary{positioning,calc}

\definecolor{lightorange}{HTML}{ffa500}

\newcommand\SecTitle[4]{%
    \begin{tikzpicture}

    \node (A) [rectangle,minimum width=\textwidth, minimum height=1cm,color=white,fill=white, text width=\textwidth+3cm,align=left] {};
    \draw (-7.2,0) -- (\textwidth,0);
    \fill[fill=lightorange] (A.north west) -- ($(A.north west)+(3.5cm,0)$) -- ($0.45*(A.north west)-0.5*(A.north west)-(0.5*\textwidth-2.5cm,0)$)--($(A.south west)+(3.5cm,0)$)--(A.south west);
    \node [color=white](A.north west) at ($0.5*(A.north west)-0.5*(A.north west)-(0.5*\textwidth-1cm,0)$) {\hspace{-1.25cm}\huge\textbf{\textsf{#4}}};

    \end{tikzpicture}
}
\titleformat{name=\section}
{\normalfont}{}{0em}
{\SecTitle{east}{west}{0\paperwidth}{#1}}

\begin{document}
    \newgeometry{left=1cm,right=1cm}
    \section{Education}
    \section{Professional Experience}
\end{document}

What I have tried
I looked at the CTAN pdf for tiks but have not found what I am looking for. I searched this Stack as well with no success. I tried changing the order in which the commands are written but that doesn't fix it.
Does anyone know how I can achieve what I am looking for ?


text:
Q: how to define the number of digits after second in timestamp of spark streaming data? My timestamp in real data would be like
this or as shown below
2018-02-28T00:05:20.3717898Z
2018-02-28T00:05:23.6589778Z
2018-02-28T00:05:23.9119922Z
2018-02-28T00:05:25.4230787Z
2018-02-28T00:05:25.6710929Z
2018-02-28T00:05:26.4271361Z

And I use this code to read the data
userSchema=StructType().add('time','timestamp')
s=spark.readStream.schema(userSchema).csv('xxxx')

The result is like
this
Complete no idea how it happened.


text:
Q: SIpml5 demo not working with asterisk 11.9.0 I am trying to configure an example for SIPml5 and i found this info from https://wiki.asterisk.org/wiki/display/AST/Asterisk+WebRTC+Support.
I have asterisk 11.9.0 installed and downloaded source of SIPml5 from http://code.google.com/p/sipml5/source/checkout
I copied sample code into web root directory and example loaded successfully and also able to register 2 extensions.
I have tried both browser Google Chrome and Firefox with their latest versions.
For asterisk, I made some configuration like below.
Please check : http://pastebin.com/7KCvtcNf
For Outbound calls :
     when i am dialling 8002 -> 8001 every time Chrome Browser asking for allow microphone. Is there any way to disable asking permission and allowing it by default ?
when i allow microphone then SIpml5 phone showing like "Not Allow".
Here is the asterisk logs : http://pastebin.com/JZeDjyay
For Incoming calls :
    When call come to browser,And allow microphone then Call rejected and asterisk showing like "Got SIP response 603 "Failed to get local SDP" in asterisk CLI.
But After some google i found new link https://code.google.com/p/sipml5/wiki/Downloads for "SIPml-api.js" and after replacing that JS File Calls are comming in browser even i am able to answer that calls,Also in browser it says "In call" but in asterisk CLI it keep showing ringing and other end showing like "remote ringing" .
Here is the asterisk logs : http://pastebin.com/e8Ap3bhq
Can anyone please let me know what am i doing wrong?

A: If you are going to test webRTC, i successfully tested the Flashphoner Web Call Server with Asterisk 1.8.x versions using different call scenarios. Regarding sipML5, i would suggest you to please try using this tutorial by Sanjay Willy : http://highsecurity.blogspot.com/2012/12/webrtc-and-asterisk-11-using-sipml5.html
I hope it will be helpful for you.
Regards,


text:
Q: Chrome Angular Unchecked runtime.lastError: The message port closed before a response was received I am getting the following error in Chrome on Mac (Version 71.0.3578.98) while accessing my angular app:
targets/showTargetsByStream:1 Unchecked runtime.lastError: The message port closed before a response was received.
My app is accessing REST api hosted by a node express server.
Above error is coming for every page, like navigating to new URL within the app.
Also noticed that Safari is not throwing above error.
Appreciate any help in resolving this error.

A: I've experienced the same problem and noticed that it depends on running extensions.
Try disabling them (or you can use incognito mode if your settings do not allow extensions) to check if this is the cause. If so, you can enable them one by one and identify the guilty one.
In my case it was the Pinterest extension that causes the issue.

A: Click on the gear icon in the console window and put a tick in the "Selected context only" box.
Selected context only ignores all of the nested browser extension contexts.

A: for me, It was the "Stayfocusd" extension that causes the problem. By removing it, solves my problem.

A: I've had the same issues as to where i'm running my react app and it would run this error several times in the Console log.
What I've done to try and fix this issue is that I disabled a few of my extensions
(Piggy - Automatic Coupons & Cash Back "Extension" to be more specific) then I refreshed the page and now I don't get this stressful error:
Unchecked runtime.lastError: The message port closed before a response was received.
Other extensions may cause this issue for you but the Piggy - Automatic Coupons & Cash Back extension is the main extension that was causing this issue.
Good luck!

A: for me, "BuiltWith Technology Profiler" extension cause this error and when uninstall it, error not occur again

A: It was the HonorLock extension causing this for me.

A: In my case was Norton Extension...

A: It was "Natural Reader Text to Speech" for me.


text:
Q: Create an Eclipse Template for Custom Indentation for Maps Is there a way to create a custom indentation for an object type in Eclipse?
I store unit tests in groovy beans. As different tests contain different levels of complexity I want to force a certain format such at below:
overrideExampleTest(OverrideTestCaseData,
    name        : 'overrideExampleTest',
    description : 'ExampleFormatting for StackOverflow',
    overrideTestCaseData : [
                            field1     : 'value1',
                            field20    : 'value20',
                            nestedList : [
                                            [                                               [
                                                 type       : 'SSL',
                                                 quantity  : 1,
                                                 termYears : 1,
                                            ]
                            ]]
)

I like the clean look and easy readability. If I use the default Correct Indentation I see the following:
overrideExampleTest(OverrideTestCaseData,
name        : 'overrideExampleTest',
description : 'ExampleFormatting for StackOverflow',
overrideTestCaseData : [
       field1     : 'value1',
       field20    : 'value20',
       nestedList : [
              [                                                                                [
                           type       : 'SSL',
                           quantity  : 1,
                           termYears : 1
                     ]
              ]]
       )

Thank you in advance for your help!


text:
Q: Emacs: How to capitalize all keywords (example in SQL) For example, I have the following example SQL document in SQL[ANSI] mode:
create table title_price as
select title, price
from frumble
group by title, price
order by title;

select *, count(*)
from frumble
group by title, price
order by title;

Any ideas on how to capitalize the keywords, like select, from, group, by, table, as, etc?
They are already shown in blue font in my editor.

A: Here is my attempt at solution (assuming you want to upcase MySQL keywords)
(defun point-in-comment ()
  (let ((syn (syntax-ppss)))
    (and (nth 8 syn)
         (not (nth 3 syn)))))

(defun my-capitalize-all-mysql-keywords ()
  (interactive)
  (require 'sql)
  (save-excursion
    (dolist (keywords sql-mode-mysql-font-lock-keywords)
      (goto-char (point-min))
      (while (re-search-forward (car keywords) nil t)
        (unless (point-in-comment)
          (goto-char (match-beginning 0))
          (upcase-word 1))))))

After evaluating this function, just do M-xmy-capitalize-all-mysql-keywordsRET. The advantage of this solution is that it picks up the keywords from Emacs sql-mode, you do not need to specify them.
Also I assumed you meant you wanted to upcase the words

A: I've written sql-upcase.el for upper-casing keywords and function names in sql-mode and/or sql-interative-mode.
It provides sql-upcase-region and sql-upcase-buffer commands for processing pre-existing SQL, but differs significantly from the other solutions in that it also provides a sql-upcase-mode minor mode which processes text automatically as it is inserted. This means (a) that SQL keywords are upcased as you type them, and (b) that you can paste SQL into a sql-mode buffer, and all of the keywords will automatically be upcased.
This will hopefully Just Work for all the SQL products supported by Emacs, as it uses the keyword regexps defined for the buffer's sql-product. This was initially inspired by the use of font-lock keywords in Douglas La Rocca's function for upper-casing all PostgreSQL keywords in a buffer, which can be found on the EmacsWiki (which also bears similarities to the method used in user2053036's accepted answer here).
Follow the link for more details.

A: Try out this function:
(defun capitalize-sql-in-buffer ()
  (interactive)
  (let ((regex
         (format
          "\\_<%s\\_>"
          (regexp-opt
           '("create" "table" "select"
             "from" "group by" "order by" "as"
             "count")))))
    (goto-char (point-min))
    (while (re-search-forward regex nil t)
      (let ((beg (match-beginning 0))
            (end (match-end 0))
            (str (match-string 0)))
        (delete-region beg end)
        (insert (upcase str))))))

You can add more keywords as needed, I'm not really proficient in SQL.

A: You can use M-x replace-regexp.
Just try these commands.
ESC M-<
M-x replace-regexp RET
\(select\|from\|group\|by\|table\|as\) RET
\,(capitalize \1) RET

Input:
create table title_price as
select title, price
from frumble
group by title, price
order by title;

select *, count(*)
from frumble
group by title, price
order by title;

output:
create Table title_price As
Select title, price
From frumble
Group By title, price
order By title;

Select *, count(*)
From frumble
Group By title, price
order By title;

A: sqlup-mode capitalizes keywords as you type them, and provides a function to capitalize keywords in the selected region.

A: Here is a hacky way that I use for capitalizing keywords in sql-interactive-mode buffers:
(defun upcase-last-keyword ()
  (when (and (= last-input-event ? )
             (save-excursion
               (backward-char 2)
               (eq (face-at-point) 'font-lock-keyword-face)))
    (upcase-word -1)))
(add-hook 'sql-interactive-mode-hook
          (lambda ()
            (make-local-variable 'post-self-insert-hook)
            (add-hook 'post-self-insert-hook #'upcase-last-keyword))))


text:
Q: Sitecore Installation SQL Issue I'm trying to install sitecore using the Sitecore Instance Manager and on the step where I need to choose network service folder I'm getting this error.
I've provided full access permissions to this folder to everyone but it wasn't help.
Do anybody have any idea how to solve it?

A: It is known issue. Here is link to workaround.
You should change account that run SQL server instance and grant that account full rights to folder where you will install your instances.


text:
Q: Python check if input number is string When I run the below code, it always returns Number please no matter what I enter. Why does this happen?
number = input("please type number: ")
if type(number) != int:
    print('Number please')
else:
    print('number')

A: Try this, this should work:
string = input()
if string.isalpha():
   print("It is a string. You are correct!")
elif string.isdigit():
   print("Please enter a string.")
else:
   print("Please enter a proper string.")

The .isalpha is used for checking if it's a string. The .isdigit is used for checking if it's a number.
Hope it helps :)


text:
Q: Lost in Space (1965) first season sets I've been watching the "original" Lost in Space (1965), "rediscovering" it having only vague memories of watching it in its original run. At the start of the first broadcast episode (not referring to the unaired pilot which I haven't seen), pre-launch "news coverage" tours the Jupiter 2, showing its two decks, amenities and general interior layout. While situated on the planet in the first season, the upper deck is about a foot or so above "ground", placing the lower deck "buried" below the surrounding landscape. The upper deck has large windows, and a door, affording views into the ship from outside and outside the ship from within. Movement between decks may be accomplished by ladder or functioning elevator.
Now to my (production context) question...
Was that just one complete set - the spaceship and landscape, serving for both interiors and exteriors, or was there a second ship set (or sets) for interiors (especially for scenes "downstairs")?
Since the ship was seen to have several bedrooms as well as dining area and workspaces, was that all accommodated within a single set, or were multiple sets required (almost seems bigger on the inside)?
There are establishing shots which are pretty obviously done using miniatures and/or paintings, but in my question I am referring specifically to sets hosting acted scenes - where the actors move around the sets - going in and out of the ship, riding the elevator, entering rooms, etc..

A: The upper and lower decks were separate sets. In the original pilot, the ship ("Gemini 12") only had one deck, with no living quarters. When the show went to series, the premise was retooled to add Dr. Smith and the Robot, along with a lower deck. The footage from the pilot was chopped up and integrated with several of the first season episodes, which is why the sets sometimes change within the same episode. The most obvious visual differences between the pilot set and series set were the airlock (which was not present in the pilot), the porthole next to the airlock, and the elevator to the lower deck. The upper deck set seems pretty faithful to the established dimensions of the ship, but that all goes out the window with the lower deck, which is far too large to fit.
There was also a full-scale mockup of the Jupiter 2, without an interior, which was only used in a few episodes (most notably in a third season episode where they go back to a 1940's version of Earth and are mistaken for a UFO). You can also see this mockup version in the first season episode where, after crash landing on the planet, they send the Robot out to take soil samples. In that scene, the ship is sitting noticeably higher on the ground, and you can see more of the lower portion of the ship. I have no evidence for this, but my assumption is that they used the mockup for that one scene while they rebuilt the regular set to add the airlock, elevator, and other series features.
There is a book called "Lost In Space Design: No Place to Hide" by Robert Rowe, which goes into much detail about the design of the original pilot ship (the pilot episode was called "No Place to Hide"). Another book called "The Saucer Fleet", by Jack Hagerty, also contains extensive coverage of the Jupiter 2, including features that were part of the original ship design but never seen in the show, such as the loading ramp for the Chariot and engine access hatches.


text:
Q: keras fit_generator reading chunks from hdfstore I try to build a generator for a Keras model which will be trained on a large hdf store.
To speed up the training, I pre-calculated all features incl. one-hot encoding already in the hdfstore. So the call from that should be straight forward.
To feed chunks of my data into the network, I try to use fit_generator, but struggle to get it up and running.
The generator:
def myGenerator(myStore, generateFrom,generateTo):
 # Create empty arrays to contain batch of features and labels#
    while True:
        X = pd.read_hdf(myStore,'X',start=generateFrom,stop=generateTo)
        y = pd.read_hdf(myStore,'y',start=generateFrom,stop=generateTo)
        yield X,y

Network and fitting:
def get_model(shape):
    '''Create a keras model.'''
    inputlayer = Input(shape=shape)

    model = BatchNormalization()(inputlayer)
    model = Dense(1024, activation='relu')(model)
    model = Dropout(0.25)(model)
    model = BatchNormalization()(inputlayer)
    model = Dense(512, activation='relu')(model)
    model = Dropout(0.25)(model)
    model = BatchNormalization()(inputlayer)
    model = Dense(256, activation='relu')(model)
    model = Dropout(0.25)(model)
    model = BatchNormalization()(inputlayer)
    model = Dense(128, activation='relu')(model)
    model = Dropout(0.25)(model)

    # 11 because background noise has been taken out
    model = Dense(2, activation='tanh')(model)

    model = Model(inputs=inputlayer, outputs=model)

    return model
shape = (6603,10000)
model = get_model(shape)
model.compile(loss='mean_squared_error', optimizer=Adam(), metrics=['accuracy'])
#X = generator(myStore)
#Xt = generator(myStore)
labelbinarizer = LabelBinarizer()
y = labelbinarizer.fit_transform(y)
#yt = labelbinarizer.fit_transform(yt)

generateFrom = 0
for i in range(10):
    generateTo=generateFrom+10000
    model.fit_generator(
        generator=myGenerator(myStore,generateFrom,generateTo),
        epochs=1,
        steps_per_epoch=X[0].shape[0] // 1000)
    generateFrom=generateTo

I have tried both, to have the fit_generator within a loop and plug in the range (as shown above), but also to handle the range inside the generator. Both does not work. Currently running into
TypeError: 'generator' object is not subscriptable

Likely I have some misunderstanding how fit_generator() is supposed to be used in this context. Most examples out there are around generating tensors from pictures.
Any hint is appreciated.
Thanks

A: The function read_hdf returns a panda object, you need to convert it to numpy array.


text:
Q: XPath 1.0 Code Selects Wrong Maximum Value I am trying to use XPath 1.0 to select the maximum double value in an XML document. I understand that XPath 1.0 doesn't support the Max function that would make this extremely easy, but the system I'm using only supports XPath 1.0 functions.
I'm not able to post the entire file due to length, but here is a sample of the document I'm scanning: https://codebeautify.org/xmlviewer/cbc93c7e.
I've tried this XPath Expression:
/site/forecast/datum[not(primary < preceding-sibling::datum/primary) and not (primary < following-sibling::datum/primary)]

But no matter what, it returns the wrong datum. It always returns:
<datum>
    <valid timezone="UTC">2019-04-04T06:00:00-00:00</valid>
        <primary name="Stage" units="ft">9.80</primary>
        <secondary name="Flow" units="cfs">3010.00</secondary>
        <pedts>HGIFE</pedts>
</datum>

I expect it to return the element with the maximum "primary stage" value like:
<datum>
    <valid timezone="UTC">2019-03-28T18:00:00-00:00</valid>
        <primary name="Stage" units="ft">13.10</primary>
        <secondary name="Flow" units="cfs">13400.00</secondary>
        <pedts>HGIFE</pedts>
</datum>

I understand it will return all those with the 13.10 primary stage, but that's okay. I'll select the first one it returns if I can just get it to that point.

A: Do note that you might have more than one maximum. Use:
/site/forecast/datum[not(primary < ../datum/primary)][1]

This select the element
<datum>
  <valid timezone="UTC">2019-03-28T18:00:00-00:00</valid>
  <primary name="Stage" units="ft">13.10</primary>
  <secondary name="Flow" units="cfs">13400.00</secondary>
  <pedts>HGIFE</pedts>
</datum>

Test it in http://www.xpathtester.com/xpath/4256aac47f4f0efc36e23a2f16183d90


text:
Q: How to pass the onClick() event to a child component from a button in the parent component in React? Let's say I have two components Component1 and Component2. I have a button in Component1.
const Component1 = () => {
    return(
        <div>
        <button onClick={()=>someExportFunc()}>Export</button>
        <Component2 />
    </div>
    )
}

My Component2.jsx is something like this.
import {ChartComponent} from '@xyz/charts';

const Component2 = () => {
    let chartInstance = new ChartComponent();

    return (
                <ChartComponent
                id='chart1'
                ref={chart = chartInstance => chart}

                >

                </ChartComponent>
        )

}

Now the function someExportFunc() is defined inside the {ChartComponent} being imported in Component2.jsx.
Had I used the button inside Component2, it would have worked simply. As in,
import {ChartComponent} from '@xyz/charts'

const Component2 = () => {
    let chartInstance = new ChartComponent();

    return (
                <button onClick={()=>someExportFunc()}>Export</button>
               <ChartComponent
                id='chart1'
                ref={chart = chartInstance => chart}

                >

                </ChartComponent>
        )

}

But how can I make it work as a button in Component1?
I am guessing it has something to do with defining state of the button and then passing the state down, but I don't exactly understand how the state of a button works. onClick() should be some instantaneous boolean, isn't it? By instantaneous, I mean it would change as soon as the 'click' is over.
Edit1: Okay, so the someExportFunc() is a library function defined in my import. It makes use of the chartInstance created in Component2. It's actual use case is
<button
   value='export'
   onClick={() => chartInstance.exportModule.export('PNG',
       `image`)}>
        Export
      </button>

So basically I want it so that when I click the button within Component1, it sends the onClick event to my ChartComponent in Component2.

A: we need to pass the function as a prop to the second component.
FirstComponent
<SecondComponent { ...data } onClick={ () => manageClick() } />

in the second Component use the onClick prop on click.
SecondComponent
<button onClick={onClick}>Click</button>

A: React uses one-way data binding, meaning parent to child in this case.
If Component 2 is a child of Component 1, define the function in Component 1 and pass the function and Chart Component as props and children respectively.
Parent:
const Component1 = () => {
  const someFunc = () => {...}
  return <Component2 someFunc={someFunc}> <ChartComponent/> </Component2>
}

Child:
const Component2 = (props) => {
  props.someFunc();
  return <div> {props.children} </div>
}


text:
Q: how filter all socket.io event data generically if i do
socket.emit("eventname",data);

I am emitting an event to socket. if I want filter this emission i would attach a function and use this function
function emit(socket,eventname,data)
{
  .. // process event data
  socket.emit(eventname,data); // emiting processed
}

but I want to overwrite the object in some way to generically all output (and input events data) to be processed or modified conveniently, as for example trimming strings of the objects. O also would add an filter for syntactic exception to avoid wrong formatted json that can collapse the process or a injection filter...
How to do it without directly modifying socket.io code but rewriting somehow. Sorry if this question is stupid.

A: You can just redefine socket.emit
socket.__emit = socket.emit

socket.emit = function (channel, data) {
  //process data;
  socket.__emit(channel, data);
};


text:
Q: Show path in Google Static maps I can show a path in Google Static Maps that is made of a collecion of points.
I can show a path in Google Static Maps that is made of enc of overview_polyline.
But, in most cases, I cannot show a path that has both:  points and enc.
Alsthough I see the path in regular Google-Maps.
Sometimes it does work as you can see in:
http://www.mobile-gap.com/where2go/launch.php?jump_to=9,13
But in most cases it shows only one or the other.
My app (trips and Events) enables the users to add a path that is a combination of both.

A: So the example in the question as the benchmark of implementation has this long URL in image tag "https://maps.googleapis.com/maps/api/staticmap?size=400x400&markers=color:0xFFFF00|label:1|40.74896068875827,-73.98549273862306&markers=color:0xFFFF00|label:2|40.7488758,-73.9680091&markers=color:0xFFFF00|label:3|40.705866,-74.00424&markers=color:0xFFFF00|label:4|40.7105139,-74.0155469&markers=color:0xFFFF00|label:5|40.6892494,-74.0445004&path=color:0x0000ff|weight:3|enc:kwuwFvhqbMbQ{i@lFqPpGmSn@uBiCuA_Am@o@g@k@i@sA}@eByA}AyA{AuAu@y@{@s@oEmDuJsH{HqGoFcFkCwBaAq@sEwD_@c@{@gAkBoCk@k@y@i@aCyAcEgDeA{@@WSMMGMIe@Us@]m@E]EMIw@C{ByAwByAt@eC@QJ_@FIJCJBz@vAv@AA|@d@Z@JRNbBdA\RPHtBvA^VPX^^pAhA|AAlAv@t@n@xAnBrAjB~@~@hHfGlHbHjR~N&path=color:0x0000ff|weight:3|enc:ivuwFrxmbMxC|BlDhCv@t@bFfFfA~@jAx@fCxAdECxBz@tA@tATnJlAtATrA^jAh@bG|DjAt@h@Tf@PvAPbA@rAOvOkCnEu@l@QZO\O|@s@tAaBnA_Bf@g@ZSd@]h@Wp@Sh@If@Ct@AzBJtDXf@Hr@N|Aj@zDlBtK~FbAd@fA^dARlAJrCPtKp@D\lCl@dAXtAl@|F|B~JfEnChAv@b@~@v@t@~@TZl@pAj@hBZlBCl@@r@P|G?ZLpEPbG@n@\vEj@hMBnTFpAx@vLp@~If@vGNzAVdBj@lBpAfC~@jBtAtDG|LjA|Bc@h@&path=color:0x0000ff|weight:3|enc:gkmwFp|tbMb@i@hAxB^v@xAC~DhHb@r@pBvDxAxCz@nBn@tB^xAjAjIJlAEHwCl@[HFXDCGh@o@v@@^q@Zo@HwD_@c@GW?UCEVMp@WhBIx@Cl@BrAFhAHvAEh@CTQn@_@l@i@b@c@R[Fs@@YCw@Sg@S_EcCcC_B{@dCqD}B[Q_A_@}@WoBk@&path=color:0x228B22|weight:3|40.7105139,-74.0155469|40.710611491308946,-74.01606188413086|40.710009675958524,-74.01634083386841|40.71043257379994,-74.01814327832642|40.70942214380081,-74.0224762910866|40.70942214380081,-74.0224762910866|40.708643372269236,-74.02586804028931|40.708643372269236,-74.02595387097779|40.6998918576991,-74.02623282071533|40.69009790752417,-74.03217659589234|40.68944709570568,-74.04419289227905|40.6892494,-74.0445004&key=AIzaSyBZ2ijM7ygGfp_BPNY2ClcoSexWta8rXXQ&language=en"
The point here is the markers are separated by "&" operator and path parameter is pretty straight forward has lat/lng coordinates separated by a "|" operator. For the enc parameter you can visit this link to find the encoded polyline. Create your polyines and get the encoded values. Finally merge the parameter same as given in the example and you will get the static map image as you want.
Hope this helps!!


text:
Q: Error when using binding_of_caller gem with Rubinius 2.1.0 Using binding_of_caller in the gem list on a Rubinius (2.1.0) environment triggers the following error, once the server launch:
NoMethodError at /
undefined method `caller_locations' on an instance of ActionController::RoutingError.

(Screenshot: https://www.dropbox.com/s/a8a7afzgwb5aq2k/Screen%20Shot%202015-01-13%20at%2010.58.36.png?dl=0?dl=1)
Here is the Gemfile:
group :development do
  gem 'spring'
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'quiet_assets'
end

This is caused by binding_of_caller because when removed, everythings works fine.
Do you have any idea of how to still work with binding_of_caller in rbx or do I have to drop it? Thanks.

A: Rubinius supports #caller_locations since the 2.4.0 version. The 2.1.0 is really old (Oct 18, 2013), I would suggest to upgrade straight to 2.4.1.


text:
Q: SBT can't resolve dependencies through proxy When I run sbt update i get this error
    :: problems summary ::
:::: WARNINGS
        ::::::::::::::::::::::::::::::::::::::::::::::

        ::          UNRESOLVED DEPENDENCIES         ::

        ::::::::::::::::::::::::::::::::::::::::::::::

        :: org.scala-sbt#sbt;0.13.8: several problems occurred while resolving dependency: org.scala-sbt#sbt;0.13.8 {default=[default(compile)]}:
    java.util.NoSuchElementException
    java.util.NoSuchElementException

        ::::::::::::::::::::::::::::::::::::::::::::::

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
unresolved dependency: org.scala-sbt#sbt;0.13.8: several problems occurred while resolving dependency: org.scala-sbt#sbt;0.13.8 {default=[default(compile)]}:
    java.util.NoSuchElementException
    java.util.NoSuchElementException
Error during sbt execution: Error retrieving required libraries
  (see /Users/$USER/.sbt/boot/update.log for complete log)
Error: Could not retrieve sbt 0.13.8

I've already set up the system to work with curl and homebrew using a proxy, but for some reason sbt won't work with the same settings. When I turn the proxy off, It just hangs for a few minutes before timing out and I don't get the aforementioned error.
I've also tried this, but without any luck
# export JAVA_FLAGS= -Dhttp.proxyHost=$domain -Dhttp.proxyPort=$portnum -Dhttp.proxyUser=$USER -Dhttp.proxyPassword=$password -Dhttps.proxyHost=$domain -Dhttps.proxyPort=$portnum -Dhttps.proxyUser=$USER -Dhttps.proxyPassword=$password -Dftp.proxyHost=$domain -Dftp.proxyPort=$portnum -Dftp.proxyUser=$USER -Dftp.proxyPassword=$password -Dhttp.nonProxyHosts=$noproxy -Dhttps.nonProxyHosts=$noproxy -Dftp.nonProxyHosts=$noproxy
    # java ${JAVA_FLAGS}

The method I used to make hombrew and curl work is
export http_proxy=$http_proxy
    export https_proxy=$http_proxy
    export ftp_proxy=$http_proxy
    export rsync_proxy=$http_proxy
    export HTTP_PROXY=$http_proxy
    export HTTPS_PROXY=$http_proxy
    export FTP_PROXY=$http_proxy
    export RSYNC_PROXY=$http_proxy

Any suggestions?
Thanks

A: I am not sure whether your JAVA_FLAGS included/exported to classpath or not, if not add it to classpath before trying this solution.
My Resoultion:
I don't know which IDE you are using, I faced same issue (I use IntelliJ 14). Try to relate to your IDE if you use different one, basically set it through VM arguments.
I have resolved this issue by adding vm arguments ...
Steps to add in IntelliJ:
File -> Default Settings -> under Build,Execution, Deployment
Build Tools -> SBT ->
JVM Options -> set in the "VM parameters" like this

-Dhttp.proxyHost=http://proxy.xxxx.com -Dhttp.proxyPort=8080 -Dhttps.proxyHost=http://proxy.xxx.com -Dhttps.proxyPort=8080 -XX:MaxPermSize=384M -Duser.home=/Users/yourusername/ -Dsbt.ivy.home=/Users/yourusername/.ivy2

Good Luck


text:
Q: How do I get Oauth.io to work with mobile browser full screen mode? I currently use oauth.io for login to fb, twitter, linked and instagram on a website application. Everything works fine accept for when the user hits the "Add to Home Screen" option and then uses the website by clicking on that home screen icon(fullscreen browser). I get a cross domain(I think)issue. I get this error right after login and no success function is run: "Unable to post message to http://www.example.com. Recipient has origin https://oauth.io."
Is there any reason that this only happens in the mobile fullscreen mode?


text:
Q: Can't upload audio file with PHP5.5.12 on WampServer 2.5 I have a problem with upload mode in PHP. Can you help me ?
My form in HTML:
<form action="upload_file.php" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit" value="ok">
</form>

My PHP code in 'upload_file.php':
<?php

if (!isset($_FILES['file'])){
    echo "Failed";
}
else{
    echo "All Ok";
}
?>

When I select image, text, zip, rar ... It report "All Ok". But, If I select audio or video, it report "Failed". So I can't upload audio file. What is wrong ? Thank you very much !.

A: Make sure that the size of your file does not exceed the limitations listed here (your php.ini file)
# The values are just for example!

; Maximum allowed size for uploaded files.
upload_max_filesize = 3M

; Must be greater than or equal to upload_max_filesize
post_max_size = 3M


text:
Q: Recover a not responding ssh server a machine with a postgres database (which is reponding fine) has a ssh service an nagios nrpe service.
Responds to ping.
Postgres is performing as expected. (apache connects from another host)
Nagios  check to port 5432(postgres is ok).
ssh does not connect (as shown above).
Access through tty has the same response as ssh (nothing shown on screen)
What can be done? I's a production server.
THanks.
[root@localmachne ~]# ssh remotemachine -vvvvvvvv
OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to remotemachine [X.Y.Z.T] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/identity type -1
debug3: Not a RSA1 key file /root/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /root/.ssh/id_rsa type 1
debug1: identity file /root/.ssh/id_dsa type -1

A: Your SSH key is corrupted. Connect with password authentication or the console and regenerate your SSH keys (or restore from a backup).


text:
Q: Why people rotate during flight in Rocket League? Why high level people on Rocket League rotate with their cars while they are flying? Do they fly faster or higher or what?

A: In addition to what @Koviko mentioned, another reason is for better control.  During eg. a tornado spin, as the bottom of your car spins quickly from pointing to the lower-left to the lower-right and back again, you can make micro-adjustments to adjust your car's path in the air much more quickly than you could if you only rotated your car along a single axis.

A: Your speed is identical, but spinning gives you the potential to:

*

*make slightly harder hits by using torque to add power the car's contact with the ball (this is the reason that flips result in harder hits than simply driving at a ball),

*make the resulting hit a bit tougher for the opponent to read, as the direction of your spin combined with your boost allows slight adjustments in midair,

*practice better midair car control since even a live match is still an opportunity to improve your skills, and/or

*make the resulting replay just a bit flashier, as spinning doesn't make the car any harder to control when you're used to it.


text:
Q: Twilio proxy + click to call I'm trying to combo the concepts found here (make a voice call with proxy) and here (click to call) but I'm running into a bit of a mental hurdle in that it seems to initialize a proxy call, you need to call a number. From the docs:

If your Twilio Phone Numbers are voice capable, you're now ready for a proxied voice conversation. Following the names from the previous steps, get Alice to make a call to her Proxy Identifier number. Twilio's Proxy service will then make a call from Bob's Proxy Number to his real number and connect the two calls.

What I'd like to do is have Alice click a button on her desktop, have the Proxy Identifier Number call her, then let Twilio's proxy make the call from Bob's proxy number to his real number and the two of them could chat.
Is there a way to trigger the call from the Proxy Identifier number to Alice?

A: You can use the Twilio REST API Calls Resource to initially trigger the call to connect the parties, using each participants proxy number as the respective CallerID. When they call or SMS each other back, the proxy session will be active.
Making Calls
TwiML™ Voice:  - Twilio


text:
Q: how to check the value of pointer (void) not be zero (Attempt to dereference a generic pointer) Sorry it must be very simple question , but since I tried in diffrenet ways without any success I have to ask here to be sure.
C programming :
There is a struct name rtg.
EDIT: type of mtch is LLIST
type of initial is LL_NODE
typr of obj is pointer (void)
.
Using gdb when I check
(gdb)  print *rtg->mtch->initial->obj
Attempt to dereference a generic pointer.

(gdb) print rtg->mtch->initial->obj

$10 = (void *) 0x4cc660
(gdb) x 0x4cc660
0x4cc660:       0x00000000

This null pointer causes segfault in my program. What I am looking for is simply how to check the value of what rtg->mtch->initial->obj is pointing not be zero? (to prevent above segfault) I mean if I check with
if (rtg->mtch->initial->obj) , it would just check if pointer obj , adress not be zero (this is not what I intend , I intend to check the value of that pointer not be zero (but when I use * before checking in gdb it says "Attempt to dereference a generic pointer".
So what is the correct way to check that value not be zero (and prevent this segfault)?
Edit : i had tried this
if (*((char *) rtg->mtch->initial->obj) != NULL)

but i got compile warning :

warning: comparison between pointer and integer

EDIT2 , here what are these defined in the source code
ECM_REQUEST is struct
ECM_REQUEST rtg;
in this struct defind mtch as LLIST mtch;
initial is LL_NODE
obj is a pointer
i want to check obj value not be zero
so now everything are clear about my question isn't it?
Thanks

A: You cannot dereference a generic pointer. The only solution I can think of is to make a temporary pointer to integer to check the value. Basically
int *tmp = rtg->mtch->initial->obj;
if (*tmp != 0)
/* the rest of your code here */

A cast could also work, but having a temporary pointer makes the code easier to read in my opinion.

A: The warning is because the left hand side is a dereferenced char * (in other words, a char) and the right hand side is a null pointer constant, in the form of a void *; You're converting a char value to a void * value... Perhaps you meant char **?
void *o = rtg == NULL                ? NULL
        : rtg->mtch == NULL          ? NULL
        : rtg->mtch->initial == NULL ? NULL
        : rtg->mtch->initial->obj;

if (o != NULL) { /* ... */ }

... Do note that it should be safe to change the type of o to any other object pointer (eg. your question seems to suggest char **?)


text:
Q: Why are relays so frequently driven by optocouplers? Since the advent of the many microcontroller development boards, like Arduino, there have been a number of relay modules sold to drive mains AC loads.
A lot of these seem to use an optocoupler, driver transistor and a relay to drive the load (example on Amazon)
Why are they implemented like this?
Some of my thoughts:

*

*Relays provide as good or better isolation than most optocouplers

*There is still a driver transistor present, so it is not component
saving

*There is still inductive kickback protection, so it is not
component saving

*Optocouplers are not as cheap as transistors, so additional cost compared to just a driver transistor

*There is no need to meet any regulatory requirements as these are DIY products

*I have never seen small mains relays driven by optocouplers in commercial equipment

*A number of these boards don't seem to be designed brilliantly (no regard to clearance or creepage), so even if the optocoupler is simply to provide two layers of isolation, the board fails at this.

A: I suspect a big part of the reason has to do with the idea that if there are two isolation barriers, there will continue to be an isolation barrier even if one is accidentally or intentionally bridged.  When working with circuits, especially if one is a klutz, one may sometimes briefly short things which really shouldn't be shorted (e.g. because a scope ground clip decides to come undone and flail itself across the board).  Adding an extra layer of isolation reduces the likelihood that such an accident will cause significant damage to anything.  Most mass-produced products will never be on anyone's workbench, much less a workbench belonging to a klutz, but many home-brew products will spend a great deal of time on such workbenches.  Further, home-brew boards are often made without solder mask, greatly increasing the likelihood that of stray ground clip or probe making an unwanted contact.
In addition to providing protection against accidental bridging, if there are two full isolation barriers it may be possible (if one is careful) to bridge one while doing diagnostics involving the other while maintaining an isolation barrier between the two main parts of the system.  For example, if one wants to determine the amount of time that elapses between the processor setting an output and a solenoid receiving power, one could start by confirming the relay-coil ground and contact-side ground were isolated, bridging the relay ground and CPU ground, and measuring the time between the CPU output and the relay coil.  One could then isolate the relay-coil ground and CPU ground and--after double-checking that they really were isolated, bridge the relay-coil ground and contact-side ground and measure timings between the coil and the things they control.  Performing such measurements in a system with only single isolation would probably require having a scope with two probes that were isolated from each other.  Such rigs exist, but they're generally expensive.

A: Relays actually provide rather poor AC isolation to a VERY noisy source of disturbances- a mechanical contact switching arcing as it switches a load that is inevitably more or less inductive, and often at mains voltage, with dv/dt that can be hundreds of volts per microsecond.
Cheap small relays typically are particularly bad, and making them better tends to make the relay more expensive, bigger and less efficient.
Circuits with multiple inputs and outputs are particularly prone.
When properly employed, an opto can help prevent disturbances caused through coil-contact coupling from affecting circuits.

There is no shortage of examples in this forum of grief from this source (relay plus random resets when loads are switched, for example), and plenty of examples of good robust appliance and industrial designs where optos are used in conjunction with relays.

A: I suspect that this is just a case of hobbyists who are trying to start a circuit board selling business. They may be complicating their board simply to make it look more complicated, because complication justifies the existence of electronics and appears to add value.
I'm sure if you contact the vendor, they will have a convincing story that their circuit is how it has to be done, and they have it ready-made, the easiest thing is to just buy their board.
Everything you need to control an AC load with a small voltage and current can be found in a single component: a solid state relay like this one.
Any board that can drive 20 mA into an LED can use this, which means that you don't need a special board.

A: A very good reason is to have separate power supplies for the logic and the power interface parts.
Logic section is in normal design powered at 5V or 3.3V, and galvanically isolated from the power section, where the most common supply is 24V, so an optocoupler is necessary.
It is true that it can be avoided using a relay with coil rated for 5V, but many relays are not available with this coils, and it would be necessary to have a much higher power on the 5V side, with a bigger DC/DC converter.
It is more common to use the field unregulated supply, 12V or 24V, automotive or industrial (relays do not need a very precise voltage), and a small galvanically isolated DC/DC converter to derive the 5V / 3.3V for just the logic section, so the isolated couplers are necessary.

A: First, a possibly more permanent link to this product is here. And the schematic is here.
(Edit 7/29/2015: Ironically my two links are now broken and OP's Amazon link is still useful)
Two reasons it makes sense to use optoisolators here:

*

*The controlling device might be very far away so that it doesn't share a common ground reference with the relay board (except as connected through a long cable). Using the optoisolator means the control signal is used purely as a differential signal between Vcc and the control signal, both sourced from the controller circuit; ground potential differences won't affect the operation.

*The relay coil voltage is not necessarily the same as the controller's Vcc. It could even be generated by an off-line (unisolated) supply. The optoisolator then provides isolation between the potentially unisolated JD-VCC supply and the controller circuits.

A: The most important reason is the coil in the relay is a pretty complex load in the circuit. As we know, a diode is required to protect the circuit from the reverse current inducted from the coil when power off the relay. Some time this method is not enough for a poorly configured power supply, as most DIY modules have. Controllers often get an impulse or even been fired by the relay. I do think if the power supply is robust enough, the optical isolator is not necessary.

A: Probably a number or reasons, but the most important being that it will prevent transient voltage from damaging the driving transistor. And depending on the application, it will help prevent AC noise from interfering in the rest of the circuit.
You bring up some good points, however optocouplers are commonly used to isolate components from potentially dangerous outside sources. They are cheap and simple to implement. And they can potentially offer more protection than a diode. And of course, as you pointed out:

A number of these boards don't seem to be
  designed brilliantly (no regard to clearance or creepage), so even if
  the optocoupler is simply to provide two layers of isolation, the
  board fails at this.

A: when using A relay most time you will wish to separate the mcu digital GND AND VDD from the relay(s)  GND and vcc  , then you get very clean mcu GND AND VDD lines .....
if a relay give back EMS , high sharp and fast voltage pick and  -- NO - flyback diode and tvs protection .
the transistor inside the optocoupler will destroy  from relay side , so the main resean , is total separation of gnd , power lines.
if the relay is use for AC it can emit EMC to the circuts from the , GND , VCC , so , optocoupler will solve most of this


text:
Q: :hover is not working; how to correct it? .signUp
{
-moz-border-radius: 3px 3px 3px 3px;
-webkit-border-radius: 3px 3px 3px 3px;
box-shadow: 3px 3px 3px #888888;
cursor : pointer;
}
.signUp :hover
{
-moz-border-radius: 3px 3px 3px 3px;
-webkit-border-radius: 3px 3px 3px 3px;

}

This is not working; how can I fix it? The class is placed in a  element.

A: try this code
.signUp
{
-moz-border-radius: 3px 3px 3px 3px;
-webkit-border-radius: 3px 3px 3px 3px;
box-shadow: 3px 3px 3px #888888;
cursor : pointer;
}
.signUp:hover
{
-moz-border-radius: 3px 3px 3px 3px;
-webkit-border-radius: 3px 3px 3px 3px;
box-shadow:none;

}

A: You :hover is remove spacae.
html
HoverTest

css
span{
 -moz-border-radius: 3px 3px 3px 3px;
 -webkit-border-radius: 3px 3px 3px 3px;
 box-shadow: 3px 3px 3px #888888;
 cursor : pointer;
 color:#ccc;
 border:1px solid #ddd;

}
span:hover{
  -moz-border-radius: 3px 3px 3px 3px;
  -webkit-border-radius: 3px 3px 3px 3px;
   color:#aaa;
   border:1px solid red;
}

SEEDEMO


text:
Q: FileSystemWatcher has a strange behaviour I want to monitor a log file of our PBX for changes. I made a small program that does just that with a FileSystemWatcher.
Now it's getting strange: The FileSystemWatcher never fires the Changed-Event when I simply start the program. Despite the fact that the log file really has changed. But when I open the directory in the Windows Explorer where the log file is located, the program works as expected. But only as long as the Explorer Window stays open... what the..?
Operating System: Windows Server 2008 R2
EDIT: Sorry, here is the code:
class Program
{
    static void Main(string[] args)
    {
        new LogFileWatcher(@"C:\PBX\Dial.log");
        System.Console.Read();
    }
}

public class LogFileWatcher
{
    public string LogFilePath { get; private set; }

    private DateTime _lastLogFileWriteTime;

    public LogFileWatcher(string path)
    {
        LogFilePath = path;
        var directoryName = Path.GetDirectoryName(LogFilePath);
        var fileName = Path.GetFileName(LogFilePath);

        var fsw = new FileSystemWatcher { Path = directoryName, Filter = fileName };
        fsw.Changed += fsw_Changed;
        fsw.EnableRaisingEvents = true;
    }

    private void fsw_Changed(object sender, FileSystemEventArgs e)
    {
        // Get and fix the last write time of the log file
        var fixLastWriteTime = File.GetLastWriteTime(LogFilePath);

        // Don't do anything when file didn't change since last time
        if (fixLastWriteTime == _lastLogFileWriteTime) return;

        Console.WriteLine("File changed on: {0} - ID:{1}", DateTime.Now.ToLongTimeString(), Guid.NewGuid());

        // Save last write time of the log file
        _lastLogFileWriteTime = fixLastWriteTime;
    }
}

EDIT2: Maybe this is important: The log file is in use by the PBX Windows-Service! I can open it with Notepad though.

A: For optimization reasons, the FileStream.Flush()-Method doesn't flush metadata anymore (Vista and later Microsoft operating systems). Therefore the FileSystemWatcher gets no file notification and won't fire the Changed-Method.
http://connect.microsoft.com/VisualStudio/feedback/details/94772/filestream-flush-does-not-flush-the-file-in-the-correct-way-to-work-with-filesystemwatcher-or-native-readdirectorychangesw


text:
Q: Compare two files with string and output required for specific format Thank you for your answer at https://stackoverflow.com/questions/71080087
@RavinderSingh13
In questions/71080087, I compared two files by the field delimiter.
one more question...
I want to ask a more detailed question
This is a list of file systems provided by each of the two servers.
cat volume1.txt (by server1)
/         80G    xfs  /dev/mapper/rootvg-lv_root
/boot     1014M  xfs  /dev/sda2
/boot/efi 500M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs

# cat volume2.txt (by server2)
/         33G    xfs  /dev/mapper/rhel-root
/boot/efi 599M   vfat /dev/sda1
/boot     1014M  xfs  /dev/sda2

Is it possible to output as below? (order of the lines doesn't matter)
volume1.txt                                                        volume2.txt
/       80G    xfs  /dev/mapper/rootvg-lv_root     : [ NotMatch ] : /       33G    xfs  /dev/mapper/rhel-root
/boot     1014M  xfs  /dev/sda2                    : [    OK    ] :
/boot/efi 500M   vfat /dev/sda1                    : [ NotMatch ] : /boot/efi 599M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs : [ NotExist ] :

my work...
FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done

If you don't understand my question please tell me.

A: With your shown samples, please try following awk code. Written and tested in GNU awk.
awk '
BEGIN{
  print ARGV[1]"                   "ARGV[2]
}
FNR==NR{
  arr1[$1]=$0
  next
}
($1 in arr1){
  if($0==arr1[$1]){
     print  $0 "           :[    OK     ] : "
  }
  else if($0!=arr1[$1]){
     print arr1[$1]"  :[ NotMatch  ] : "$0
  }
  arr2[$1]
  next
}
{
  print $0"  :[ NotExist  ] : "
}
END{
  for(i in arr1){
     if(!(i in arr2)){
        print arr1[i]"           :[ NotExist  ] : "
     }
  }
}
' volume1.txt  volume2.txt

Explanation: Adding detailed explanation for above.
awk '                                                        ##Starting awk program from here.
BEGIN{                                                       ##Starting BEGIN section from here.
  print ARGV[1]"                   "ARGV[2]                  ##Printing passed Input_file names here.
}
FNR==NR{                                                     ##Checking condition FNR==NR which will be TRUE when food1.txt is being read.
  arr1[$1]=$0                                                ##Creating array named arr1 with index of 1st field and value is $0.
  next                                                       ##next will skip all further statements from here.
}
($1 in arr1){                                                ##Checking condition if $1 is present in arr1 then do following.
  if($0==arr1[$1]){                                          ##Checking condition if whole line is equal to arr1 value.
     print  "           :[    OK     ] : " $0                ##Printing ok message with current line of food2.txt here.
  }
  else if($0!=arr1[$1]){                                     ##Else(in case whole line is NOT equal to arr1 value) then do following.
     print arr1[$1]"  :[ NotMatch  ] : "$0             ##Printing first field FS value of arr1 followed by NotMatch followed by current line from food2.txt.
  }
  arr2[$1]                                                   ##Making an entry of current $1 for arr2 array here.
  next                                                       ##next will skip all further statements from here.
}
{
  print $0"  :[ NotExist  ] : "                              ##printing current line followed by NotExist statement.
}
END{                                                         ##Starting END block for this program from here.
  for(i in arr1){                                            ##Traversing through arr1 elements here.
     if(!(i in arr2)){                                       ##Checking condition if key i is NOT present in arr2 then do following.
        print "           :[ NotExist  ] : "i FS arr1[i]     ##printing NOtExist statements followed by i FS and arr1 value.
     }
  }
}
' volume1.txt  volume2.txt                                   ##Mentioning Input_file names here.


text:
Q: Sound file location isn't found when run in another computer My C# program is running well on my computer and the sound is playing, but when i sent it to my lecturer, he said the program was running but it couldn't locate my sound file. my file location in the program was like:
C:\Documents\Visual Studio 2012\Projects\Barista3000_Aroka_Lab6\Barista3000_skal\Sounds\sound.wav
How do i make sure the sound will always be located when ran on a different computer?

A: You need to add the file to your project like and set build action to content.

And when you build the project it will end up in your output folder, just play it with something like.
PlayFile("sound.wav"); // I made up this method btw.

Notice, not the full path to the file, this is relative and it will look for this file in the working (current) folder.

How do i make sure the sound will always be located when ran on a different computer?

For this, you will still need to distribute it with your EXE and other 'stuff' that's in your build output folder.
Also, have a look at embedding resources, that way you can include the WAV in your EXE.


text:
Q: Spring boot Database authentication using Angular I'm using Spring boot as my Rest API and Angular as my front end framework.
I'm a beginner in angular and struggling doing authentication using angular. I have read some articles online but they all are very difficult to grasp.
This is my authentication builder configure method:-
     @Override
 protected void configure(AuthenticationManagerBuilder auth) throws
 Exception{
     auth.userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
 }

And this is my configuration
    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
    .and()
    .authorizeRequests()
        .antMatchers("/profile").hasAnyRole("USER", "ADMIN")
        .antMatchers("admin/**").hasRole("ADMIN")
        .antMatchers("user/**").hasRole("USER")
        .antMatchers("/","/faq","/donate","/recent","/signup","/register").permitAll()
        .antMatchers("/adduser/**").permitAll()
        .antMatchers("/h2/**").permitAll()
        .anyRequest().authenticated()
    .and()
    .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error=true")
        .successHandler(successHandler())
        .defaultSuccessUrl("/user/profile")
        .permitAll()
    .and()
    .logout()
        .logoutSuccessUrl("/login?logout")
        .permitAll();
}

I've successfully implemented user authentication and authorization
using thymeleaf but now I'm trying to implement it in angular for learning purpose.
Should I do JWT authentication (Which includes lot of boiler code in spring)? Is there any other way or alternative solution?
What are the possible ways I can implement this as I can't find any other solution. Please help...

A: there are two approaches, using Oauth or JWT, i prefer JWT for spring boot applications,though the configuration for JWT may be overwhelming.
the most straightforward solution for JWT on Spring boot for your angular app:
Video tutorial by TechPrimers
Source code of the video tutorial


text:
Q: gpu.js with BigDecimal or float64array possible? I am writing a mandelbrot-calculator with the help of gpu.js and till now, everything works perfectly fine. The only issue I am facing is, that the GPU only wants to compute 32-Bit floats. Or at least this is what the official docs are telling me.
But when doing the same calculation with python and numba - which also runs on the same GPU - is much more precise when rendering the mandelbrot fractal.
With Python, I am able to get nearly around 1e-15 whereas in Javascript, the image becomes blurry at around 1e-7.
Python Kernel:
@cuda.jit(device=True)
def mandel(x, y, max_iters):
    c = complex(x, y)
    z = 0.0j
    for i in range(max_iters):
        z = z * z + c
        if (z.real * z.real + z.imag * z.imag) >= 4:
            return i

    return max_iters

Javascript Kernel:
const recalculateMandelbrot = gpu.createKernel(function(x_start, x_end, y_start, y_end, iters){
    let c_re = x_start + (x_end - x_start) * this.thread.x / 1024;
    let c_im = y_start + (y_end - y_start) * this.thread.y / 1024;
    let z_re = 0, z_im = 0;
    let z_re_prev = 0;

    for(let i = 0; i < iters; i++) {
        z_re_prev = z_re;
        z_re = z_re * z_re - z_im * z_im + c_re;
        z_im = z_re_prev * z_im + z_re_prev * z_im + c_im;

        if ((z_re * z_re + z_im * z_im) >= 4) {
            return i;
        }
    }
    return iters;
}).setOutput([1024, 1024]).setPrecision('single');

The algorithms are equal to each other, except that in Python, I can use its built-in complex type.
So I thought about using BigDecimal, where I can achieve arbitrary precision (so I can zoom in as far as I want), but I do not know how to add this to my gpu-kernel.
Update:
The reason why python works more precise, is because the complex type consists of two 64-Bit Floats. So the reason why JavaScript is calculation less precise, is because of JavaScript itself.
So my question now focuses on how to add big.js to my gpu-kernel?

A: There is custom kernel test file here: https://github.com/gpujs/gpu.js/blob/1be50c09ed4edb7c7e846b1815414ef504089ab6/test/features/add-custom-native-function.js
with this kernel sample:
const glslDivide = `float divide(float a, float b) {
  return a / b;
}`;

Maybe there can be a way to use "double" in place of "float" and use it in place of simple multiplications and additions.
I don't know how to use glsl but if backend can be attached to glsl somehow, this should work. Also "double" needs glsl 4.0 so it may not work.
Even if it works, it still needs all of the iterations recursive because there is not "state variable" definition for double. Just like calling same function until max-iteration is reached. There should be two function parameters to keep track of imaginary and real parts and two other function parameters to keep track of number of iterations and maybe c value. Considering the depth of recursion is limited, it may not work, again.

Even in webgl backend, https://github.com/gpujs/gpu.js/blob/1be50c09ed4edb7c7e846b1815414ef504089ab6/src/backend/web-gl/fragment-shader.js it looks like you could just edit the string of some functions (like module down there) and use it like multiplication/addition.
You can also read here for an inspiration on multiplying/adding two 64bit values simulated by four 32bit values: https://github.com/visgl/luma.gl/blob/master/modules/shadertools/src/modules/fp64/fp64-arithmetic.glsl.ts
In any way, buffers(between Js environment & GPU driver) may not work at all and you are stuck with 100% functional programming within the kernel (no state handling for 64bit variables).
These are not good options. You should use a library that lets you write native kernel as a string (like this https://github.com/kashif/node-cuda/blob/master/test/test.js) and use it directly from Javascript so that you can do nearly anything you'd do within CUDA/OpenCL.


text:
Q: is python dict.items() threadsafe? Python raises an exception if a dictionary changes its size during iteration using iteritems().
I am hit by this problem since my program is multithreaded and there are cases that I need to iterate over the dict while another thread is adding keys into the dict.
Fortunately, I don't need the iteration to be very precise on every element in the dict. Therefore I am thinking to use items() instead of iteritems() to do the iteration. I think items() makes a static snapshot of the dict and I would work around the problem.
My question is: does items() raises an exception if the dict size is changing at the same time with items() execution?
thanks

A: This answer pertains to CPython's implementation of Python 2 and Python 3.
Since the items() method is implemented purely in C without releasing the GIL beforehand or during its execution, no other thread may acquire it and the underlying data structure remains unchanged while this method is executed.
Thus, the invocation of the items() method in Python 2 and in Python 3 is guaranteed to succeed.
However, while the operations performed on the returned object are thread-safe in Python 2, they are not in Python 3.
Python 2
The returned object is a copy of the dictionary's list of (key, value) pairs. As such, it is decoupled from the dictionary and operations performed on the dictionary can't affect the copy in hand.
Though, it's worth noting that the items themselves aren't copies of the original items so care should be taken when dealing with mutable items.
Python 3
The returned object is a view object. As such, certain operations performed on it might fail, as detailed in the official documentation:

Iterating views while adding or deleting entries in the dictionary may
raise a RuntimeError or fail to iterate over all entries.


text:
Q: Unable to use json body of gcp cloud scheduler in cloud function as parameter value? I have a cloud scheduler which I am using to trigger my cloud function as http call, In my cloud function I would like to form a query (which should be dynamic). To do so, I am passing some parameter from cloud scheduler (Json Body), but when I trigger my cloud function it doesn't take parameter values which are coming from cloud scheduler as json body. Can anyone help me to resolve this issue.
json body from cloud scheduler:
{
   "unit":"QA",
   "interval":"3"
}

Cloud function code:
def main(request):

    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'unit' in request_json:
        retail_unit = request_json['unit']
    elif request_args and 'unit' in request_args:
        retail_unit = request_args['unit']
    else:
        unit = 'UAT'

    if request_json and 'interval' in request_json:
        interval = request_json['interval']
    elif request_args and 'interval' in request_args:
        interval = request_args['interval']
    else:
        interval = 1

    query = "select * from `myproject.mydataset.mytable` where unit='{}' and interval ={}".format(
    unit,interval)
    client = bigquery.Client()
    job_config = bigquery.QueryJobConfig()
    dest_dataset = client.dataset(destination_dataset, destination_project)
    dest_table = dest_dataset.table(destination_table)
    job_config.destination = dest_table
    job_config.create_disposition = 'CREATE_IF_NEEDED'
    job_config.write_disposition = 'WRITE_APPEND'
    job = client.query(query, location='US', job_config=job_config)
    job.result()

Note: It works when I pass same variables from cloud scheduler as argument values in http url (https://my-region-test-project.cloudfunctions.net/mycloudfunction?unit=QA&interval=3)

A: You can override the default Content-Type by creating the cron job using gcloud with the flag --headers Content-Type=application/json.
For instance:
gcloud scheduler jobs create http my_cron_job \
  --schedule="every 5 hours" \
  --uri="https://${ZONE}-${PROJECT_ID}.cloudfunctions.net/${FUNCTION_NAME}" \
  --http-method=POST \
  --message-body='{"foo": "bar"}' \
  --headers Content-Type=application/json

This doesn't seem to be available from the GCP Console level yet. Update 08/2021: It seems that it has been implemented in the UI now:

Alternatively, using force=True seems to help if you're using Flask:
request.get_json(force=True)

This is due to the fact that Cloud Scheduler seems to set the default Content-Type header to application/octet-stream. See the doc

A: The best hint is UTF-8 issue.
Check out also the situations described in this other thread:
HTTP Triggering Cloud Function with Cloud Scheduler


text:
Q: Query string (URL) lead to 403 Please help me on this.Already tried disable mode_security module through .htaccess no use.

PHP Version 5.6.30

Apache redirect the request to 403 page if pass parameter below.
&test[object_type]=0
The name (object_type) leads to 403 page.
eg:http://www.cudec.com.my/?test[object_type]=0 ✖ NOT WORKING LEADS TO 403
eg:http://www.cudec.com.my/?test[object_types]=0 ✓ WORKING

A: Will update this post to a full answer as soon as I got more information to work with ;)

I tried to call the 403-URL:
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

You ensured that ModSecurity is the one replying with 403? Looks more like the folder permissions are insufficient.
Check if your DocumentRoot is at least readable for users (an 'r' at the last triple or 4 in the last byte).
If it's really ModSecurity, have a look into /var/log/apache2/modsecurity_audit.log and you should see which rule (by ID) is the one throwing 403 and also the reason (Error-Msg in the rule) why.
Does http://www.cudec.com.my/?test[object_types]=0 return the expected result?
The parameter doesn't seem to be interpretated when using &test[object_type] instead of &test[object_types] and the target ressource / seems to have insufficient rights, same for the error-pages...


text:
Q: Substitute Multiple Alphabets Without Using Replace function in Python I am a beginner of python. I need to replace  ARED with TUXY without using replace function. Example: Apple is behind a tree. After: TpplX is bXinY T tUXX.
Can you help? Thanks

A: You can use str.translate and string.maketrans:
import string
match = "ARED"
replace = "TUXY"
translator = string.maketrans(match, replace)

s = "Apple is behind a tree."
s.translate(translator) # => 'Tpple is behind a tree.'

However, you will notice that this is case-sensitive.
If you want a case-insensitive replacement, concatenate the lower-case characters
as well:
match = "AREDared"
replace = "TUXYtuxy"
translator = string.maketrans(match, replace)

s = "Apple is behind a tree."
s.translate(translator) # => 'Tpplx is bxhiny t tuxx.'

For Python 3, the str class has its own maketrans method. So, use
translator = str.makestrans(match, replace) instead – the string module is no longer required.


text:
Q: How to send content from Freemarker to java by request? I'm trying send information from a FreeMarker template to my Java model class.
I've tried this:
//my array of string casted in a string
var pais = selected.join();

request.setAttribute(pais, "paises");

Ok, now I'm trying collect this content in my Java class doing this:
String paises = MgnlContext.getAttribute("paises");

But it doenst work. I tried other methods like this:
Stirng paises = MgnlContext.getInstance().getAttribute("paises");

But it always returns null.

A: SOLUTION (sending info by ajax):
first get the values by javscript :
[#assign cpathx = ctx.contextPath]
[#assign url = model.getUrl() /]
var field = $('#key').val();
var calin = $('#calendarIni').val();
var calfin = $('#calendarFin').val();
var pais = selected.join();
var url = '${cpathx}${url}?paises='+pais+'&palabra='+field+'&calendarini='+calin+'&calendarfin='+calfin;
    jQuery.post(url ,function(data) {
    jQuery('#ajax').html(data);
  });

Now we can collect the info in java:
String paises = MgnlContext.getWebContext().getAttribute("paises");
String queryString = MgnlContext.getWebContext().getAttribute("palabra");
String dateStart = MgnlContext.getWebContext().getAttribute("calendarini");
String dateEnd = MgnlContext.getWebContext().getAttribute("calendarfin");

A: That first piece doesn't look like freemarker but more as JavaScript, so maybe that is your problem. While freemarker directives are executed server side, html and Js produced by freemarker is executed client side so w/o Ajax call there's no way for Js to talk back to server (and thus to model class).
If you were really interested in passing something from freemarker to java model, model is exposed directly.  You can simply add method in java model and call it from freemarker template like
${model.myMethod(someParam)}

HTH,
Jan


text:
Q: WSO2 EMM Command Issue to phone slow to receive I have setup a WSO2 EMM in a test enviroment and enrolled an Android Phone for testing. In the testing, I notice that all the command that issued from my WSO2 EMM to the enrolled Android phone seems to be very slow in receving it. E.g Ring the phone, send notification to phone, mute phone etc, all of them take more than 10 mins to perform each.
Both the server and phone are connected to the same network. Is there anywhere I should be looking to improve this ?

A: There are two notification methods for Android OS.
GCM(The Google Cloud Messaging) and Local
If you select Local notification method from the Android Platform configuration/notifier Type,provide the Notifier Frequency (in milliseconds) - Defines the time interval for the Andorid Agent to automatically trigger the wake-up command.
[sign to EMM console>>Platform configuration>> Android Configuration>>Notifier Type]
If the notification type is GCM, when there are pending operations that need to be enforced on a device, WSO2 EMM server will send a push notification to the GCM server and the GCM server will in-turn send the message to the respective Android Agent that is within the Android device. When the Android Agent receives the push notification, it will communicate with WSO2 EMM server and receive the list of pending operations that need to be enforced on the Android device.