text:
Q: Recreate contextmenu event in RxJS I want to recreate the contextmenu event from touch events in RxJS because iOS does not support the contextmenu event on touch.
In plain language, this observable should emit when:

*

*the touchstart event occurred

*for 2000ms (basically long-press)

*followed by touchend

It should not emit when:

*

*the touchend occurs in less than 2000ms

*the touchstart event is followed by touchmove event

I can't figure out how to skip if the touchend occurs sooner or if the touchstart is followed by touchmove. This is what I've so far:
const touchStart$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchstart");
const touchEnd$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchend");
const touchMove$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchmove");
const contextmenu$ = touchStart$.pipe(
      switchMap(event => touchEnd$.pipe(mapTo(event))),
      switchMap(event => timer(2000).pipe(mapTo(event), takeUntil(merge(touchEnd$, touchMove$))))
);

contextmenu$.subscribe($event => {
      console.log("CONTEXTMENU EVENT HAPPENED");
});

A: Your solution can be simplified a little bit.  The inner mapTo isn't necessary, if you don't reuse the name event, you can just use a single mapTo at the end of your pipe.  Also, you may want to use take(1) instead of takeUntil(touchMove$) on the inner switchMap since you want to end the stream after the first emission:
  const longPress$ = this.touchStart$.pipe(
    switchMap(event => timer(2000).pipe(
      takeUntil(merge(touchMove$, touchEnd$)),
      switchMap(() => touchEnd$.pipe(take(1))),
      mapTo(event)
    ))
  );

I'm assuming you got the behavior you wanted, but I think normally a longpress will fire when duration passes; i.e. we needn't wait for the touchend event.  If that were the case, it gets even simpler:
  const longPress$ = this.touchStart$.pipe(
    switchMap(event => timer(2000).pipe(
      takeUntil(merge(touchMove$, touchEnd$)),
      mapTo(event)
    ))
  );

Here are a couple StackBlitzes with colorful logging: Original | Simplified

A: I came up with a possible solution:
const touchStart$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchstart");
const touchEnd$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchend");
const touchMove$ = fromEvent<TouchEvent>(this.el.nativeElement, "touchmove");
const contextmenu$ = touchStart$.pipe(
    switchMap(event =>
        timer(2000).pipe(
           mapTo(event),
           takeUntil(merge(touchMove$, touchEnd$)),
           switchMap(event => touchEnd$.pipe(mapTo(event), takeUntil(touchMove$)))
        )
    )
);

contextmenu$.subscribe($event => {
    console.log("CONTEXT MENU EVENT HAPPENED");
});


text:
Q: Can I access the registration tokens of all users registered in my Firebase notifications? Sometimes I want to send a message through Firebase notifications to one unique user, then I want access the token from that user, so I like to know what is the best practice for get that token at any time?
On initial startup of my app, the FCM SDK generates a registration token for the client app instance.
I can get that token, but if I save that token in Firebase realtime database, I think other people can access that data because it is "set persistent mode on" to access offline data.
My questions is:
Is it possible to get tokens of all users without save that in a database?
Can I get these tokens direct from Firebase Authentication? If not, what is the best practice for access these tokens?

A:
I think other people can access that data because it is "set persistent mode on" to access offline data.

Simply save the registration token details to a secure node. Making sure that only you (or even including the user itself) to be the only ones that can access it. Read more on Understand Firebase Realtime Database Rules.

I can get that token, but if I save that token in Firebase realtime database, I think other people can access that data because it is "set persistent mode on" to access offline data.

Users won't be able to get the data they're not allowed to/wasn't designed to have on their device if you choose to restrict them.

Is it possible to get tokens of all users without save that in a database?

There is no API to get all the registration tokens related to your app. As mentioned in the documentation (emphasis mine):

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

It's the developer's (you) responsibility to send and store the registration token to a secure location.

Can I get these tokens direct from Firebase Authentication?

I'm not entirely sure what you mean by this. FCM Registration tokens are different from auth tokens. So, no.

If not, what is the best practice for access these tokens?

So long as you store the tokens in a secure location and make sure that you're always using the most recent/valid token, it should be good.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VB6 COM Object - only works when IDE is running? I have an ancient COM object in VB6 that has been working fine until recently. (Don't they all). The only code change that has been made (as verified by svn) is the inclusion of a new string literal in an array.
The VB6 IDE compiles the object fine. When I hit Run|Start... and execute the following test vb script from the command prompt, the object works fine and I see the dialog boxes I expect:
dim o

set o = CreateObject("MyDll.MyClassName")

wscript.Echo "Testing object"
wscript.Echo o.HelloWorld     ' runs a test method that returns "Hello World"
wscript.Echo "Done"

However, when I stop debugging in the IDE and attempt to run the same vbscript from the same command prompt, I get the error:

(ProgID removed for security reasons, but it is the same as in the script.)
Things I've tried:

*

*I suspected that the DLL may have been registered and unregistered by VB when I start and stop the debugger, so I also tried registering the object with regsvr32 before running the test script. This has had no effect.

*I also removed all references to the DLL from the registry, and re-registered the object. Same error.

*I deleted the DLL and re-built it from VB (File|Make...) and re-registered the DLL. Same error.
Machine is Win7 Ultimate x64, object built with VB6.
Any suggestions?
And, no, unfortunately, rewriting the object in C# isn't an option.

A: Microsoft says it's some sort of dependency issue: http://support.microsoft.com/kb/194801
Because it's working when you run the object in the IDE this leaves you with four possibilities:

*

*The ActiveX dll itself is not on the system path.

*The ActiveX dll depends on something else which is not on the system path.

*After registering the dll, it is somehow marked as requiring elevated security to run

*After registering the dll, something it depends on requires elevated security to run.

I would try opening a command prompt as administrator then run your vbscript file that starts the object.  If that works then it means the problem is either #3 or #4.  If it doesn't, then it means #1 or #2.
You can eliminate #2 and #4 if the ActiveX dll has no external dependencies.
Next, I'd look in my event log to see if any other errors were logged by windows about this.
UPDATE
Just found another possible cause.  If the ActiveX dll is 32-bit, then the script has to use the 32-bit version of the script engine to run; otherwise it will give this error because the default script engine (x64 on that machine) literally can't find the dll.
I believe if you use \windows\system32\cscript.exe to run your vbscript then you'll be good.

A: Well it definitely sounds like the issue because of 32bit dll.. The suggestion mentioned above is correct but the path is wrong.. try using the CSCRIPT from C:\Windows\SysWOW64..

A: Try registering the DLL with regsvr32.exe from %Windows%\SysWOW64. It is different than the regsvr32.exe in %Windows%\System32 (on a 64-bit OS).
See this SO posting.


text:
Q: LibreOffice 6.2.4+ crashes with code 139 on CentOS 7.6 Versions of LibreOffice starting from 6.2.4 are not able to run on CentOS 7.6. Running libreoffice6.2 exits with code 139.
There are old bug reports (e.g. this) which have similar symptoms but are related to a different problem. This particular error is not related to Java 9+ (as remove Java from the system does not solve the problem).
Downgrading to 6.2.3 resolves the issue.

A: After a crash LibreOffice creates dump file path to which can be found in
~/.config/libreoffice/4/crash/dump.ini. Checking dumps reveals that there are
some dependent libraries that cannot be loaded, e.g.:
cannot open shared object file.libKF5KIOFileWidgets.so.5

These libraries, found one by one, suggest that the following packages must be installed to allow new versions of LibreOffice to run:
yum install kf5-kcoreaddons kf5-ki18n kf5-kconfig-core \
    kf5-kwindowsystem kf5-kio-core-libs kf5-kio-file-widgets

All of these packages are in EPEL repository. Once they are installed, LibreOffice 6.2.4+ runs.


text:
Q: Bootstrap Modal Closes on Touch for stock Android Browser Using Bootstrap 3+
I have a registration / login form in a modal. When you open a modal in the stock android browser the user can't touch a form or anything because it automatically closes like it would if you clicked outside of the modal area.
I have a lot of users using the default android browser for some strange reason so this is causing major issues on my website.
If anyone knows of a fix for this issue it would be much appreciated

A: on button click to open the modal
$(window).scrollTop(0);


text:
Q: BLE-RSSI completely noisy signal I am working on an app for indoor navigation. I am reading the RSSI-values of three Bluetooth beacons, that I placed in my apartment. The TX signal strength of these beacons is 6 dBm, advertising interval 100 ms. I am using a Motorola G7 Plus, Android Version 10. In the room there is also WLAN (mine and that of the neighbours).
I have done a lot of measurements (with self-made beacons and bought ones) and very often there is such a lot of noise in the received RSSI-values! I read some papers about indoor navigation and I did not see that other developers were having the same problem. I also cannot figure out what causes this noise. E.g. I did measurements outdoors (with only one beacon), without any WLAN in reach and the noise was still present (though less intense). Maybe it´s interference with the Smartphone?
Has anyone of you experienced similar measurements?

A: I wouldn't call this noise, there is clearly a pattern.
Since a myriad of factors can influence the received signal, one can only speculate without further information/measurements.
An example: Bluetooth LE uses three channels for advertising (37, 38 and 39) which are spread over the frequency band. Since the receiver can only receive on one channel at a time, the picture you showed could indicate that the deviations are caused by the different channels/frequencies that find completely different propagation paths in your environment.
The magic word is filtering. You have to average your RSSI measurements over a longer period of time and then use the obtained values to triangulate the position.


text:
Q: Adaptive modelling using GEKKO sysid I have 100 points of data that I'm trying to describe using sysid in GEKKO. At some point ( t = 50 in this case) the data changes significantly and the prediction is no longer accurate. I'm trying to include an if statement that evaluates actual vs predicted and generates a new model (new yp ) if the prediction is x times bigger than the model. Here's my sample code. The loop continues evaluating yp at each point in time but it should be evaluating yp_new now.
from gekko import GEKKO
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# load data and parse into columns
t = np.linspace(0,1,101)
u = np.linspace(0,1,101)
y = np.zeros(len(t))
y[:50] = np.sin(u[:50])
y[50:] = np.exp(u[50:]/500)
# generate time-series model
m = GEKKO(remote=False)
# system identification
na = 2 # output coefficients
nb = 2 # input coefficients
yp,p,K = m.sysid(t,u,y,na,nb,diaglevel=1)
print(yp)
for i in range(len(t)):
    difference = np.abs((yp[i]-y[i])/max(0.01,y[i]))
    if difference>=0.2:   #If the difference is >20%
        yp_new,p_new,K = m.sysid(t,u,y,na,nb,diaglevel=0)
        print('Recalculating at i  = ' + str(i))
print(yp_new)
plt.figure()
plt.subplot(2,1,1)
plt.plot(t,u)
plt.legend([r'$u_0$',r'$u_1$'])
plt.ylabel('MVs')
plt.subplot(2,1,2)
plt.plot(t,y)
plt.plot(t,yp)
plt.plot(t,y)
plt.plot(t,yp_new)
plt.show()

A: You would need to update yp to be the new yp value yp = yp_new or else just return yp when doing the next system identification. However, the data that you are using to redo the sysid calculation is the same as the data that you used previously so there is no change in the model prediction. Are you trying to update the time-series model only with the most recent data such as yp_new,p_new,K = m.sysid(t[i:],u[i:],y[i:],na,nb)?

The model currently updates on cycles that do not agree with the original time-series model prediction.
Recalculating at i  = 10
Recalculating at i  = 11
Recalculating at i  = 12
Recalculating at i  = 13
Recalculating at i  = 14
Recalculating at i  = 15
Recalculating at i  = 16
Recalculating at i  = 17
Recalculating at i  = 18
Recalculating at i  = 19
Recalculating at i  = 20
Recalculating at i  = 21
Recalculating at i  = 22
Recalculating at i  = 23
Recalculating at i  = 24
Recalculating at i  = 25
Recalculating at i  = 40
Recalculating at i  = 41
Recalculating at i  = 42
Recalculating at i  = 43
Recalculating at i  = 44
Recalculating at i  = 45
Recalculating at i  = 46
Recalculating at i  = 47
Recalculating at i  = 48
Recalculating at i  = 49
Recalculating at i  = 50
Recalculating at i  = 51
Recalculating at i  = 52

If you include just the most recent data then it only recalculates at cycles 10, 42, 46, and 48.
from gekko import GEKKO
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# load data and parse into columns
t = np.linspace(0,1,101)
u = np.linspace(0,1,101)
y = np.zeros(len(t))
y[:50] = np.sin(u[:50])
y[50:] = np.exp(u[50:]/500)
# generate time-series model
m = GEKKO(remote=False)
# system identification
na = 2 # output coefficients
nb = 2 # input coefficients
yp,p,K = m.sysid(t,u,y,na,nb)
yp_init = yp.copy()
print(yp)
j = 0
for i in range(len(t)):
    difference = np.abs((yp[i-j]-y[i])/max(0.01,y[i]))
    if difference>=0.2:   #If the difference is >20%
        j = i # get cycle where the last update occurred
        yp,p,K = m.sysid(t[i:],u[i:],y[i:],na,nb)
        print('Recalculating at i  = ' + str(i))
plt.figure()
plt.subplot(2,1,1)
plt.plot(t,u)
plt.legend([r'$u_0$',r'$u_1$'])
plt.ylabel('MVs')
plt.subplot(2,1,2)
plt.plot(t,y)
plt.plot(t,yp_init)
plt.plot(t,y)
plt.plot(t[j:],yp)
plt.show()


text:
Q: Remove Unnecessary Tags from Html string in c# I am getting this Html string from system

PDF Attachment

Your service detail are following

I have two h1 tags in this string. I want to remove "h1" tag in which "table" tag is used.
How can i remove it programmatically?

A: You can use HtmlAgilityPack:
var content = @"
PDF Attachment

Your service detail are following

";

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content);
var h1NeedsToRemove = htmlDoc.DocumentNode.SelectNodes("/h1").Where(i => i.ChildNodes.Any(c => c.Name == "table")).FirstOrDefault();
var childNodesOfH1 = h1NeedsToRemove.ChildNodes;
h1NeedsToRemove.Remove();

htmlDoc.DocumentNode.AppendChildren(childNodesOfH1);

It will give you desired output:

PDF Attachment

Your service detail are following


text:
Q: Product of two non-zero complex numbers equals zero Is it possible for the product of 2 non-zero complex numbers to be 0?

A: No, it is not possible.
For complex numbers $z_1,z_2 \in \mathbb{C}$ we have that
$$z_1\cdot z_2 = 0 \quad\implies\quad z_1 = 0\quad\text{ or }\quad z_2 = 0.$$
As a hint: non-zero complex numbers have multiplicative inverses.

A: Let $z_1 = r_1e^{i\theta_1}$ and $z_2 = r_2e^{i\theta_2}$ then $z_1z_2 = r_1 r_2 e^{i(\theta_1 + \theta_2)}$. Now $\exp(.)$ is never $0$ so for $z_1z_2$ to be $0$ we need one of $r_1, r_2$ to be $0$. But this immediately implies that one of $z_1,z_2$ have to be $0$. So no.

A: It's not possible. the product of 2 complex number can equal 0 if and only if one of the numbers is zero.
   i.e a.b = 0 where a,b are complex numbers
     Then either a or b is 0


text:
Q: Define loss function in keras using itertools I want to define a loss function, which represent the distance between the hidden layer output points. Firstly ,I wrote this without keras
import numpy as np
import itertools
pts = np.array([
    [10,10,10],
    [10,11,20],
    [20,11,30],
    [20,10,10],
    [10,10,20],
    ])
diff = list(itertools.combinations(pts, 2))

ptdiff = lambda (p1,p2): (np.sqrt(np.sum((p1 - p2) ** 2)))
diffs = map(ptdiff, diff)
np.mean(diffs)

I get the result. And I try this loss function in keras, z is the output of hidden layer, which is a matrix
define loss function
def vae_loss(z):
    z_diff = list(itertools.combinations(z,2))
    ptdiff = lambda (p1,p2): (np.sqrt(np.sum((p1 - p2) ** 2)))
    z_diffs = map(ptdiff, z_diff)
    loss = K.mean(z_diffs)
    return loss

But it shows the TypeError: 'Tensor' object is not iterable., I just wonder how can I fix this problem.

A: Based on this very helpful question, you can make use of Keras' broadcasting properties. I'm assuming here you run Keras on the TensorFlow backend. From the TF docs on broadcasting:

A special case arises, and is also supported, where each of the input
  arrays has a degenerate dimension at a different index. In this case,
  the result is an "outer operation".

A reproducible example of your numpy code is the following:
import numpy as np
import itertools

# Generate 100 random points in a 5-D space
n_dim = 5
matrix = np.random.rand(1000, 5)

# List all possible combinations
combinations = list(itertools.combinations(matrix.tolist(), 2))

def mse(tup):
    """MSE between first and second element of a tuple of lists"""
    return np.mean((np.array(tup[0]) - np.array(tup[1]))**2)

avg_mse = np.mean([mse(c) for c in combinations])
print('Average mse: {:.3f}'.format(avg_mse))

This returns, in my case, Average mse: 0.162
Based on the question cited above, you could construct your loss function as follows:
import keras.backend as K

# Wrap our random matrix into a tensor
tensor = K.constant(value=matrix)

def loss_function(x):
    x_ = K.expand_dims(tensor, axis=0)
    x__ = K.expand_dims(tensor, axis=1)

    # Compute mse for all combinations, making use of broadcasting
    z = K.mean(K.square(x_ - x__), axis=-1)

    # Return average mse
    return(K.mean(z))

with K.get_session() as sess:
    print('Average mse: {:.3f}'.format(loss_function(tensor).eval()))

Which returns for me Average mse: 0.162.
Note that this implementation does not exactly replicate the behaviour from your numpy example. The difference is that all combinations of rows with itself are also considered (not the case with itertools.combinations) and combinations are considered twice: mse((row1, row2)) and mse((row2, row1)) will both be calculated, which is again not the case with your itertools code. For matrices with a large number of rows, this should not make too much of a difference, as my example shows.


text:
Q: Add/Remove Input Fields Dynamically and preview field values in separate div I'm building a survey and I need the ability to preview dynamic input fields as they are created, in another div.
For example, here I'm creating text inputs (pretty trivial) and creating radio buttons in a separate div:
$('#p_scnt, #p_scnt_' + i +'').live('click', function() {
            $('
<input type="text" size="20" id="p_scnt_' + i +'" value="" placeholder="Input Value" /> Remove
').appendTo(scntDiv);
            $('
<input type="radio" value="' + crunchValue + '">' + crunchValue + '
').appendTo(crunchville);
            i++;
            return false;
    });

http://jsfiddle.net/crunchfactory/tZPg4/15947/
I'm not sure how to get the values, hence the obviously 'undefined'.
Three things:
I want to get the values from the text boxes as they are typed to the values in the separate div.
I want to click in the text box to create a new text box, which, a) only seems to work in the top 2, and b) if a box has a null value, don't create an object in the other div.
Thank you!

A:
I want to get the values from the text boxes as they are typed to the
  values in the separate div.

I think this is what you mean :)
HTML
<button id="btn-add">Add</button>

Javascript
// --- Main functions --- //
function _createTextInput() {
  var inputWrapper = document.createElement('div');
  var inputElement = document.createElement('input');
  var removeBtn    = document.createElement('button');

  $(removeBtn)
    .html("Remove")
    .addClass("btn-remove-input-wrapper");

  $(inputWrapper)
    .addClass('input-wrapper')
    .append(inputElement)
    .append(removeBtn);

  return inputWrapper;
}

function _createRadioInput() {
  var radioWrapper = document.createElement('div');
  var radioElement = document.createElement('input');
  var radioLabel   = document.createElement('label');

  $(radioWrapper)
    .append(radioElement)
    .append(radioLabel);

  radioElement.type = 'radio';
  radioElement.name = 'group';
  return radioWrapper;
}

// --- Helper functions --- //

function getIndex(me) {
  return $(me).parent().index();
}

function getRadioElement(me) {
  return $('#radio div:nth-child(' + (getIndex(me) + 1) + ')');
}

// --- Event handlers --- //

$('#btn-add').click(function() {
  $('#source').append(_createTextInput());
  $('#radio').append(_createRadioInput());
});

$(document).on('click', '.btn-remove-input-wrapper', function() {
  getRadioElement(this).remove();
  $(this).parent().remove();
});

$(document).on('keyup', '.input-wrapper input', function() {
  var index = getIndex(this);
  var inputText = $(this).val();
  getRadioElement(this).children('label').html(inputText);
});

DEMO

A: since live is deprecated I would use this format:
$(document).on("click",'#p_scnt, #p_scnt_' + i,function(){
//
});

then give each INPUT a CLASS of text-input(or whatever)
$(document).on("keyup",".text-input",function(){
   $("div").html($(this).val());
});

the above code will need to be updated for the proper div, but it will get the type as its typed for each input field and place it into the HTML of a div.


text:
Q: Relative Layouts Background resize on keyboard open I work on a background for my app but when i open the keyboard the image resizes.
I have heard from adjustPan and so on but it doesn´t work to.
getWindow.setBackground also don´t work because i am on a fragment.
If i set the Windows Background it works , but when i go back the background is still there.
Screens:
Correct screen
Incorrect screen

A: The reason seems to be that you're using android:windowSoftInputMode="adjustResize" which resizes your activity when the soft keyboard is opened. This is what you want for sure, but background images are always resized to fit the entire element. Instead of using a background, place an ImageView in the bottom of the layout and put the image there with a proper android:scaleType, this prevents the aspect ratio from being lost.

A: Add ImageView with scaleType="fitStart"
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="280dp"
             android:layout_height="match_parent"
             android:background="@android:color/white"
             android:paddingTop="8dp">

    <ImageView
        android:id="@+id/img_background"
        android:src="@drawable/background"
        android:scaleType="fitStart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <include layout="@layout/content"/>

</FrameLayout>


text:
Q: make a query not in subquery as a condition with enum value i have a schema called users
user_id state transition
  1.       accept   v1
  1.       refused  v1
  2.       accept   v1
  2.       refused  v2

with no primary key in the table users and a enum values for state and transition
I have to get a distinct user_id where transition!='v2'
the result that i want
user_id
   1

as user_id=2 has a transition=v2
I made this query but is not working or at least giving me duplicate user_id
select  T.user_id from users T
                         where  T.user_id not
          in
(select 1  from users where transition='v2' and users.ad_id=T.user_id
                                           group by user_id) limit 10;

A: Your query must looks like this:
select distinct user_id from users where transition != 'v2';

With purpose to limit your result just add limit 10 in the end of the query.

With purpose exclude users which appears twice in table with different transition versions - try this:
select distinct user_id from users where user_id not in (
  select user_id from users where transition = 'v2'
);


text:
Q: Text template custom host: how to implement ResolveDirectiveProcessor Im trying to use this example from msdn on how to create a custom host for text template generation.
The CustomCmdLineHost class implements the ITextTemplatingEngineHost interface but not completely, the ResolveDirectiveProcessor is not implemented and it throws each time an exception wich is normal. Here is the ResolveDirectiveProcessor method:
public Type ResolveDirectiveProcessor(string processorName)
    {
        //This host will not resolve any specific processors.
        //Check the processor name, and if it is the name of a processor the
        //host wants to support, return the type of the processor.
        //---------------------------------------------------------------------
        if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
        {
            //return typeof();
        }
        //This can be customized to search specific paths for the file
        //or to search the GAC
        //If the directive processor cannot be found, throw an error.
        throw new Exception("Directive Processor not found");
    }

and processorName passsed to this function is "T4VSHost",
The question now:
What is the type of "T4VSHost" to return in this method ?
P.S.: i tried "Microsoft.Data.Entity.Design.VisualStudio.Directives.FallbackT4VSHostProcessor" but it seems that it doesnt exist in any namespace.

A: It appears that the only way is to create that type. how ? by creating a class (lets call it FallbackT4VSHostProcessor) that inherits from the DirectiveProcessor abstract class which lives in the Microsoft.VisualStudio.TextTemplating namespace (the only example i found in the internet is Here). then we need to return the type of FallbackT4VSHostProcessor in the ResolveDirectiveProcessor like this:
Type ITextTemplatingEngineHost.ResolveDirectiveProcessor(string processorName)
    {
        if (string.Compare(processorName, "T4VSHost", StringComparison.OrdinalIgnoreCase) == 0)
        {
            return typeof(FallbackT4VSHostProcessor);
        }
        throw new Exception("Directive Processor not found");
    }

I hope this will help someone someday.


text:
Q: MYSQL : Improving query perfomance on join with order by clause I have two tables which contains the daily activities of a user . I have two join these tables and select top ten ids from this table .
Table 1 : buildlog
+----------------+------------------------+------+-----+---------+----------------+
| Field          | Type                   | Null | Key | Default | Extra          |
+----------------+------------------------+------+-----+---------+----------------+
| NAME           | varchar(50)            | YES  |     | NULL    |                |
| ID             | int(11)                | NO   | PRI | NULL    | auto_increment |
| DATE_AND_TIME  | datetime               | YES  |     | NULL    |                |
| COMMENT        | mediumtext             | YES  |     | NULL    |                |
+----------------+------------------------+------+-----+---------+----------------+

Number Of Rows : 276186
Table 2 : reports
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| r_id          | int(10)      | NO   | PRI | NULL    | auto_increment |
| id            | int(15)      | YES  | UNI | NULL    |                |
| label         | varchar(200) | YES  |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

Number Of Rows : 134058
If I am using only join query with this two tables using id it comes very quickly .
Query 1:
select  buildlog.id,reports.label from buildlog join reports on reports.id = buildlog.id limit 10\G

Query Time : 10 rows in set (0.01 sec)
If I add order by to get latest ten build ids,label it takes 1 to 2 minutes to execute .
Query 2 :
select  buildlog.id,reports.label from buildlog join reports on reports.id = buildlog.id order by buildlog.id desc limit 10\G

Query Time : 10 rows in set (0.98 sec)
order by column is an primary key buildlog.id . So, It's already indexed why It takes more time to execute this query ? . Can anyone suggest how can I optimize this?

A: SELECT  * FROM (
    SELECT
      buildlog.id,
      reports.label
    FROM
      buildlog
    JOIN
      reports
    ON
      reports.id = buildlog.id
) AS myval_new
ORDER BY id DESC limit 10

The slow down comes because it is probably choosing to do the ordering before doing the join. Doing the order by in an outer query forces it to only order the selected items.


text:
Q: Gruntjs throwing error with requirejs task I'm trying to setup a simple gruntjs task using requirejs on Windows 8, but when I run it keeps producing the follow command line error.

package.json:
{
"name": "my-app",
"version": "0.0.1",
"devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-requirejs": "~0.4.1"
}
}

Gruntfile.js:
    module.exports = function(grunt) {
grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    requirejs: {
        compile: {
            options: {
                appDir: "../",
                dir: "../../build",
                fileExclusionRegExp: /^(r|build)\.js$/,
                mainConfigFile: "js/main.js",
                removeCombined: true
            }
        }
    }

});

grunt.loadNpmTasks('grunt-contrib-requirejs');

grunt.registerTask('default', ['requirejs']);

};

I used npm install in the directory, then it installed all the dependencies. Any thoughts on how to fix this?

A: So Gruntfile.js is in the public_html directory correct?
I think the way you have it configured, you're telling the requirejs task to try to uglify and combine everything in the skritter-html5/ and it's choking on that, because its running through all javascript files in your project instead of just your RequireJS app code.. What you may want the appDir option to point to is something like "js/myClientSideAppDir" and then I would output it to "js/build"
Try looking over the comments in this file. https://github.com/jrburke/r.js/blob/master/build/example.build.js
They're the best description of r.js options that we've got.


text:
Q: Get group photo: ErrorAccessDenied I can get a valid authtoken and I can use this token to successfully call other endpoints like "https://graph.microsoft.com/v1.0/groups" and get valid results, using the client_credential flow.  However, I am trying to get group photo, that is used for teams:
GET https://graph.microsoft.com/v1.0/groups/{id}/photos

https://learn.microsoft.com/en-us/graph/api/group-list-photos
Problem is I am getting "ErrorAccessDenied" as the result, ie:
 { "error": { "code": "ErrorAccessDenied", "message": "Access is denied. Check credentials and try again.", "innerError": { "request-id": "e1936ac7-84f6-4cc6-be9e-e7feb38b5198", "date": "2019-11-28T23:26:10" } } }

I believe I have all the needed permissions:

Does anyone know what the problem is?


text:
Q: After Upgrading to 15.10 VPN doesn't work quite as expected, connection possibly breaks After upgrading to Ubuntu 15.10, the VPN started to behave very strangely.
I use Private Internet Access and it worked just fine.
If I connect to a site that's blocked in my country right after I connect to a VPN - it works. However, after maybe 1 minute it's not working anymore: it shows the standard "this site is blocked" page. Interestingly, the ip-address remains the one provided by PIA (checked with Google) and http://whatismyipaddress.com shows the country I'm connecting through, not my country. The VPN connection icon is present and all seems to indicate the VPN works. Except that I can't access the site.
I tried connecting to VPN from my Android device and visiting the sites and it works all the time. So it clearly must be a newly introduced bug.
Update 1: it appears to be a DNS leak problem, looking for a solution how to solve it in Ubuntu.
Update 2: ended up writing PIA's DNS into /etc/resolv.conf manually, resolved my problem.

A: So I have also discovered that possibly a bug causes DNS leaks when using a network manager openVPN connection on Ubuntu 15.10
LAN/ISP DNS are not removed and remain available as possible DNS plus the VPN DNS. They cause the leak even though the VPN DNS are present. They might be used or not. It's random
My solution is to reset the VPN DNS (removing LAN DNS) by using a network manager script dispatcher calling dbus to update dnsmasq
Create a script /etc/NetworManager/dispatcher.d/99resetvpndns with the content
#!/bin/sh

interface=$1
status=$2

case $status in
    vpn-up)
    # because dnsmasq keep DNS LAN and leak our DNS, reset DNS servers to PIA ones
    dbus-send --system --dest=org.freedesktop.NetworkManager.dnsmasq --type=method_call /uk/org/thekelleys/dnsmasq uk.org.thekelleys.SetServers
    dbus-send --system --dest=org.freedesktop.NetworkManager.dnsmasq --type=method_call /uk/org/thekelleys/dnsmasq uk.org.thekelleys.SetServers uint32:3520991966
    dbus-send --system --dest=org.freedesktop.NetworkManager.dnsmasq --type=method_call /uk/org/thekelleys/dnsmasq uk.org.thekelleys.SetServers uint32:3520991962
    ;;
    vpn-down)
    ;;
esac

and make it executable with
chmod +x /etc/NetworkManager/dispatcher.d/99resetvpndns

You need to change the uint32 value. There are your VPN DNS in integer form, not quad decimal form. Go to http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp to convert your DNS to integer for example.


text:
Q: where can i get different cypher query commands? I am new to Neo4j. i have just installed and practised a few code present in the guide provided by their official website.
I need assistance on where to get more codes for Neo4j or cypher. I have an idea only on the queries present in this link Neo4j cypher cheat sheet
where can i get idea for inserting a timestamp and varoius other function?

A: Welcome to SO and Neo4j. The starting point is the Neo4j documentation. There you choose which version of Neo4j you want to learn. 1.9.5 is at this point the last stable release, but 2.0 will be released very soon, and I recommend starting there. That means that you find the manual pages regarding cypher here and specifically the timestamp function here. All the grammar that is summarized in the cheat sheet is explained in a little more detail in those pages and there are examples of use.
Next I recommend the learn cypher page, which is an interactive tutorial based on the online Neo4j console. The console is a keeper, here you can go to create small sample graphs and test out your cypher queries, and it is particularly useful when you want to ask questions on SO about a specific modelling problem or query: create a sample of your data and model in the console, click "Share", copy the link and include it with your question here. It is much easier to answer a question when there is a shared graph to look at and you will likely get faster and higher quality answers that way.
Then install Neo4j server, run it and explore the new Neo4j browser. It contains similar tutorials to the "learn cypher" page above and has a similar ui to Neo4j console (but much prettier). Since the changes you make to your database in the browser are persistent, you can explore cypher in much more depth and create more advanced models. When you run the browser the first time you will get the option to take a quick tour which will show you how to use it.
Then remains to click the [cypher] tag here at SO and read all the questions and answers, follow the Neo4j blog and look at any graph gists posted there (such as this), identify the people know cypher well and read what they write on their blogs (there are several, examples are 1, 2 and 3).

A: Neo4j has provided very well documentation on their official document site::
http://docs.neo4j.org/chunked/milestone/index.html
Read cypher queries section.
You can try cypher online using link:::
http://www.neo4j.org/learn/try

A: The Cypher cheat sheet is nice if you've understood the concepts and need a reference nearby your desktop.
The reference manual has a extensive section on Cypher teaching you all the details. This covers the timestamp() function as well.
Neo Technology offers 1 day training events focussing on Cypher call "Neo4j Intro". Check out the schedule to see if there one in your region.


text:
Q: Symfony2 Doctrine ORM Manager named "db2" does not exist I create YML entity, generate entity and config multiple connections
config.yml
# Doctrine Configuration
doctrine:
dbal:
    default_connection: db1
    connections:
        db1:
            driver:   '%database_driver%'
            host:     '%database_host%'
            port:     '%database_port%'
            dbname:   '%database_name%'
            user:     '%database_user%'
            password: '%database_password%'
            charset:  UTF8
        db2:
            driver:   '%database_driver2%'
            host:     '%database_host2%'
            port:     '%database_port2%'
            dbname:   '%database_name2%'
            user:     '%database_user2%'
            password: '%database_password2%'
            charset:  UTF8
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

my orm.yml
TestBundle\Entity\Test:
type: entity
table: Test
id:
    id:
        type: integer
        nullable: false
        options:
            unsigned: true
        id: true
fields:
    name:
        type: string
        nullable: false
        length: 255
        options:
            fixed: false
lifecycleCallbacks: {  }

after clean cache and generate entities, I try to run this code (in command controller)
<?php

...

protected function execute(InputInterface $input, OutputInterface $output)
{
    $doctrine = $this->getContainer()->get('doctrine')->getManager('db2');
    //both methods cant work :( db2_entity_manager not found
    $doctrine = $this->getContainer()->get('doctrine.orm.db2_entity_manager');

    $test = $doctrine->getRepository('DionisDataBaseBundle:Test');

}

And I have error:

[InvalidArgumentException]
    Doctrine ORM Manager named "db2" does not exist.

A: change config.yml to
 orm:
    auto_generate_proxy_classes: "%kernel.debug%"
    default_entity_manager: db1
    entity_managers:
        db1:
            connection: db1
            mappings:
                DionisDataBaseBundle: ~
        db2:
            connection: db2
            mappings:
                DionisDataBaseBundle: ~
        db3:
            connection: db2
            mappings:
                DionisDataBaseBundle: ~

A: you just declared connections but no entity manager, from one of my projects :
doctrine:
    dbal:

        default_connection: default
        connections:
            default:
                host:     "%database_host%"
                dbname:   "%database_name%"
                user:     "%database_user%"
                password: "%database_password%"
                driver_class:  Realestate\MssqlBundle\Driver\PDODblib\Driver
                mapping_types:
                    enum: string
                    string: string
                # schema_filter: ~^(sf_fos_user)~
            prod:
                host:     *****
                dbname:   ****
                user:     "%database_user%"
                password: "%database_password%"
                driver_class:   Realestate\MssqlBundle\Driver\PDODblib\Driver
                mapping_types:
                    enum: string
                    string: string
                # schema_filter: ~^(sf_fos_user)~

    orm:
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                mappings:
                    AppBundle: ~
                    Bundle2: ~
            db2:
                connection: prod
                mappings:
                    otherBundle: ~
        auto_generate_proxy_classes: "%kernel.debug%"


text:
Q: Requirement for weak pullback to be a Lie groupoid (Moerdijk) Let $\phi:\mathcal{G}\rightarrow  \mathcal{K}$ and $\psi:\mathcal{H}\rightarrow \mathcal{K}$ be morphisms of Lie groupoids.
We define weak pullback/2-fibre product corresponding to $\phi:\mathcal{G}\rightarrow \mathcal{K}$ and $\psi:\mathcal{H}\rightarrow \mathcal{K}$ to be a groupoid $\mathcal{G}\times_{\mathcal{K}}\mathcal{H}$ whose object set is
$$(\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_0=\{(a,\alpha,b)| a\in \mathcal{G}_0, b\in \mathcal{H}_0,\alpha:\phi(a)\rightarrow \psi(b) \in \mathcal{K}_1\}.$$
Given $(a,\alpha,b ),(a',\alpha',b')\in (\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_0$ we declare
$$\text{Mor}((a,\alpha,b),(a',\alpha,b'))=\{u:a\rightarrow a'\in \mathcal{G}_1, v:b\rightarrow b'\in \mathcal{H}_1| \alpha'\circ \phi(u)=\psi(v)\circ \alpha\}.$$
We then see that $$(\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_0= \mathcal{G}_0\times_{\phi,\mathcal{K}_0,s}\mathcal{K}_1\times_{t\circ pr_2,\mathcal{K}_0,\psi}\mathcal{H}_0$$
$$(\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_1=\mathcal{G}_1\times_{t\circ \phi,\mathcal{K}_0,s}\mathcal{K}_1\times_{t,\mathcal{K}_0,s\circ \psi}\mathcal{H}_1.$$
Source, target maps are given by
$$s(u,\gamma,v)=(s(u),\gamma\circ \phi(u),s(v))$$
$$t(u,\gamma,v)=(t(u),\psi(v)\circ \gamma, t(v))$$
Moerdijk  (in page no $5$)  says that assuming $t\circ pr_2:\mathcal{G}_0\times_{\mathcal{K}_0}\mathcal{K}_1\rightarrow \mathcal{K}_0$  is a submersion confirm that $\mathcal{G}\times_{\mathcal{K}}\mathcal{H}$ is a Lie groupoid. All I can see is  $(\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_0$ and $(\mathcal{G}\times_{\mathcal{K}}\mathcal{H})_1$ are manifolds (being pullbacks under submersions) if $t\circ pr_2:\mathcal{G}_0\times_{\mathcal{K}_0}\mathcal{K}_1\rightarrow \mathcal{K}_0$  is a submersion.
But, what I do not understand is, why does $s,t$ are smooth?
For source map, first and third coordinates are submersions. Second projection $\gamma\circ \phi(u)$ does not seem to be submersion, unless I assume $\phi:\mathcal{G}_1\rightarrow \mathcal{K}_1$ is a submersion. Similarly, to prove target map is submersion, first and third projections are submersions but second projection is $\psi(v)\circ \gamma$ does not seem to be submersion unless I assume $\psi:\mathcal{H}_1\rightarrow \mathcal{K}_1$ is a submersion.
I think we should also assume $\phi:\mathcal{G}_1\rightarrow \mathcal{K}_1$ and $\psi:\mathcal{G}_1\rightarrow \mathcal{K}_1$ are submersions.
Does it follow with out assuming $\phi,\psi$ are submersions?
If $\phi$ is submersion, then, $$\mathcal{G}_1\times_{t\circ \phi,\mathcal{K}_0,s} \mathcal{K}_1\rightarrow \mathcal{K}_1\times_{t,\mathcal{K}_0,s}\mathcal{K}_1$$ given by $(u,\gamma)\mapsto (\phi(u),\gamma)$ is submersion.
 As multiplication map $\mathcal{K}_1\times_{t,\mathcal{K}_0,s}\mathcal{K}_1\rightarrow \mathcal{K}_1$ is submersion (thanks to David Roberts), the composition map given by
$$(u,\gamma)\mapsto (\phi(u),\gamma)\mapsto \gamma\circ \phi(u)$$ is submersion.

So, for $(u,\gamma,v)\mapsto \gamma\circ \phi(u)$ to be submersion, we need $\phi$ to be submersion even after using multiplication map is submersion.

What am I missing here?

A: This answer is too big to fit into a comment, and doesn't quite answer the question.
Lemma Given a diagram
$$
\array{
U & \to &  V & \leftarrow &W \\
\downarrow && \downarrow  && \downarrow \\
X &  \to & Y & \leftarrow & Z
}
$$
of finite dimensional manifolds and submersions, then the induced map $U\times_V W \to X\times_Y Z$ is a submersion.
This is proved by taking $(u,w) \in U\times_V W$ and looking at the diagram of tangent spaces and seeing that the induced linear map at $(u,w)$ is surjective.
You can iterate this lemma to deal with the case of maps between limits of longer zig-zags, like $A \to B \leftarrow C \to D \leftarrow E$.
The source and target maps for the groupoid you are looking for are almost examples of such maps between pullbacks. What you need is a generalisation of this above lemma that applies in your situation. Do the source map, without loss of generality, the target map then follows immediately. If you pick a point in the arrow space of the pullback, look at the diagram of tangent spaces at all the other points in the image of that point. You will get a diagram of vector spaces, and it should be possible to see why the map you are interested in is then surjective. As this was for a generic point, the source map has surjective derivative everywhere.


text:
Q: Dependencies for VB6 application
Possible Duplicate:
How to Deploy VB6 Applications?

The company I'm working for has this application that was written in VB6 last year.  I've had the pleasure of working through just a few minor things here and there in it.  However, now I've had a bit of a stumble.  In the latest Visual Studios, whenever you build your application, any referenced .dll dependencies can be found in the bin/Debug(or Release) folder.
My question is that in the VB6 Enterprise IDE, where does the dependencies get placed when you  make the .exe?  I'd assume that they are in the same location as the .exe; however, when I copy that entire folder over to another computer, and regsver32 (in administrator mode, of course), and I try to run the program, I get told I'm missing a dependency.  Thanks for any and all help.

A: It's been a while since I worked in VB but I seem to remember that you wouldn't copy the executable but would create an installation package that would manage all the DLL's, OCX's and such and register the necessary things with the registry for you.


text:
Q: Erro ao compilar um projeto em delphi seattle para android sando SQLite Estou recebendo esse erro ao compilar para android. No windows, compila e executa o app sem problemas. Se alguém puder ajudar ficarei imensamente grato.
[DCC Error] E2597 C:\Users\Public\Documents\Embarcadero\Studio\17.0\PlatformSDKs\android-ndk-r9c\toolchains\arm-linux-androideabi-4.6\prebuilt\windows\bin\arm-linux-androideabi-ld.exe: error: sqlite: no archive symbol table (run ranlib)

A: Esse projeto você tinha de outro delphi?... e converteu para o Seatle, já tentou criar um projeto do zero com um botão e gerar o deploy dele para ver se da o mesmo problema.
Você marcou Release em Build Configurations e criou a keystore para teste?


text:
Q: Doubt about the integration of a particular function: how start to think on how to solve a non-standard integral? I have a poor knowledge on numerical integration, advanced techniques and wayouts to solve integrals. In particular I have this one here:
$$z(r) = \int dr\sqrt{\frac{-3e^R+q^2\lambda e^rr^2}{3e^{R}-e^r(3+q^2\lambda r^2)}} \tag{1}$$
Where $\lambda$,$q$ and $R$ are simply constants.
So, how can I solve the integral $(1)$?


text:
Q: Cannot print from Microsoft Office (other programs work fine) I have a TCP/IP network printer installed on 5 machines in my office.  On 4 of the machines, I can print without problem from any program. On the 5th machine, I can print without problem from any program except Microsoft Office.  When I try to print from any of the Office programs, the office shows up in my printer status box with the status "Error - Printing".
Here are all the steps I have tried:

*

*Checked my event log, nothing is recorded

*Followed all the steps from the MS KB article

*Ran the repair utility on my office installation

*Reinstalled my printer driver

*Checked to see if a different driver was available from the manufacturer (there's not)

*Disabled UAC and ran Word as an adminstrator

*Tried using a different printer, the other printer worked

*Tried logging in as a different user, same problem


text:
Q: The data from json is not populated in my angular 8 app My json looks as follows:
    {
    "content": [
        {
            "id": 1,
            "name": "test name",
            "email": "test@test.com",
            "img_url": "url",
            "field1": [
                {
                    "id": 10,
                    "userId": 1,
                    "registeredAt": "2020-01-09T22:21:23.272",
                    "amount": 200
                }
            ],
            "field2": [
                {
                    "id": 11,
                    "userId": 1,
                    "registeredAt": "2020-01-09T22:21:46.113",
                    "amount": 200
                }
            ],
            "creationDateTime": "2020-01-05T00:00:00Z"
        }
    ],
    "page": 0,
    "size": 30,
    "totalElements": 1,
    "totalPages": 1,
    "last": true
}

and I want to populate with it my angular 8 website.
In my api.service.ts I have:
getMyStructure(): Observable<HttpResponse<MyStructure[]>> {
    return this.http.get<MyStructure[]>(
        localUrl, { observe: 'response' });
}

and in app.components.ts I have:
myStructure: MyStructure[] = [];

getMyStructure() {
    this.api.getMyStructure()
    .subscribe(function(resp) {
        console.log(resp.body.length); //this prints undefined
        console.log(resp.body) // this prints {content: Array, page: 0, size: 30, totalElements: 1, totalPages: 1, …}
        this.myStructure = resp.body;
    });
    console.log("after");
    console.log(this.myStructure.length); //this prints 0

Now, myStructure is an interface, that contains:
export interface Shelter {
    id: number;
    name: string;
    email: string;
    img_url: string;
    field1: string[];
    field2: string[];
    creationDateTime: string;
}

but the data inside myStructure somehow is not populated. I have no idea why, can you help me with that?

A: You need to add the console.log inside the subscribe part of the code, otherwise as it gets executed first, you will see it as 0. Change it as,
.subscribe(function(resp) {
        console.log(resp.body.length); //this prints undefined
        console.log(resp.body) // this prints {content: Array, page: 0, size: 30, totalElements: 1, totalPages: 1, …}
        this.myStructure = resp.body;
        console.log("after");
        console.log(this.myStructure.length);
    });

EDIT:
As I see you want to display the content array on the front end, so you need to assign the data as,
 this.myStructure = resp.body.content;

A: Your API doesn't return MyStructure[] it returns:
Please chose a better name for the interface
interface SomeStructure {
  content: MyStructure[];
  page: number;
  size: number;
  totalElements: number;
  totalPages: number;
  last: boolean
}

api.service.ts
getMyStructure(): Observable<HttpResponse<SomeStructure>> {
    return this.http.get<SomeStructure>(
        localUrl, { observe: 'response' });
}

app.component.ts
myStructure: MyStructure[] = [];

getMyStructure() {
    this.api.getMyStructure()
    .subscribe((resp) => {
        this.myStructure = resp.body.content;
    });
}

Take note of the arrow function in the subscribe .subscribe((resp) => {


text:
Q: I've found the fractional-ordered derivative operator I've been thinking about it since yesterday and have noticed this pattern:
We have, the first order derivative of a function $f(x)$ is:
$$f'(x)=\lim_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h} .......(1)$$
The second order derivative of the same function is:
$$f''(x)=\lim_{h\rightarrow 0}\frac{f'(x+h)-f'(x)}{h}$$
By putting $x=x+h$ in (1), we can have $f'(x+h)$.
So,$$f''(x)=\lim_{h\rightarrow 0}\frac{\lim_{h\rightarrow 0}\frac{f(x+h+h)-f(x+h)}{h}-\lim_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}}{h}$$
Or , $$f''(x)=\lim_{h\rightarrow 0}\frac{f(x+2h)-2f(x+h)+f(x)}{h^2}.....(2)$$
You can check by L'Hospital's rule that this limit evaluates to $f''(x)$.
Now, the third order derivative of the same function is:
$$f'''(x)=\lim_{h\rightarrow 0}\frac{f''(x+h)-f''(x)}{h}$$
By putting $x=x+h$ in (2), we can get $f''(x+h)$.
So, $$f'''(x)=\lim_{h\rightarrow 0}\frac{\lim_{h\rightarrow 0}\frac{f(x+3h)-2f(x+2h)+f(x+h)}{h^2}-\lim_{h\rightarrow 0}\frac{f(x+2h)-2f(x+h)+f(x)}{h^2}}{h}$$
which gives $$f'''(x)=\lim_{h\rightarrow 0} \frac{f(x+3h)-3f(x+2h)+3f(x+h)-f(x)}{h^3}......(3)$$
Again, by repeating the same process, we can get that:
$$f''''(x)=\lim_{h\rightarrow 0}\frac{f(x+4h)-4f(x+3h)+6f(x+2h)-4f(x+h)+f(x)}{h^4}....(4)$$
So, we observe that the coefficient of $f(x+(n-r)h)$ in the expression of $f^{n}(x)$ ($n^{th}$ derivative of $f(x)$) is actually $(-1)^{r}\cdot {^n}C_r$, same as the coefficient of $x^{n-r}$ in the expansion of $(x-1)^n$.
It can be proved that:
$$f^n(x)=\lim_{h\rightarrow 0}\frac{\sum_{r=0}^n(-1)^{r}\cdot ^{n}C_r\cdot f(x+(n-r)h)}{h^n}$$
where $f^n(x)$ is the $n^{th}$ order derivative of the function $f(x)$.
Now, to generalize this to fractional order derivatives, we just have to generalize the coefficients, which must be similar to the generalization of the expansion of $(x-1)^n$ to fractional exponents.
I'm not very good with binomial theorem, but I guess that it should be:
$$f^n(x)=\lim_{h\rightarrow 0}\frac{f(x+nh)-n\cdot f(x+(n-1)h)+\frac{n(n-1)}{2!}\cdot f(x+(n-2)h)-....}{h^n}$$
, where $n$ can be fractional. Have I done anything wrong?
UPDATE: A lot of people are saying that my method to get the expressions of $f''(x)$, $f'''(x)$, $f''''(x)$, etc are wrong. I've checked by L'Hospital's rule that the results are correct. Could you please write an answer about getting to these results by using a correct method?
UPDATE: On second thoughts, the $n^{th}$ derivative of a function can also proved to be equal to:
$$\lim_{h\rightarrow 0^+}\frac{\sum_{r=0}^{n}(-1)^r\cdot \binom{n}{r}\cdot f(x-(n-r)h)}{(-h)^n}$$
If we try to expand this to fractions, it can turn out to be imaginary because of the fractional power of $-1$ in the denominator.

A:
While the following does not address fractional derivatives, the OP has requested in a comment and in an UPDATE in the OP, a way to proceed rigorously to show that $$f''(x)=\lim_{h\to 0}\frac{f(x+h)-2f(x)+f(x-h)}{h^2}$$It is to that end only that we now proceed.

From the extended law of the mean, if $f$ is twice differentiable in the neighborhood of $x$, then for $h$ sufficiently small, there exists a number $\theta\in (0,1)$ such that
$$f(x+h)=f(x)+f'(x)h+\frac12 f''(x+\theta h)h^2 \tag 1$$
Alongside this, the extended law of the mean guarantees that there exists a number $\eta\in(0,1)$ such that
$$f(x-h)=f(x)-f'(x)h+\frac12 f''(x+\eta h)h^2 \tag 2$$
Adding $(1)$ and $(2)$ reveals
$$\frac12(f''(x+\theta h)+f''(x+\eta h))=\frac{f(x+h)-2f(x)+f(x-h)}{h^2} \tag 3$$
If $f''$ is continuous in a neighborhood of $x$, then we have from $(3)$
$$f''(x)=\lim_{h\to 0}\frac12(f''(x+\theta h)+f''(x+\eta h))=\lim_{h\to 0}\frac{f(x+h)-f(x)-f'(x)h}{h^2}$$
And we are done!

To obtain limit expressions for higher order derivatives, we simply use the extended mean value theorem
$$f(x+h)=f(x)+f'(x)h+\frac12f''(x)h^2+\cdots +f^{(n)}(x+\theta h)h^n \tag 4$$
and judiciously select different values combinations of $(4)$ to eliminate all derivative terms.  This is left as an exercise for the reader.

A: As an answer to the 'fractional derivative' part I mention that your derivation was on the way to Gruenwald-Leitnikov derivative. Notice the similarity in the approach and the summation :)


text:
Q: confusion about the process of earthing If the surface of the earth is negatively charged why do electrons move towards the earth when a negatively charged conductor is being discharged via earthing?

A: The earth is negatively charged relative to its upper atmosphere, which is positively charged per Kyle Kanos' link above. But all the electrons flowing around near the surface of the earth are unaffected by the net charge of the earth. Here is how to understand this:
Imagine we construct a circuit like a digital clock on a PC board and power it with a battery. But just for safety we also connect the negative battery terminal to an earth ground. The circuit works fine.
Now we replace the ground connection with a battery of voltage V whose negative terminal is connected to earth ground and whose positive terminal is connected to the negative battery terminal of the circuit. We have now lifted the ground reference of our circuit to a voltage that is +V volts above ground. We notice that the circuit still works fine.
This means that we can designate our ground reference to be any voltage we want- because the thing that drives the electrical circuit is voltage differences, and these are unaffected by any DC bias that the ground reference may possess.


text:
Q: precommit hook failed [code 225] mercurial I'm trying to commit with tortoiseHq, but I'm getting the error
Abort: precommit.whitelist hook failed, and the file is right since I diff'd with the file from another repo which is working fine and they have equal binary.
What should I do to fix this problem?

A: The precommit hook is set only on your repo, and may not be on every repository just yet. That may explain why you have the same identical file elsewhere. Or maybe it existed before the hook was added.
Nonetheless, for the problem at hand, you have few options. Either contact your admin to see why the file is not on the whitelist, and add it to the list, or disable the hook on your repo. If you do the latter, you may still get rejected at the push, if the same hook is present there, too.


text:
Q: Subtraction on PHP return 0 I have a function in PHP which calculate the distance with longitude and latitude in parameters.
//Convert to kilometers
function distance($lat1, $lon1, $lat2, $lon2, $unit)
{
  $theta = $lon1 - $lon2; //$lon1 = 1.451785000 and $lon 2 = 1.451628000 (should return -0.000157)
  echo $theta; //Display "0" instead of "-0.000157"

  $dist  = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist  = acos($dist);
  $dist  = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit  = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  }
  else if ($unit == "N") {
    return ($miles * 0.8684);
  }
  else {
    return $miles;
  }
}

The problem is that $theta returns 0 instead of the real result -0.000157.
I think it is because PHP assumes that this number is too tiny so it rounds it to 0.
Is there a function to avoid that ?

A: I think ini_set('precision', 17) is what you are looking for.

A: I found the solution for my problem !
I had to use the following code :
bcsub($lon1, $lon2, 10);

It subtracts the 2 numbers and set the number of digits after the decimal place in the result (10 here).


text:
Q: Changing permissions on FileZilla Server I've just setup a FileZilla Server on Windows,
every thing is going well, but, I cant change the file permissions.
When I'm using windows explorer I get this:

And when I'm using FileZilla FTP Client I get this response

Is there a way to do it?

A: FileZilla server does not support SITE CHMOD command.
It would not make sense anyway. FileZilla server is supported on Windows only. Unix style permissions does not make much sense on Windows.
Nor it supports any other way to change file permissions (not even Windows-style).


text:
Q: Prevent all commands from being defined as an alias Is there a way to prevent all commands from being defined as an alias?
For example a user shouldn't be able to define rm or any other command (Ubuntu default commands) as an alias name.

A: This is quite a pointless endeavor, as muru's answer shows. But there are some options, but they are not perfect.
According to bash manual, functions always take precedence over aliases, thus we could do the following:
xieerqi@eagle:~$ function alias { echo "Aliases are no-no" ; }
xieerqi@eagle:~$ alias TEST='rm'
Aliases are no-no

You could place function definition into the systemwide .bashrc , however as muru pointed out, smart users will find way to get aliases by sourcing a different bashrc file for example.
Another idea I've played with is enable built-in.
alias is a shell built in, and bash has nice enable command that allows enabling or disabling builtins. For instance, here's me disabling alias.
xieerqi@eagle:~$ enable -n alias
xieerqi@eagle:~$ alias
No command 'alias' found, did you mean:
 Command '0alias' from package 'zeroinstall-injector' (universe)
alias: command not found
xieerqi@eagle:~$ alias TEST='rm'
No command 'alias' found, did you mean:
 Command '0alias' from package 'zeroinstall-injector' (universe)
alias: command not found
xieerqi@eagle:~$ enable alias
xieerqi@eagle:~$ alias
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
xieerqi@eagle:~$

Again, using systemwide bashrc is an option here.

A: There is no way you can prevent a user from defining whatever aliases they prefer. Consider:

*

*You disable aliases in /etc/bash.bashrc. They enable it wherever they chose to.

*You delete all mentions of aliases in /etc/bash.bashrc, and all ~/.bashrc and ~/.bash_aliases via a script. They put their aliases in another file and source it.

*You run a command in PROMPT_COMMAND that disables certain aliases. They redefine or undefine PROMPT_COMMAND.

*You trap DEBUG and undefine aliases. They remove the trap.

*You chown all files sourced at invocation to root. They use another file and source it manually as the first command they run.

*You disable the builtins unset, builtin and enable; make alias a function; declare -rf alias to prevent users from modifying the function; and export the function. They run /bin/bash with --rcfile and --init-file to start a new shell, where said builtins are now enabled.

*...

You could disable aliases at compile time, then it would be up to you to keep bash up-to-date and make sure you aren't affected by the next Shellshock. Of course, the users could build their own bash.

A: TL;DR
The only way to prevent a user from creating aliases is to provide them with a shell that doesn't support aliasing. This is generally an X/Y problem, where X is really a threat model that should be solved with appropriate controls or architectures rather than trying to solve the problem post-facto after a user is given a shell on a shared system.
Below, I provide a technically-correct answer, as well as some guidance on what problems this will and won't solve. I also provide some additional guidance on alternative controls.
Using the Bash Restricted Shell
You can use Bash's restricted shell by assigning rbash as the user's login shell. For example:
foo:x:2001:2001:restricted user:/home/foo:/bin/rbash

You must then disable the alias built-in for the user, preferably without breaking everyone else's shell too. As an example, you could add the following to a file such as /etc/profile.d/rbash.sh:
# Limit effect to users in a specific UID range.
if ((UID >= 2000)) && ((UID < 3000)); then
    # Check shell options; disable alias builtins when shell is restricted.
    if [[ $- =~ r ]]; then
        enable -n alias
        enable -n unalias
    fi
fi

Caveats
Unless you've placed the user into a chroot jail or provided them with a modified PATH that doesn't include access to other shells, there's nothing stopping the user from simply typing bash at the prompt and getting an unrestricted shell.
In addition, by design the restricted shell prevents many common activities such as changing directories:
$ cd /tmp
rbash: cd: restricted

but doesn't prevent other scripts or programs in the PATH from doing so. This means you have to carefully craft the user's environment, and specifically that you need to prevent them from being able to modify the PATH in their startup files, because even though rbash makes PATH read-only it does so after initialization.
Better Choices
Even if you use rbash, you need to do so as part of a broader set of controls. Some examples may include:

*

*Prevent non-technical users from accidentally invoking dangerous commands by providing default aliases such as rm -i, mv -i, and cp -i in the /etc/bash.bashrc file.

*

*Given your original example, this is probably the most sensible solution.

*You can combine this with enable -n alias if you like.

*This won't prevent knowledgable users from changing the aliases, but it may be sufficient to prevent non-technical users from doing whatever it is you're concerned about.

*Traditional Unix permissions or POSIX ACLs to protect files and directories.

*Logins that perform a single non-interactive command. For example:
foo:x:2001:2001:run foo.sh:/home/foo:/usr/local/bin/foo.sh

*Use per-key SSH forced commands. For example:
# ~foo/.ssh/authorized_keys
command="/usr/local/bin/foo.sh" [remainder of line]

*Use the OpenSSH ForceCommand option with a conditional Match block.

*Use special tools like gitolite or scponly designed for your specific use case.

*Use a chroot jail.

*Use virtualization such as Xen, OpenVZ, LXC, VMware, VirtualBox, or other technologies to provide a segregated environment.
Once you have accurately defined your threat model, you can identify the most appropriate controls for your use case. Without a more meaningful understanding of why you want to prevent aliasing (e.g. what real-world problem does it solve?) you can't select the most appropriate controls.

A: You could define (in /etc/profile) a function called alias which does the validation you want (probably using type -p) (after all "Ubuntu default commands" are "executables in $PATH") before calling the builtin alias, BUT, as others have pointed out, your users could get around that. Why not get a different set of users, or educate them ("Defining an alias that overrides a command is a Very Good Way of Shooting Oneself in the Foot, and causing confusion (e.g, Why does ls prompt for my password?))?


text:
Q: get status callback function from service how to implement call-back function between component and service..Sorry I'm still new with angular and typescript.
getDiscount(){
    let getDisc = [];
    getDisc.push({
      price: Number(this.commonService.getPayments$.getValue())
    });

    this.commonService._getGlobalDiskaun(getDisc[0])
    setTimeout(() => this.getResult(),1000);
  }

I'm trying to implement like above code but it give null result when network slow. How to code when this.commonService._getGlobalDiskaun(getDisc[0]) get value then call this function this.getResult()

A: This issue occurs because you are using a setTimeout method with a 1-second delay and the result of the API might not reach in one second
You need to subscribe the service you are using so you can invoke the function as soon as you get the response from the API like this:
this.commonService._getGlobalDiskaun(getDisc[0]).subscribe(result => this.getResult())

you also need to return data in your service like this:
_getGlobalDiskaun(){
   return this.http.get<any>(`${your_api_address}`)
}

It might be a POST request but doesn't matter and you still need to return the response in your service


text:
Q: Tengo que editar datos de mi base de datos pero para eso tengo que saber la id de la categoría Este es código y el error es en el segundo select
Update producto set PrecioVenta="4590",

PrecioCompra="3750",

Nombre="Carburador 28mm",

Stock="12",

Marca="Mikuni",

Descripcion="Moto Suzuki DR-Z400 Kawasaki KLX",

NomFoto ="carburador.png",

(select IDCat from categoria where NombreCat ="Otros") where CodigoProducto = "34535453";


text:
Q: AttributeError: 'Settings' object has no attribute 'scene' I need to add pixmap to my rectangles. When I press the click button then my pixmap will be added to one by one in my rectangles but I got this attribute error. Can any one please guide me how to solve this error? I tried so many ways but I didn't get the proper output.
Thank you in advance.
Given below is my code:
from pyface.qt import QtGui, QtCore
import sys
global X,Y

class ScanView(QtGui.QGraphicsView):
    def __init__(self,X=5, Y=5, parent=None):
        super(ScanView, self).__init__(parent)

        self.row = X
        self.cols = Y
        self.squareLB = 50
        self.width = Y*self.squareLB+2*self.squareLB
        self.height = X*self.squareLB+2*self.squareLB
        self.List = []
        if self.width>708:
            self.scene = QtGui.QGraphicsScene(0,0,self.width,self.height)
            for i in range(self.row):
                for j in range(self.cols):
                    item = self.scene.addRect(QtCore.QRectF(0,0,self.squareLB,self.squareLB))
                    item.setPos(self.squareLB+j*self.squareLB, X*self.squareLB-(i*self.squareLB))
                    self.List.append(item)
        else:
            self.scene = QtGui.QGraphicsScene(0,0,708,self.height)
            self.marginLR = (708.0-Y*self.squareLB)/2.0
            for i in range(self.row):
                for j in range(self.cols):
                    item = self.scene.addRect(QtCore.QRectF(0,0,self.squareLB,self.squareLB))
                    item.setPos(self.marginLR+j*self.squareLB, X*self.squareLB-(i*self.squareLB))
                    self.List.append(item)

        self.setScene(self.scene)

class Settings(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Settings, self).__init__(parent)
        spacer = QtGui.QWidget(self)
        spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        self.vbox = QtGui.QVBoxLayout()
        self.save = QtGui.QPushButton("save")
        self.open= QtGui.QPushButton("open")
        self.folder= QtGui.QPushButton("Folder")
        self.folder.clicked.connect(self.showSettings)
        self.vbox.addWidget(self.save)
        self.vbox.addWidget(self.open)
        self.vbox.addWidget(self.folder)
        self.grid = QtGui.QGridLayout()
        self.grid.addLayout(self.vbox,0,0)
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
        self.scrollArea.setWidgetResizable(True)
        self.grid.addWidget(self.scrollArea,0,1)
        self.setCentralWidget(QtGui.QWidget(self))
        self.centralWidget().setLayout(self.grid)
        self.setGeometry(200,100,300,300)
        self.show()
    def showSettings(self):
        self.MyView = ScanView(5,5)
        self.vbox2 = QtGui.QVBoxLayout()
        self.Scanbtn1 = QtGui.QPushButton(("click"))
        self.Scanbtn1.clicked.connect(self.on_clicked)
        self.vbox2.addWidget(self.Scanbtn1)

        self.newwidget = QtGui.QWidget()
        self.glayout = QtGui.QGridLayout(self.newwidget)
        self.glayout.addWidget(self.MyView,0,0)
        self.Sw = QtGui.QWidget()
        self.Sw.setLayout(self.vbox2)
        # self.Sw.setFixedWidth(width - self.scrollArea.viewport().width())
        self.glayout.addWidget(self.Sw,0,1)

        self.scrollArea.setWidget(self.newwidget)

    def on_clicked(self):
        print "hellloooooo"
        filename1 = "./img/tick.png"
        pixmap = QtGui.QPixmap(filename1)
        if not pixmap.isNull():
            self.MyView.add_pixmap(pixmap)
        # pic = QtGui.QPixmap("./img/tick.png")
        # scene.addItem(QtGui.QGraphicsPixmapItem(pic))
        # # view = self.gv
        # self.MyView.setScene(scene)
        # self.MyView.setRenderHint(QtGui.QPainter.Antialiasing)
        # self.MyView.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Settings()
    sys.exit(app.exec_())
if __name__ == '__main__':
    main()

A: You have that error because scene does not exist in the Settings class, self.scene is a member of the ScanView class plus self.scene is different from scene.
Going to the problem, you must add as a child of the rectangles and you must also change the size of the pixmap is necessary. To obtain the first rectangle you must store it in a list and then create an iterator.
import sys
from pyface.qt import QtGui, QtCore

class ScanView(QtGui.QGraphicsView):
    def __init__(self,X=5, Y=5, parent=None):
        super(ScanView, self).__init__(parent)
        self._squares = []
        n_rows, n_cols = X, Y
        squareLB = 50
        width, height = (Y + 2)*squareLB, (X + 2)*squareLB
        self._scene = QtGui.QGraphicsScene(0, 0, max(708, width), height)
        p = squareLB if width > 708 else (708.0-Y*squareLB)/2.0

        for i in range(n_rows):
            for j in range(n_cols):
                it = self._scene.addRect(0, 0, squareLB, squareLB)
                it.setPos(p + j*squareLB, i*squareLB)
                self._squares.append(it)
        self.setScene(self._scene)

class Settings(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Settings, self).__init__(parent)
        self.save = QtGui.QPushButton("save")
        self.open = QtGui.QPushButton("open")
        self.folder = QtGui.QPushButton("Folder", clicked=self.showSettings)
        central_widget = QtGui.QWidget()
        self.setCentralWidget(central_widget)
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.save)
        vbox.addWidget(self.open)
        vbox.addWidget(self.folder)
        self.scrollArea = QtGui.QScrollArea(widgetResizable=True)
        self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
        hlay = QtGui.QHBoxLayout(central_widget)
        hlay.addLayout(vbox)
        hlay.addWidget(self.scrollArea)
        self.setGeometry(200, 100, 300, 300)

    def showSettings(self):
        self.view = ScanView(5, 5)
        self.scanbtn = QtGui.QPushButton("click", clicked=self.on_clicked)
        self.newwidget = QtGui.QWidget()
        hlay = QtGui.QHBoxLayout(self.newwidget)
        hlay.addWidget(self.view)
        hlay.addWidget(self.scanbtn)
        self.scrollArea.setWidget(self.newwidget)

        self._iter_squares = iter(self.view._squares)

    def on_clicked(self):
        filename = "./img/tick.png"
        pixmap = QtGui.QPixmap(filename)
        if pixmap.isNull():
            return
        try:
            it = next(self._iter_squares)
        except StopIteration:
            pass
        else:
            pixmap = pixmap.scaled(it.rect().size().toSize())
            pixmap_it = QtGui.QGraphicsPixmapItem(pixmap, it)

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Settings()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
Q: No module named 'encodings' error while starting uwsgi I referred to following three links to upgrade python to 3.6.3 version and create virtual environment and then tried to server django via nginx/uwsgi. However, i'm struggling with the error saying "no module named encodings".
If I used  below command then the django can be accessed. However, If run over the config file it will raise error saying "no module named encodings".
 "uwsgi --http :8080 --home /home/testuser1/myproject --chdir
/home/testuser1/myprojecttss -w myprojecttss.wsgi
 "

https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-centos-7#setting-up-the-uwsgi-application-server
https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-centos-7#set-up-an-app-directory-and-a-virtualenv
Error Log:
 (myproject) [test@VM_134_114_centos ~]$ systemctl status uwsgi -l
 * uwsgi.service - uWSGI Emperor service
  Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: disabled)
  Active: active (running) since Sat 2018-01-20 20:29:47 CST; 9min ago
  Main PID: 11381 (uwsgi)
  Status: "The Emperor is governing 0 vassals"
    CGroup: /system.slice/uwsgi.service
       `-11381 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites

Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uwsgi socket 0 bound to UNIX address /run/uwsgi/myprojecttss.sock fd 3
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uWSGI running as root, you can use --uid/--gid/--chroot options
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: setuid() to testuser1
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Python version: 3.6.3 (default, Jan 17 2018, 14:02:51)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Set PythonHome to /home/testuser1/myproject
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Fatal Python error: Py_Initialize: Unable to get the locale encoding
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: ModuleNotFoundError: No module named 'encodings'
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Current thread 0x00007fb1c7a04840 (most recent call first):
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Sat Jan 20 20:38:16 2018 - [emperor] curse the uwsgi instance myprojecttss.ini (pid: 12256)
Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Sat Jan 20 20:38:16 2018 - [emperor] removed uwsgi instance myprojecttss.ini

uwsgi config file:
 [uwsgi]
 project = myprojecttss
 username = testuser1
 base = /home/%(username)
 env = myproject

 chdir = %(base)/%(project)
 module = %(project).wsgi
 home = %(base)/%(env)
 ##module = %(project).wsgi:application
 master = true
 processes = 5
 binary-path = %(base)/%(env)/bin/uwsgi
 #virtualenv = %(base)/%(env)
 uid = %(username)
 socket = /run/uwsgi/%(project).sock
 chown-socket = %(username):nginx
 chmod-socket = 775
 vacuum = true
 die-on-term = true

uwsgi service:
    [Unit]
      Description=uWSGI Emperor service

    [Service]
    ExecStartPre=-/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown testuser1:nginx /run/uwsgi'
    ExecStart=/usr/bin/bash -c 'cd /home/testuser1/myprojcettss; source /home/testuser1/myproject/bin/activate; uwsgi --ini  /etc/uwsgi/sites/myprojecttss.ini'
   Restart=always
   KillSignal=SIGQUIT
   Type=notify
   NotifyAccess=all

  [Install]
  WantedBy=multi-user.target


text:
Q: Help needed in refining PHP search I am trying to create a php search engine which can refine search results based on time similar to google's search refine but with a select dropdown without a submit button.
I am using sql server as database with pdo-sqlsrv driver. The regular search works great. I have problem only in passing value in time variable through select box and loading the page as soon as user selects the option.
Any help would be great.
Thanks

A: Add <select name="foo" onchange="javascript:this.form.submit();">

A: In JavaScript , you can do something like...
onchange="mysubmit()"


text:
Q: How to Get cell index in gridview I'm using a website(asp.net,C#) to view some details in gridview. In that gridview I have generated checkboxes dynamically. So it will be placed any cell inside of that gridview. I find that control in grdview by using FindControl(), but I cant get that cell index... now I want to get that excact cell index which placed that checkbox. How shall I get that cell index?
Please anyone Tell me the solution of this problem.
Thanks in advance.
My code for getting that Control is:
if (HeaderCell.Text.Contains(strColumnName))
{
    CheckBox chk = GrdDynamicControls.Rows[index].FindControl(chkCheckBox1.ID) as CheckBox;
    chk.Checked = true;
    strCelValue = chk.Checked.ToString();
}

A: Try this:
int theCellNumberWhatINeed = -1;
for (int cellNumber = 0; cellNumber < GridView1.Rows[index].Cells.Count; cellNumber++)
{
    foreach (Control ctrl in GridView1.Rows[index].Cells[cellNumber].Controls)
    {
        if (ctrl.ID == "aCheckBox") // or compare by clientid... etc
        {
            theCellNumberWhatINeed = cellNumber;
            break;
        }
    }
}
if (theCellNumberWhatINeed > -1)
{
    // ...
}

Not the most elegant solution but works with the builtin gridview control without creating your own.

A: You can use Event Args e

e.Item.ItemIndex

it will return an integer
Hope this will help


text:
Q: The onclick EventListener not working more than once i've made a word finder that would find a word whenever i click button and send input in the prompt.
Now the problem is that my event listener's not working more than once.
Here's my javascript code:
const words = []; // /lorem/gi, /ipsum/gi

let makeFindWord = document.getElementById("makeFindWord");
makeFindWord.onclick = () => {
    let input = prompt("Search a word");
    console.log("works");

    let value = new RegExp(input, "gi");
    words.push(value);

    console.log(words);

    findTheWord(words);

    console.log(makeFindWord.onclick);
};

function findTheWord(words) {
    const body = document.body;

    let log = [];

    for (const w of words) {

        loo: do {
            let theWord = w.exec(body.innerHTML);
            if (theWord == null) {
                break loo;
            } else {
                let index = theWord.index;
                let length = theWord[0].length;

                let word = body.innerHTML.substring(index, index + length);
                log.push([theWord, word, index, length]);
            }
        } while (true);

    }

    log.forEach(w => {
        let word = w[1];
        body.innerHTML = String(body.innerHTML).replaceAll(word, `<span style="color: #fe0">${word}</span>`);
    });
}

A: Problem:
The problem is that you are manipulating the whole body tag using the DOM innerHTML property. It replaces the button with the id "makeFindWord" also and the Event Listener on that button no longer works because you have replaced the button with id "makeFindWord" with new one using innerHTML.. Its pretty normal thing in JavaScript DOM.
Solution:
Wrap the whole body inside an other container (say a div with id "search-container"). Don't forget to place your Button (having id "makeFindWord") outside this container.
Here is the complete working code:
 <!DOCTYPE html>

  <title>Title</title>

  <button id="makeFindWord">Button</button>

Lorem ipsum dolor sit amet

I have attached a screenshot showing the working output. Now,
EventListener will work forever.

A: Delete this line in makeFindWord.onclick
makeFindWord = document.getElementById("makeFindWord");


text:
Q: javascript to insert image I am currently building a site to be used for a digital menu display. I am having trouble getting a input field that user is prompted to change the picture in the page. the images will be hosted locally on the displays netbook not through the sites server (picture selections will change regularly). any ideas would be a great help
 bellow is the code i have so far:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Custom Entree</title>

</image>

<embed name="" id="logo" src="custom.pdf#scrollbar=0" type="application/pdf" width="900px" height="900px" scrollbar="0" /><input name="" type="image" width="900" height="900" />

<input type="text" id="price" border="0" />

<input type="text" id="price" border="0" />

A: It doesn't seem like your question is that clear.  To replace an image's source, it's as simple as this:
var images = ['imageone.jpg','imagetwo.jpg'];
var img    = document.getElementById('logo');
img.src    = images[0];

[EDIT:] Based on your last comment using file://, it looks like this is what you are after:

<input id='file' type='file' onchange='callme()' value='' />


text:
Q: How to locate the nearest marker to a user? I'm quite new to android development and I was wondering if it is possible for me to locate the nearest marker to a user and knowing which marker is closest direct the user there using a polyline and google directions api. The locations of the markers are taken from a database that I have parsed into a list array which I then use to place the markers on the map. I have tried to find help from other questions however they do not seem to fit in my project.
If it is possible for me to find the nearest marker to the user how can I do it if not is there an alternative method I could use??
This is my code for my main activity:
package com.example.defiblocator;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        LocationListener,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener{

    public static TextView data;
    public static String location;
    GoogleMap mapAPI;
    SupportMapFragment mapFragment;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    String delimiter = ",";
    List<String> full = new ArrayList<>();
    List<String> size = new ArrayList<>();
    private ArrayList<LatLng> markerCoords = new ArrayList<LatLng>();
    String info;
    String name;
    Double lat;
    Double lng;
    Button emergency;
    LatLng mark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapAPI);
        mapFragment.getMapAsync(this);

        data = findViewById(R.id.fetchdata);
        new fetchData(new CallbackClass()).execute();

        emergency = findViewById(R.id.button);
        emergency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mapAPI = googleMap;
        mapAPI.getUiSettings().setZoomControlsEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mapAPI.setMyLocationEnabled(true);
                //mapAPI.setOnMyLocationChangeListener(this);
            }
        } else {
            buildGoogleApiClient();
            mapAPI.setMyLocationEnabled(true);
        }

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

        /*mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }*/
        //Place current location marker
        LatLng patient = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(patient);
        markerOptions.title("Patient");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
        mCurrLocationMarker = mapAPI.addMarker(markerOptions);

        //move map camera
        mapAPI.animateCamera(CameraUpdateFactory.zoomTo(11));
        mapAPI.moveCamera(CameraUpdateFactory.newLatLng(patient));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    public class CallbackClass implements CallbackInterface {

        @Override
        public void onSuccess(String callbackData) {
            info = callbackData;
            full = Arrays.asList(info.split(delimiter));
            size = Arrays.asList(info.split(delimiter));

            Integer x = 0;
            while(x != size.size()){

                name = full.get(x);
                x += 1;
                lat = Double.valueOf(full.get(x));
                x += 1;
                lng = Double.valueOf(full.get(x));
                x += 1;
                LatLng pos = new LatLng(lat, lng);
                mapAPI.addMarker(new MarkerOptions().position(pos).title(name));

                mark = new LatLng(lat,lng);
                markerCoords.add(mark);

            }
        }

        @Override
        public void onFailure() {

        }
    }

}

and this is the code for parsing the JSON from the database any help would be greatly appreciated.
package com.example.defiblocator;

import android.app.Application;
import android.os.AsyncTask;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class fetchData extends AsyncTask <Void,Void,Void>{

    CallbackInterface callbackInterface;
    String data = "";
    String json_url;
    String singleParsed = "";
    public String dataParsed = "";
    String sent;

    public fetchData(CallbackInterface callbackInterface) {
        this.callbackInterface = callbackInterface;
    }

    public Integer x = 0;
    @Override
    protected void onPreExecute(){
        json_url = "http://defiblocator.ml/json_get_data.php";
        dataParsed = "";
    }
    @Override
    protected Void doInBackground(Void... voids) {

        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray JA = new JSONArray(data);
            for(int i =0 ; i <JA.length(); i++){
                JSONObject JO = (JSONObject) JA.get(i);
                singleParsed = JO.get("name") + "," + JO.get("lat") + "," +JO.get("lng") + "," ;
                dataParsed = dataParsed + singleParsed ;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException | JSONException e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {

        MainActivity.data.setText(dataParsed);
        callbackInterface.onSuccess(dataParsed);

    }

}

A: You could use a simple distance formula to archive this:
private Double distance(Double lat1, Double lon1, Double lat2, Double lon2) {
  return Math.sqrt (Math.pow((lat1 - lat2), 2) - Math.pow((lon1 - lon2), 2));
}

// The user Location
currentLat = xxxx;
currentLon = xxxx;

if ((markerCoords != null) && (markerCoords.size() > 0)) {
  LatLng near = markerCoords.get(0);
  for (int x = 1; x < markerCoords.size(); x++) {
    Double lat = markerCoords.get(x).latitude;
    Double lon = markerCoords.get(x).longitude;

    Double currentMarkerdistance = distance(
      currentLat,
      currentLon,
      markerCoords.get(x).latitude,
      markerCoords.get(x).longitude);

    Double nearMarkerdistance = distance(
      currentLat,
      currentLon,
      near.latitude,
      near.longitude);

    if (currentMarkerdistance < nearMarkerdistance) {
      near = markerCoords.get(x);
    }
  }
}

// After this process the near variable will hold the near marker