text:
Q: A possible simplification of the Time-Independent Schrodinger equation? The Time Independent Schrodinger Equation is as follows: $$-\frac{\hbar^2}{2m}\frac{d^2\psi}{dx^2}+V(x)\psi(x)=E\cdot\psi(x)$$
Due to the fact that $E=E_{kinetic}+E_{potential}$ and the fact that $V$ is the potential energy, the equation could be simplified to $$-\frac{\hbar^2}{2m}\frac{d^2\psi}{dx^2}=(E-V(x))\cdot\psi(x)=\frac{1}{2}mv^2\cdot\psi(x)$$
which can be rearranged to get $$-\frac{\hbar^2}{p^2}\frac{d^2\psi}{dx^2} = \psi(x)$$
After applying the De Brogile relationship, we have that $$-\left(\frac{\lambda}{2\pi}\right)^2\frac{d^2\psi}{dx^2}=\psi(x)$$
which can be simplified to
$$\frac{d^2\psi}{dx^2} + k^2\psi(x) = 0$$
This is the differential equation for a system with zero potential energy, and it would be absurd to think that all systems behave as such. As such, what is the mistake in this simplification of the Schrodinger Equation, or if there is none, then is there any confirmation in the literature of this form?

A: Thanks to @QMechanic and @JahanClaes for clearing up this question in the comments.
As $$k=\frac{\sqrt{2m(E-V)}}{\hbar} = \frac{\sqrt{\hat{p}^2}}{\hbar}=-i\frac{\partial}{\partial x},$$ we have that $$k^2\psi=-\frac{\partial^2 \psi}{\partial x^2}$$ and thus when substituted into the derived equation we obtain an identity, and thus the derived equation is equivalent to the Schrodinger Equation.
The confusion arose by considering momentum and kinetic energy as artifacts of classical mechanics, but it is resolved by considering momentum in the context of quantum mechanics, where $\hat{p}=-i\hbar \frac{\partial}{\partial x}.$


text:
Q: How to create an SVG component dynamically in Angular2? I am creating a web application which uses SVG.
I have created components consist of SVG element, and they are put into a root svg element.
They have attribute selector, because SVG/XML document tree is strict so I cannot use element selector.
And they have a template starts with svg:g tag:
@Component({
  selector:'[foo]',
  template: '<svg:g>...</svg:g>',
})

In the application, I want to create a component when a user press a button,
and simultaneously start dragging it.
I thought it can be achieved by creating a component dynamically using ComponentResolver:
  @ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef})
  protected dynamicComponentTarget: ViewContainerRef

  private componentResolver: ComponentResolver

  onMouseDown() {
    this.componentResolver
      .resolveComponent(FooComponent)
      .then((factory) => {
        const dynamicComponent = this.dynamicComponentTarget.createComponent(factory, 0)
        const component: FooComponent = dynamicComponent.instance
        const element = dynamicComponent.location.nativeElement
        // add event listener to start dragging `element`.
      })
  }

Component is created when onMouseDown() called, but its DOM element is div, so it is illegal element in svg document and cannot be displayed.
I have tried with selector='svg:g[foo]', then g element is created, but its namespace is not for SVG (http://www.w3.org/2000/svg), but normal HTML namespace (http://www.w3.org/1999/xhtml) and its class is HTMLUnknownElement > g.
I also tried with selector='svg:svg[foo]', then svg:svg element is created and it is displayed. But svg:svg cannot move with transform attribute so this doesn't work well for my application.
How can I dynamically create svg:g element for attribute selector component?
I am using Angular2: 2.0.0-rc4.

A: You're right about the namespacing issues keeping the g element from rendering as svg. Unfortunately, attaching the node as an svg element is the only way to feasibly get the component to namespace properly.
However, this doesn't mean this won't work. If you add the drag functionality as a directive on the g element in the template, it will be compiled with your component, and you can offset your logic into that directive. The top level svg will be namespaced correctly, and the template will inherit this accordingly.
import {Component, Input} from '@angular/core';

@Component({
  selector: 'svg:svg[customName]', // prevent this from hijacking other svg
  template: '<svg:g dragDirective>...</svg:g>', // note the directive added here
  style: []
})
export class GComponent {

  constructor() { }

}

This may not be ideal, but until https://github.com/angular/angular/issues/10404 is resolved, there's not much of an alternative.

A: I am not sure that my solution is right but it works for me (even with ivy):
@Component({
...
})
class ParentComponent {
    constructor(
        private injector: Injector,
        private appRef: ApplicationRef,
        private componentFactoryResolver: ComponentFactoryResolver,
    ) {}

    createDynamicComponent() {
        let node = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        let factory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
        let componentRef = factory.create(this.injector, [], node);

        this.appRef.attachView(componentRef.hostView);
    }
}

After that you must manually append node into DOM.

A: Instead of trying to create your component to the view with the Component Resolver I will do this instead.

*

*Create a object with properties which match the attributes you want to pass to your SVG Component.

*Append this object to an array (ex.svgItems).

*Add *ngFor="svgItem in svgItems" to the SVG component you want to create dynamically.

Hope it's clear and solve your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CBORFactory NoClassDefFoundError exception in spark 3.0.0 I am having spark streaming application using kinesis and running in EMR 6.0.0,
It's running fine locally but when deploying  to AWS EMR it keeps failing with
NoClassDefFoundError exception
20/11/17 15:26:56 INFO Client:
     client token: N/A
     diagnostics: User class threw exception: java.lang.NoClassDefFoundError: com/fasterxml/jackson/dataformat/cbor/CBORFactory
    at com.amazonaws.protocol.json.SdkJsonProtocolFactory.getSdkFactory(SdkJsonProtocolFactory.java:123)
    at com.amazonaws.protocol.json.SdkJsonProtocolFactory.createGenerator(SdkJsonProtocolFactory.java:54)
    at com.amazonaws.protocol.json.SdkJsonProtocolFactory.createGenerator(SdkJsonProtocolFactory.java:74)
    at com.amazonaws.protocol.json.SdkJsonProtocolFactory.createProtocolMarshaller(SdkJsonProtocolFactory.java:64)
    at com.amazonaws.services.kinesis.model.transform.DescribeStreamRequestProtocolMarshaller.marshall(DescribeStreamRequestProtocolMarshaller.java:52)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.executeDescribeStream(AmazonKinesisClient.java:861)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.describeStream(AmazonKinesisClient.java:846)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.describeStream(AmazonKinesisClient.java:887)
    at com.gartner.tn.datafeed.application.PositionStreamApplicationV4.getJavaDStream(PositionStreamApplicationV4.java:240)

A: I had the exact same issue and I solved it by removing the dependence on CBOR from Kinesis.  I am not sure if that is an option for you but it worked for me.
There are a few ways to do this but, for when running in local mode, I put the following code at the beginning of the main class in my streaming spark application;
System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true");

When running in cluster mode start your spark submit as follows;
spark-submit --deploy-mode cluster \
--conf spark.driver.extraJavaOptions='-Dcom.amazonaws.sdk.disableCbor=true' \
--conf spark.executor.extraJavaOptions='-Dcom.amazonaws.sdk.disableCbor=true'

When running in client mode on the cluster start like this;
spark-submit --deploy-mode client \
--driver-java-options '-Dcom.amazonaws.sdk.disableCbor=true' \
--conf spark.executor.extraJavaOptions='-Dcom.amazonaws.sdk.disableCbor=true'

This question led me to the answer; Getting an AmazonKinesisException Status Code: 502 when using LocalStack from Java


text:
Q: UIButton and UILabel display strange characters when reading from sqlite my app reading from a SQLite database and display the text on UILabel, but for some reasons, a small "rectangle symbol" appear as shown  in the picture. When I use NSLog to print the text in the console, the text appears normally, i.e, just printing out "Home." (without the rectangle symbol)

Here is my code:
NSString *text=[[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];

NSLog(text);
myLabel.text=text;

A: try:
NSLog ([NSString stringWithFormat:@"%s<--",text]);

in your console output, does the <-- appear on the line below the text?  If so, you've likely got a CR/LF terminated string.
Or likely more useful, enumerate each character in your string and output to console as hex value, you can then at least see what these characters are (if not CR/LF).


text:
Q: Send Default data through ajax post request I am trying to send a default data in every ajax post request however using the below code I the data is being sent for all the requests. Please suggest.
$.ajaxSetup({
          data: {
             at: $('#at').attr('value'),
          },
       });

A: I think you can try below. Thought not tried it running.

*

*Setup the ajax like below with "beforeSetup"
$.ajaxSetup({
    beforeSend: myFunc
});

*In the function "myFunc" check if it is a post request then set the data.
UPDATE : This will work !
$.ajaxSetup({
                  beforeSend: function(xhr, settings) {
                          if (settings.type == 'POST') {
                                  if(settings.data == null || settings.data == '' || settings.data == undefined) {
                                          settings.data = "?value=test";
                                  } else {
                                          settings.data = settings.data + "&value=test";
                                  }
                          }
                  }
               });

A: You can register a global AJAX event handler like .ajaxSend() and check the request type, for example
$(document).ajaxSend(function(event, jqxhr, settings) {
    if (settings.type == 'POST' && !settings.data) {
        settings.data = $.param({at: $('#at').attr('value')});
    }
});


text:
Q: How do I disconnect PyCharm from all debug sessions? I have about 5 processes/services that make up a single app.  During development, I've got all 5 of them running at once, but when I try to close PyCharm, I get pestered with this annoying dialog 5 times:

Is there a way to make PyCharm assume the obvious and kill them all without pestering me?
A similar question was asked here, but, in that case, the person was accidentally starting several of the same process, so the accepted answer was "don't start so many processes".  In my case, I don't have a choice - I need all 5.


text:
Q: ansible & bash deployment on remote tomcat server I have written an ansible script to execute a bash scipt on remote server.
When I am running the same bash script directly on node, Its working fine.
Through ansible its not working properly and return without any error.
Scenario: 1. kill tomcat 2.deploy the war file 3.start tomcat
This scenario perfectly works while executing directly on remote node.
Through ansible tomcat is getting killed but deploy and start is not working.
Can anyone guide please.

A: The issue is with the user. Seems like the user is not added in the sudoers file.
Also please make a practice to update the question with as much info as possible. For eg playbook code error using the proper syntax that SO supports
Cheers,
Yash


text:
Q: Is there a libfaketime alternative for Golang? I want to automate some tests where I have to manipulate the system time to check for authentication behaviours of a program that is written in golang. According to this post, libfaketime does not work with golang. Is there another way that I can achieve what I want to do with libfaketime?
Here's a description of what libfaketime does from github.

libfaketime intercepts various system calls that programs use to retrieve the
  current date and time. It then reports modified (faked) dates and times (as
  specified by you, the user) to these programs. This means you can modify the
  system time a program sees without having to change the time system-wide.

A: No, there is none.
You need to use something like clockwork (see this for more) and explicitly pass "time" implementation around your code.

Update from 2021-03-01 with a more up-to-date list of options:

*

*https://github.com/LopatkinEvgeniy/clock

*https://github.com/jonboulle/clockwork

*https://github.com/benbjohnson/clock

*https://github.com/facebookgo/clock

*https://github.com/tkuchiki/faketime

*https://github.com/rzajac/clock

A: There is this repository (tkuchiki/faketime) which claims to be able to fake the time.Now()-function. I don't know how extensively this works and haven't tested it. But it sounds like it might be a solution to your problem.


text:
Q: NullPointer Exception in listview,creating separate layout for listitems? I created a listview that contains two types of items either text or image.But i am getting nullpointer exception only on when i scrolling down.
my adapter's code is this.
public class ListViewAdapter extends BaseAdapter {

ArrayList<ListModel> myList = new ArrayList<ListModel>();
LayoutInflater inflater;
Context context;
private static final int TYPE_ITEM1 = 1;
private static final int TYPE_ITEM2 = 2;

public ListViewAdapter(Context context, ArrayList<ListModel> myList) {
    this.myList = myList;
    this.context = context;
    inflater = LayoutInflater.from(this.context);

}

int type;

@Override
public int getItemViewType(int position) {
    ListModel listModel = myList.get(position);
    String data = listModel.getType();
  /*  if (data.equals("Text")) {
        return type1;
    } else if (data.equals("Image")) {
        return type2;

    }return 0;*/

    if (data.equals("Text")) {
        type = TYPE_ITEM1;
    } else if (data.equals("Image")) {
        type = TYPE_ITEM2;
    }
    return type;

}

@Override
public int getViewTypeCount() {
    return myList.size() + 1;
}

@Override
public int getCount() {
    return myList.size();
}

@Override
public ListModel getItem(int position) {
    // return myList.get(position);

    if (position >= myList.size()) {
        return null;
    }
    return myList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    View v = convertView;
    TextView textView = null;
    ImageView imageView = null;
    int type = getItemViewType(position);
    System.out.println("getView " + position + " " + v + " type = " + type);
    if (v == null) {
        holder = new ViewHolder();
        if (type == TYPE_ITEM1) {
            v = inflater.inflate(R.layout.list_text, null);
            textView = (TextView) v.findViewById(R.id.text);
        } else if (type == TYPE_ITEM2) {
            v = inflater.inflate(R.layout.list_image, null);
            imageView = (ImageView) v.findViewById(R.id.imgView);
        }
        holder.textView = textView;
        holder.imageView = imageView;
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    ListModel model = myList.get(position);
    String datatype = model.getType();

    if (datatype.equals("Text")) {

        holder.textView.setText(model.getData());

    } else if (datatype.equals("Image")) {

        UrlImageViewHelper.setUrlDrawable(holder.imageView, model.getData());

    }

    return v;
}

public static class ViewHolder {
    public TextView textView;
    public ImageView imageView;

}}

The error is
java.lang.NullPointerException in line 117, it is the textView,

A: It is a classic ArrayIndexOutOfBoundsException. Don't forget that arrays in java (like in most programming language) are 0-indexed, meanign the first element is at index 0 (not 1).
You haven't shown any caller code, but most likely some of your code are calling methods getItem() or getView() with a position which value is 2 where it should be 1 (to access to second element in the list).
If you cannot control the caller (maybe it is from an third-party library), then I suggest that:

*

*offset the value of position by -1. But this might break some other part of your code.

*add some protection in your code to prevent exception, such as:

public ListModel getItem(int position) {
    if (position >= myList.size()) {
        // TODO: log an error, show a message, etc.
        return null; // or a default value
    }
    return myList.get(position);
}

It is also possible that the values you chose for TYPE_ITEM1 and TYPE_ITEM2 are not well if they must represent indices in arrays. Consider using 0 and 1 instead.

A: It's probably your getItemViewType. You should return a zero-based index (i.e. 0 or 1 not 1 or 0). From the docs:

Note: Integers must be in the range 0 to getViewTypeCount() - 1


text:
Q: how to check heap size allocated for jvm by linux I have apache-tomcat as my web server.
I want to check what heap size is allocated for jvm by linux.
Also from where, I can modify it.

A: You can easily check the heap size memory allocation using JConsole, if you have a path to your jre/jdk set up correctly on the system you should be able to start it with command jconsole from anywhere.
For managing your heap memory allocation you can have a look here: http://javahowto.blogspot.com/2006/06/6-common-errors-in-setting-java-heap.html

A: A simple way on Linux is to run the following:
ps -ef |grep tomcat

Look for the starting and maximum JVM memory:

-Xms1024m -Xmx4096m

In this case it is allocating 1G on startup and the Maximum is 4G.

A: The heap size used by Tomcat is defined in its configuration.
This is the place where you can both check and change it.
If you're unsure about where this configuration is saved, I'd suggest looking at the Tomcat documentation where this is explained together with all configuration values.

A: If you need more information from the server but cannot log into it interactively (or don't have a GUI or JMX set up etc) you can include javamelody in your POM file/libs and it will create a page at host:8080//monitoring with all kinds of good information, including heap size, GC statistics and permgen size.
This is NOT a safe thing to leave running in a production environment - if you need it all the time at least lock it down!


text:
Q: Update a component prop from another one I have a component A who display a collection of item. I have a component B with filters (search bar, radio) than should update the items in component A. When I log this.componentA.items from component B, i see data but visually nothing happen.
Here is what I have:
// ComponentA.ts
imports {} from '...'
@Component({...})
export class ComponentA implements OnInit {

  public items: Item[];

  constructor(private itemService: ItemService) {}

  ngOnInit() {
    this.itemService.getItems().subscribe(items => {
      this.items = items.map( item => new Item().deserialize(item));
    })
  }
}

// ComponentB.ts
imports {} from '...'
@Component({...})
export class ComponentB implements OnInit {

  constructor(private componentA: ComponentA, private itemService: ItemService) {}

  setItems(items: Item[]): void {
    this.componentA.items = items;
  }

  onCategoryChange(category: string): void {
    this.itemService.getItemsByCategory(category).subscribe( items => {
      this.setItems( items.map( item => new Item().deserialize(item) ))
    }
  }
}

A: You get the items from an Observable of the "itemService".
I would inform the itemService about the filter, than it changes the data and all subscribers get informed.
With that, the service is the royal king over the data.
Component A (that shows the data) just shows data, whatever there comes. A dumb component is a good component.
Component B (the Filter) just informs the service about filtering-Events.
Two more or less dumb components and one service with a bit business (filtering) logic.
A construction like that could be easily covered by UnitTests.
warm regards

A: To acces this data i gave to componentB a reference of componentA.
<componentB [componentA]='compA'></componentB>
<componentA #compA></componentA>

and
// componentB
...
@Input() componentA: ComponentA;
...


text:
Q: Website URL only displays domain name and not the subpages When I access my website at www.example.com, I receive the correct page.  When I click on a link that accesses www.example.com/somepage.php, the server loads the new page correctly, but the URL bar still says www.example.com.  In addition, the web pages do not show the <title> specified in the HTML.
Could this have something to do with my using a URL Frame instead of a URL redirect through Namecheap?

A: You probably just linked the domain to your website host. If you have a decent host you should be able to park the domain name in your cpanel. If you will tell me your host I will give you more information.
NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot /www/docs/dummy-host.example.com
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog @rel_logfiledir@/dummy-host.example.com-error_log
    CustomLog @rel_logfiledir@/dummy-host.example.com-access_log common
</VirtualHost>


text:
Q: Removing Saved Reports from Interactive Grid in Oracle APEX 5.1 Is there any way I can remove the saved Reports drop down from an Interactive Grid?

I have tried adding this JavaScript code, but this leads to removal of Edit and Save buttons as well.
function(options) {
    var toolbarData = $.apex.interactiveGrid.copyDefaultToolbar();
    options.toolbar = toolbarData;
    options.toolbar.savedReports = false;
    return options;
}

I'm using Oracle APEX 5.1, and unfortunately can't upgrade to newer versions of Oracle APEX.

A: This shows up if you have saved reports. So just remove the non primary reports.
If you select the report and then go under Actions-Reports-Delete report.
That should remove the currently selected report. If there are no extra reports, only the primary one, then this shouldnt show up.
If you really only just want to hide this one field. Play around in the console and once you have it set you can have the code run sometime after load, maybe add in a wait or something so you can be sure the IG has already loaded.
I did the following(emp is the IG static ID):
var ig$ = apex.region("emp").widget();
var temp = ig$.interactiveGrid("getToolbar")[0]
temp.children[0].children[1].hidden = true

If you play around in the console with this you will see what is selected each time as you go a layer deeper. Then finaly we get just to the select list of the Reports, we get its property hidden which is false by default, we change it to true.
So now its hidden.
This methodology works for damn near everything. In the console you find a way to select the region or something inside it that includes whatever it is you want. Then go deeper and deeper until you are only selecting the specific thing you want. Then you can hide it, change it, get its value, id,...


text:
Q: Личные сообщения Как организовать у себя на сайте обмен личными сообщениями между пользователями.
A: В MySQL таблице присваивать одному столбцу "id от кого", второму "id кому".
При запросе пользователем MySQL сделать ограничения

Where IdTo = 'id'

Дополнено.
Допустим У нас есть таблица 'MyTable'
'ID', 'FromID', 'ToID', 'Message' - поля таблицы

P.S.: Таблицу я думаю произвольно можно заполнить самому.
Я - пользователь вашего сайта. Мой id = 569163357.
$MyID = '596163357';

Чтобы посмотреть все сообщения которые мне присылали:

$conn = mysql_connect($SQL_Server, $SQL_Login, $SQL_Pass) or die ("Connection failed!");
mysql_select_db ($SQL_DataBase, $conn) or die("DATABase not found");

$query = "SELECT * FROM `MyTable` WHERE ( ToID = $MyID )";
$result = mysql_query($query, $conn);

Чтобы посмотреть все сообщения которые мне присылал пользователь 560969357:

$FromUser = '560969357';
$conn = mysql_connect($SQL_Server, $SQL_Login, $SQL_Pass) or die ("Connection failed!");
mysql_select_db ($SQL_DataBase, $conn) or die("DATABase not found");

$query = "SELECT * FROM `MyTable` WHERE ( ToID = $MyID , FromID = $FromUser )";
$result = mysql_query($query, $conn);


text:
Q: Delete an object within an outer object not working Currently trying to delete an object within another object using the delete keyword as I've seen all around the web. The object I'm using is similar to the one below:
object = { NAME: {hello: 3838383, goodbye: 3474737}, NAME2: {hello: 3838383, goodbye: 3474737} }

Trying:
delete object.NAME

But I continually get: Cannot delete property 'NAME' of [object Object]. Any ideas?

A: It sounds like NAME is a non-configurable property. That means you can't delete it I'm afraid, as deleting (removing) a property counts as "configuring" it (as does changing the configurable flag on the property).
You can see what the configuration of the property is by using Object.getOwnPropertyDescriptor. In your case it probably will either not show a configurable property at all (because false is the default) or more likely it'll show configurable: false.
Here's an example which shows using getOwnPropertyDescriptor and demonstrates the error you're getting:

"use strict";
const object = { };
Object.defineProperty(object, "NAME", {
    value: {hello: 3838383, goodbye: 3474737},
    configurable: false,
    writable: true
});
console.log(Object.getOwnPropertyDescriptor(object, "NAME"));
delete object.NAME;

If the property is writable, you can assign some other value to itm, such as null or undefined:
object.NAME = null;

But if it's also non-writable, you can't do that, either.
As a final resort, you could create a new object and only copy the properties to it that you want, and assign that new object to the variable or property you're using to refer to the object. For instance:
object = Object.fromEntries(
    Object.entries(object)
      .filter(([key]) => key !== "NAME")
);

Live Example:

"use strict";
let object = {
    NAME2: {hello: 3838383, goodbye: 3474737}
};
Object.defineProperty(object, "NAME", {
    value: {hello: 3838383, goodbye: 3474737},
    configurable: false, // Just here for emphasis, false is the default
    writable: false      // same
});
console.log(Object.getOwnPropertyDescriptor(object, "NAME"));

// Can't do this: delete object.NAME;
object = Object.fromEntries(
    Object.entries(object)
      .filter(([key]) => key !== "NAME")
);
console.log(object);
.as-console-wrapper {
    max-height: 100% !important;
}


text:
Q: Update UI using IntentService with ActivityRecognition I am using the new APIs for locations and trying the ActivityRecognition. I used the code base that its on the Google Developers Training and everything went just fine until I wanted to update the UI. (I'm aware that you cannot update the UI directly on a service and that's why I'm using a handler/interface/something.)
What I tried:
Using an interface, but this was useless since I didn't find a way to get the Activity context from the IntentService.
Also tried passing a handler to the IntentService for it to send a message with the action but for some reason whenever it reaches the call to this:
 // If the intent contains an update
    if (ActivityRecognitionResult.hasResult(intent)) {

this just returns false since I'm passing the messenger with the handler. If I remove the line that add the extra containing the message it works just fine but I cannot update my UI.
I tried removing the extra before starting the service but no success. Any Ideas how should I fix this?
These are the codes I have:
Activity:
public class MainActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener {

public static final int MILLISECONDS_PER_SECOND = 1000;
public static final int DETECTION_INTERVAL_SECONDS = 20;
public static final int DETECTION_INTERVAL_MILLISECONDS = MILLISECONDS_PER_SECOND * DETECTION_INTERVAL_SECONDS;

private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private PendingIntent mActivityRecognitionPendingIntent;
// Store the current activity recognition client
private ActivityRecognitionClient mActivityRecognitionClient;
private Context mContext;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private static final String TAG = "MainActivity";
public static final String KEY_ACTION = "user_action";

public enum REQUEST_TYPE {START, STOP}
private REQUEST_TYPE mRequestType;
private TextView tvAction;

//FIXME I'm aware of this potential leak
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Bundle reply = msg.getData();
        final String userAction = reply.getString(KEY_ACTION);
        tvAction.setText("You are now: "+userAction);
        // do whatever with the bundle here
    }
};

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

    tvAction = (TextView)findViewById(R.id.tv_action);
    // Start with the request flag set to false
    mInProgress = false;

    mActivityRecognitionClient =
        new ActivityRecognitionClient(mContext, this, this);

    Intent intent = new Intent(
            mContext, ActivityRecognitionIntentService.class);
            //putting this will make return false.
    intent.putExtra("messenger", new Messenger(handler));

    mActivityRecognitionPendingIntent =
        PendingIntent.getService(mContext, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);
}

private void startUpdates() {

    mRequestType = REQUEST_TYPE.START;

    // Check for Google Play services

    if (!servicesConnected()) {
        return;
    }
    // If a request is not already underway
    if (!mInProgress) {
        // Indicate that a request is in progress
        mInProgress = true;
        // Request a connection to Location Services
        mActivityRecognitionClient.connect();
    //
    }
}

private void stopUpdates() {
    // Set the request type to STOP
    mRequestType = REQUEST_TYPE.STOP;
    /*
     * Test for Google Play services after setting the request type.
     * If Google Play services isn't present, the request can be
     * restarted.
     */
    if (!servicesConnected()) {
        return;
    }
    // If a request is not already underway
    if (!mInProgress) {
        // Indicate that a request is in progress
        mInProgress = true;
        // Request a connection to Location Services
        mActivityRecognitionClient.connect();
    //
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {
    case CONNECTION_FAILURE_RESOLUTION_REQUEST:
        /*
         * If the result code is Activity.RESULT_OK, try to connect again
         */
        switch (resultCode) {
        case Activity.RESULT_OK:
            /*
             * Try the request again
             */
            break;
        }

    }
}

private boolean servicesConnected() {
    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Activity Recognition", "Google Play services is available.");
        // Continue
        return true;
        // Google Play services was not available for some reason
    } else {
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);
            // Show the error dialog in the DialogFragment
            errorFragment.show(getSupportFragmentManager(), "Activity Recognition");
        }
        return false;
    }
}

// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    // Turn off the request flag
    mInProgress = false;
    /*
     * If the error has a resolution, start a Google Play services
     * activity to resolve it.
     */
    if (connectionResult.hasResolution()) {
        try {
            connectionResult.startResolutionForResult(
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    // If no resolution is available, display an error dialog
    } else {
        // Get the error code
        int errorCode = connectionResult.getErrorCode();
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                errorCode,
                this,
                CONNECTION_FAILURE_RESOLUTION_REQUEST);
        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment =
                    new ErrorDialogFragment();
            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);
            // Show the error dialog in the DialogFragment
            errorFragment.show(
                    getSupportFragmentManager(),
                    "Activity Recognition");
        }
    }
}

@Override
public void onConnected(Bundle arg0) {

    switch (mRequestType) {
    case START:
        /*
     * Request activity recognition updates using the preset
     * detection interval and PendingIntent. This call is
     * synchronous.
     */
    mActivityRecognitionClient.requestActivityUpdates(
            DETECTION_INTERVAL_MILLISECONDS,
            mActivityRecognitionPendingIntent);
        break;
    case STOP :
        mActivityRecognitionClient.removeActivityUpdates(
                mActivityRecognitionPendingIntent);
        break;

    default :
        Log.e(TAG, "Unknown request type in onConnected().");
        break;
    }

    /*
     * Since the preceding call is synchronous, turn off the
     * in progress flag and disconnect the client
     */
    mInProgress = false;
    mActivityRecognitionClient.disconnect();
}

@Override
public void onDisconnected() {
    // Turn off the request flag
    mInProgress = false;
    // Delete the client
    mActivityRecognitionClient = null;
}

@Override
protected void onPause() {
    super.onPause();
    stopUpdates();
}

@Override
protected void onResume() {
    super.onResume();
    startUpdates();
}

@Override
protected void onStop() {
    super.onStop();
    stopUpdates();
}

}

IntentService
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;

public class ActivityRecognitionIntentService extends IntentService {

    // Formats the timestamp in the log
    private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSSZ";

    private static final String TAG = "ActivityRecognitionIntentService";

    private static final String SHARED_PREFERENCES = "ActivityRecognition";

    private static final String KEY_PREVIOUS_ACTIVITY_TYPE = "KEY_PREVIOUS_ACTIVITY_TYPE";

    // A date formatter
    private SimpleDateFormat mDateFormat;

    // Store the app's shared preferences repository
    private SharedPreferences mPrefs;
    protected Messenger messenger;

    public ActivityRecognitionIntentService() {
        // Set the label for the service's background thread
        super("ActivityRecognitionIntentService");

    }

    public ActivityRecognitionIntentService(String name) {
        super(name);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Bundle extras = intent.getExtras();
        messenger = (Messenger) extras.get("messenger");
        intent.removeExtra("messenger");
        super.onStart(intent, startId);
    }

    /**
     * Called when a new activity detection update is available.
     */
    @Override
    protected void onHandleIntent(Intent intent) {

        // Get a handle to the repository
        Context mContext = getApplicationContext();

        mPrefs = mContext.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);

        // Get a date formatter, and catch errors in the returned timestamp
        try {
            mDateFormat = (SimpleDateFormat) DateFormat.getDateTimeInstance();
        } catch (Exception e) {
            Log.e(TAG, getString(R.string.date_format_error));
        }

        // Format the timestamp according to the pattern, then localize the
        // pattern
        mDateFormat.applyPattern(DATE_FORMAT_PATTERN);
        mDateFormat.applyLocalizedPattern(mDateFormat.toLocalizedPattern());

        // If the intent contains an update
        if (ActivityRecognitionResult.hasResult(intent)) {

            // Get the update
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

            // Get the most probable activity from the list of activities in the
            // update
            DetectedActivity mostProbableActivity = result.getMostProbableActivity();

            // Get the confidence percentage for the most probable activity
            int confidence = mostProbableActivity.getConfidence();

            // Get the type of activity
            int activityType = mostProbableActivity.getType();

            // Check to see if the repository contains a previous activity
            if (!mPrefs.contains(KEY_PREVIOUS_ACTIVITY_TYPE)) {

                // This is the first type an activity has been detected. Store
                // the type
                Editor editor = mPrefs.edit();
                editor.putInt(KEY_PREVIOUS_ACTIVITY_TYPE, activityType);
                editor.commit();

                // If the repository contains a type
            } else if (
                // The confidence level for the current activity is > 50%
                    (confidence >= 50)) {

                // Notify the user
                final String userAction = getNameFromType(activityType);
                sendNotification(userAction);

                if (messenger != null) {
                    Message msg = Message.obtain();
                    Bundle data = new Bundle();
                        data.putString(MainActivity.KEY_ACTION, userAction);
                    msg.setData(data); //put the data here
                    try {
                        messenger.send(msg);
                    } catch (RemoteException e) {
                            Log.i("error", "error");
                    }
                }
            }
        }
    }

    /**
     * Post a notification to the user. The notification prompts the user to
     * click it to open the device's GPS settings
     */
    private void sendNotification(String type) {

        // Create a notification builder that's compatible with platforms >=
        // version 4
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());

        // Set the title, text, and icon
        builder.setContentTitle(getString(R.string.app_name)).setContentText(type)// getString(R.string.turn_on_GPS))
                .setSmallIcon(R.drawable.ic_launcher)

                // Get the Intent that starts the Location settings panel
                .setContentIntent(getContentIntent());

        // Get an instance of the Notification Manager
        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Build the notification and post it
        notifyManager.notify(0, builder.build());
    }

    /**
     * Get a content Intent for the notification
     *
     * @return A PendingIntent that starts the device's Location Settings panel.
     */
    private PendingIntent getContentIntent() {

        // Set the Intent action to open Location Settings
        Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

        // Create a PendingIntent to start an Activity
        return PendingIntent.getActivity(getApplicationContext(), 0, gpsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    /**
     * Map detected activity types to strings
     *
     * @param activityType
     *            The detected activity type
     * @return A user-readable name for the type
     */
    private String getNameFromType(int activityType) {
        switch (activityType) {
        case DetectedActivity.IN_VEHICLE:
            return "in_vehicle";
        case DetectedActivity.ON_BICYCLE:
            return "on_bicycle";
        case DetectedActivity.ON_FOOT:
            return "on_foot";
        case DetectedActivity.STILL:
            return "still";
        case DetectedActivity.UNKNOWN:
            return "unknown";
        case DetectedActivity.TILTING:
            return "tilting";
        }
        return "unknown";
    }
}

A: IntentServices are not allowed to update UI, since they are designed to run background tasks.
You should design your service interface based on a notification instead, that when clicked can open an app activity to show detailed info about the service status.


text:
Q: How to connect appsheet to oracle autonomous database always free Appsheet in principle gives you the option to connect to an oracle database in the cloud, but it only lets you set the parameters of server name, database name, username and password. I tried a lot of options but it always ends up giving me:
Failed to establish connection. Error: ORA-12537: Network Session: End of file
If anyone knows where the problem comes from, I will thank them.

A: That won't work for Autonomous.
Autonomous is secured with a Wallet. You must be able to provide it as part of your connection string. Specifically for SSL, you need to be able to define ssl_server_cert_dn in your JDBC or TNS / EZConnect string.


text:
Q: Using predict.lm based on a model.matrix with different contrasts in R The aim is to predict new observations based on a multiple regression model.
The model includes two factors ("ec" with effect coding, "dc" with dummy coding) and a numeric variable ("num") plus an interaction term of "ec" and "num".
However, the predict.lm function based on new data fails.
# Dependent variable

y <- rnorm(12, 50, 10)

# Independent variables

# Dummy coding

dc <- factor(x=c("Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel", "Schlecht", "Gut", "Mittel"))

contrasts(dc) <- contr.treatment(3, 1)

# Effect coding

ec <- factor(x=c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"))

contrasts(ec) <- contr.sum(4)

num <- rnorm(12, 10, 2)

# Design matrix

df <- data.frame(dc = dc, ec = ec, num = num)

lm_dm <- model.matrix(~ 1 + ec + dc * num, df)

lm <- lm(y ~ 0 + lm_dm)

# prediction

newdata <- data.frame(dc = c("Schlecht", "Gut", "Gut"), ec = c("C", "D", "B"), num = c(9, 8, 12))

predict.lm(lm, newdata)

How can I use the estimated model to conduct a new prediction?

A: The issue is that the model is estimated using an exterior matrix rather than with the data argument. Instead we may do
mod <- lm(y ~ 1 + ec + dc * num, data = df)
predict.lm(mod, newdata)
#        1        2        3
# 24.19016 71.26768 59.50670

Sticking to not using this is complicated. For instance, the variables in your version of mod have names lm_dmec1, lm_dmdc3, which we would need to match. Further, in the process of supplying lm_dm as a whole we lose information that ec and dc are factors; for this reason we cannot use dc and ec as factors in your newdata; instead we must have dummy variables for all the levels. Thus, the best alternative seems to be to perform the prediction manually:
model.matrix(~ 1 + ec + dc * num, newdata) %*% coef(mod)
#       [,1]
# 1 57.08853
# 2 31.90847
# 3 47.81049


text:
Q: C++ - detecting dead sockets I have a server application written in C++. When a client connects, it creates a new thread for him. In that thread there is a BLOCKING reading from a socket. Because there is a possibility for a client to accidentally disconnect and left behind a thread still hanging on the read function, there is a thread that checks if the sockets are still alive by sending "heartbeat messages". The message consists of 1 character and is "ignored" by the client (it is not processed like other messages). The write looks like this:
write(fd, ";", 1);

It works fine, but is it really necessary to send a random character through the socket? I tried to send an empty message ("" with length 0), but it didn't work. Is there any better way to solve this socket checking?
Edit:
I'm using BSD sockets (TCP).

A: I'm assuming when you say, "socket, you mean a TCP network socket.
If that's true, then the TCP protocol gives you a keepalive option that you would need to ask the OS to use.
I think this StackOverflow answer gets at what you would need to do, assuming a BSDish socket library.

A: In my experience, using heartbeat messages on TCP (and checking for responses, e.g. NOP/NOP-ACK) is the easiest way to get reliable and timely indication of connectivity at the application layer.  The network layer can do some interesting things but getting notification in your application can be tricky.
If you can switch to UDP, you'll have more control and flexibility at the application layer, and probably reduced traffic overall since you can customize the communications, but you'll need to handle reliability, packet ordering, etc. yourself.

A: You can set connection KEEPALIVE. You may have interests in this link: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
It is ok you create a thread for each new coming requests if it is only toy. In most of time, i use poll, that is non-blocking io, for performance improvement.


text:
Q: remove duplicate values inside an array I am returning an array of result with a question and few answers of that question. Form some reason the answers are being duplicated. I am trying to filter the answers on $a variable and it's working as it should.
When I try to filter the whole array on $result variable it doesn't do the job.
How to fit the $array_map function that I separated down to filter inside the array just $result['answers'] part?
 $questions = $this->getQuestionRepository()->findBy([
   'user' => $user
 ]);

 $result = [];
 foreach ($questions as $question) {
   $result['question'] = $question->getQuestion();
   $result['answers'][] = $question->getAnswer();
 }

 return $result;


text:
Q: How to pass the list of integers inside count in entity framework I have IQueryable query with filters.
 IQueryable<User> usersQuery = Context.Users;

I need to pass list of integers instead of single integer value.
usersQuery = usersQuery.Where(u => u.UsersHRs.Count(um => um.Id == 1233 ) > 0);

A: Sounds like you want something like this:
var ints = new []{1,2,3}; // somehow fill ints
usersQuery = usersQuery.Where(u => u.UsersHRs.Where(um => ints.Contains(um.Id)).Count() > 0);

A: update your query to
var ListOfIds = //list of integers
usersQuery = usersQuery.Where(u => u.UsersHRs.Count(um => ListOfIds.Contains(um.Id)) > 0);


text:
Q: Element appending with and without scroll varies I have 2 button, one in top another in the bottom. when I click the top button it works fine. when i scroll down to bottom button and click the button again ( same function ) it appends the element with some where. I am calculating the top position from absolute way. getting the relation ship with body.
so how to handle this kind of scenario?
Live demo
Js code :
const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();
  console.log(parentPos)
  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + "px";
}

HTML:

Hello Plunker!

some div info goes here
      <button onclick="addElement()">Click Me </button> //works fine.

    <button onclick="addElement()">Click Me </button> //it's not. after scroll down!!

the second button appends the element some where. what is the correct way to calculation do we have to do here?
Thanks in advance.

const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();

  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + "px";
}
.mydiv{
  border: 1px solid green;
  height: 600px;
}

Hello Plunker!

some div info goes here
      <button onclick="addElement()">Click Me </button>

    <button onclick="addElement()">Click Me </button>

A: If you want absolute positioning, you need to take scrolling into account. You can do that with window.scrollY. Notice the change at the last line of addElement:

const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();

  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + window.scrollY + "px";
}
.mydiv{
  border: 1px solid green;
  height: 600px;
}

Hello Plunker!

some div info goes here
      <button onclick="addElement()">Click Me </button>

    <button onclick="addElement()">Click Me </button>


text:
Q: Cannot install dotnet-sdk2.1 on Ubuntu 16.04 server I was trying to install dotnet-sdk2.1.101 on my Ubuntu 16.04 server today but following error occured:
"dotnet-sdk-2.1.101 : Depends: aspnetcore-store-2.0.6 but it  but it is not going to be installed"
Steps taken: (followed instructions on microsoft website):

*

*wget -q https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb

*sudo dpkg -i packages-microsoft-prod.deb

*sudo apt-get install apt-transport-https

*sudo apt-get update

*sudo apt-get install dotnet-sdk-2.1

Any help is much appreciated :)

A: Following a guide on Upgrading to dotnet core 2.1.4 on Ubuntu 16.04 resolved this issue on my end:

First, Setup the package manager.
$ curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
$ sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
$ sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt/sources.list.d/dotnetdev.list'
$ sudo apt-get update
Next, Install .NET Core 2.x
$ sudo apt-get install dotnet-sdk-2.1.4

A: I have fixed my own issue following these below steps:

wget -q packages-microsoft-prod.deb https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update –y
sudo apt-get install dotnet-sdk-2.1.101

A: For me previous didn't help.
But for me worked the next:
wget http://ftp.us.debian.org/debian/pool/main/i/icu/libicu57_57.1-6+deb9u2_amd64.deb
sudo dpkg -i libicu57_57.1-6+deb9u2_amd64.deb

wget http://mirrors.kernel.org/ubuntu/pool/main/i/icu/libicu60_60.2-6ubuntu1_amd64.deb
sudo dpkg -i libicu60_60.2-6ubuntu1_amd64.deb

sudo apt-get install dotnet-sdk-2.1

I don't quite understand did I need 2 versions of libicu, but after 1st it required the 2nd one.


text:
Q: Azure B2C Bearer error="invalid_token", error_description="The signature key was not found" I took the Microsoft sample  which is using client_credentials flow
https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi
and modified it using my values  exactly as the guide says  but i still get the following error when i try to access my API
Bearer error="invalid_token", error_description="The signature key was not found"
Any ideas what might be wrong here ?

A: If you want to do some troubleshooting, you can drop the access token JWT into jsonwebtoken.io 232 and get the kid field from the jwt header. After you get the kid, you can check your authorization server's keys by going to
https://[my okta org].com/oauth2/default/v1/keys
This will give you the list of public keys by ID. Hope this information helps you troubleshoot. Let me know if you still have problems!
Check a couple things for me:
1:  Are you setting the issuer in your widget / auth js?
2.  If you are, is the issuer the same as your default authorization server?
3.  Double check that the [my okta url] is correct

A: I solved it by using  the console application sample that Microsoft provided together with the Web API sample that microsoft provided as well , together they both work , i should't have tried to write my own code , its very tricky if you miss a tiny piece . One thing i want to add , Microsoft says using api://GUID format as a scope , that seems wrong , or did not work with me ,what worked is full url of the exposed API + /.default example
https://mydomain.onmicrosoft.com/myapiname , that works just fine .


text:
Q: "firebase serve" in firebase functions is not running the latest changes I am playing with firebase functions. Works fine when deploying to firebase server using command firebase deploy --only functions. However, I would like to test my functions locally before deploy to server of course. What I see running firebase serve is that the functions "deployed" locally have not the latest changes I did in indext.ts - are running the last builded version, which are in index.js.
My question is, How do I manual build my firebase functions project to test them locally with latest changes?
Should firebase serve autobuild the project before deploy it locally? For me, it sounds like a bug.

A: firebase serve doesn't seem to be running npm build. But if you look inside functions/package.json, you can see there is already a serve script there that performs npm run build && firebase serve --only functions. So if you just do:
cd functions
npm run serve

You can build and serve without having to do two separate commands.

A: If you are looking for hot reloading i just did it like below:
"start:emulators": "firebase emulators:start --only functions",
"ts:watch": "tsc --watch",
"dev": "concurrently --kill-others \"npm run start:emulators\" \"npm run ts:watch\"",

It will run both firebase and ts watch in parallel, which will help your development speed

A: If you want to reload the changes to your TypeScript when running firebase serve or firebase functions:shell, all you have to do is build your project again using npm script that was created for you when you initialized the project (see package.json):
cd functions
npm run build

This will transpile your TypeScript to JavaScript, and the changes to the JavaScript will get picked up by the emulator automatically.
Also, if you are a more advanced TypeScript user, you can run tsc --watch to automatically compile TS to JS when source files change on disk.  You can read more about that in this blog.

A: I don't think you can just switch between Javascript and Typescript in an initialized project. The setup for Typescript is a bit different than Javascript. You will need to migrate your Javascript project to Typescript.
To migrate your project from JS to TS follow this firebase-functions documentation on :
Migrating an existing JavaScript Cloud Functions project
Typescript project setup:

A: Go to functions folder, open package.json and add new key:   "hotReload": "tsc --watch"
next, run npm run hotReload in same functions folder and keep the terminal open. This will update *.js whenever any changes to *.ts file. Remember that cloud functions run from *.js file not *.ts file. Hence, *.ts file needs to compiled to *.js first.
Next, open new terminal, go to main project folder and run firebase serve (to parallely run hosting+functions) or firebase serve --only functions

A: Just use this command when you are using first time npm serve command
firebase emulators:start


text:
Q: Access last command of history within a function I'm trying to create a function that will echo the previous to last command from the current terminal. This is the expected output (here I call the desired function f):
$ history 1
history 1
$ f
history 1

Side question: Where does history(1) saves the current terminal's history. I know that when the terminal session ends history is typically saved in $HISTFILE (which is set to ~/.bash_history in my case). But I'd like to know where history(1) keeps the history of the currently running terminal.

A: Found a solution:
f()(echo $(history 2 | head -n1 | cut -d' ' -f2-))

or using fc as suggested by G-Man:
f()(fc -ln -1)

test:
$ echo 123*
123*
$ f
echo 123*


text:
Q: How to use %?% in sqlite prepared statements for Android Currently my query look like this
Cursor c = db.query(CONTENT_TABLE, new String[]{"content"}, "content like %?%", new String[]{keyword}, null, null, null);

What i want to do is write a prepared statement, surrounded with the % sign. This is my Logcat
android.database.sqlite.SQLiteException: near "%": syntax error (code 1): , while compiling: SELECT content FROM `const` WHERE content like %?%

How do i do this properly?

A: i used
Cursor c = db.query(CONTENT_TABLE, null, "content like ?", new String[]{"%" + keyword + "%"}, null, null, null);

and it worked fine


text:
Q: I wanna know how this comparator works
The diagram that is shown in the figure compares if the voltage supplied is higher than the reference voltage or not and the. Gives the output, high or low, accordingly... What I don't understand is how it compares? How does it know if the voltage is higher or not

A: At its heart a comparator is the same as an opamp: You have a differential amplifier as input stage, a differential to single ended conversion, an intermediate amplifier stage and an output amplifier stage. What makes the comparator different are the following things (incomplete list in no particular order):

*

*The input stage is designed for large differential voltages. Most opamps assume that inverting and non-inverting input have almost the same voltage and are optimized for this, the comparator has to work correctly, without having undue input currents, even if the differential input range spans the whole power supply range.

*The output stage can have a different, digital power supply voltage than the input stage.

*The output stage is optimized for 0/1-output instead of a variable voltage output.

*There is a small hysteresis built-in (usually by having some slight positive feedback to the inputs) to ensure the comparator does not oscillate, even under slowly varying inputs.

*As the output goes only to 0 or 1, care has to be taken, that this doesn't cause saturation within the comparator, which would cause slower reaction time.


text:
Q: Where should Tableau questions that don't involve writing code be asked? Until earlier today, Stack Overflow had quite a collection of [tableau] questions, a large number of which were off-topic there.  Now the tag has been renamed to [tableau-api] to emphasize that only programming questions about Tableau belong on Stack Overflow:

Questions about using Tableau are off-topic here. It is a data visualization tool, and unrelated to programming.

Where should these sorts of non-programming Tableau questions (one example: "Changing the X axis header title") be posted?

A: I think the answer is Data Science.SE, which has 100 posts containing "tableau" and a [tableau] tag with 31 questions.  Additionally, a post on that site's meta concludes that visualization (what Tableau does) is an integral part of data science.
Other places I looked, but don't seem correct:

*

*WebApps.SE has no positively voted Tableau questions.

*Stats.SE has a few questions involving tableau, but it's mostly incidental to the question in almost all of them.


text:
Q: Is there a bijection there? Let $X$ be a normed vector space and $T$ a subset of $X^{\prime} = \mathcal{L}(X,\mathbb{R})$. Then define the set:
$$^{\circ}T\ :=\ \{\;x\in X\ :\ F(x)=0,\ \forall\ F\in T\;\}.$$
(When) Is possible the get a bijection $G\in\mathcal{L}(T,\;^{\circ}T)$? Where
$$\mathcal{L}(X,Y)\ =\ \{F:X\rightarrow Y\ \mbox{ such that }
 F \mbox{ is linear and bounded}\}.$$
Thanx so much in advance.


text:
Q: DialogFlow CX V3 - Upsert Entities (Batch Insert) I am looking for some advice on how I can upsert or replace existing user entity.
I tried couple of API's documented here and also here.
The entities are read from database and the plan is to keep them in sync with database values as a scheduled job.
Update: Code Snippet
   client_options = {"quota_project_id": gcp_default_project_id,
                      "api_endpoint": "us-central1-dialogflow.googleapis.com:443"}
   client = EntityTypesClient(credentials=credentials_det, client_options=client_options)

   entity_type = v3beta.EntityType()
   entity_type.display_name = entity_display_name
   entity_type.kind = "KIND_REGEXP"
   print(client_options)
   entity_type.entities = entity_json

   # Initialize request argument(s)
   request = v3beta.UpdateEntityTypeRequest(
       entity_type=entity_type,
   )
   print(request)
   response = client.update_entity_type(request=request)
   print(response)

entity_json is fetched from DB and created as JSON object as below.
        df = get_data.get_df_details(config_dir, entity_data_source, sql)

        username = df['username'].tolist()
        entity_json = []
        for each in username:
            each_entity_value = {}
            each_entity_value['value'] = each
            each_entity_value['synonyms'] = [each]
            entity_json.append(each_entity_value)

Here's the Trace
Traceback (most recent call last):
File "/Users/<some_dir>/df_ins_entities/df_ins_entities/ins_entity_val.py", line 116, in
ins_now(config_dir, input_entity_name, entity_data_source)
File "/Users/<some_dir>/df_ins_entities/df_ins_entities/ins_entity_val.py", line 96, in ins_now
response = client.update_entity_type(request=request)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py", line 902, in update_entity_type
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/api_core/gapic_v1/method.py", line 154, in call
return wrapped_func(args, **kwargs)
File "/Users/<some_dir>/df_ins_entities/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.InvalidArgument: 400 Resource name '' does not match 'projects//locations//agents//entityTypes/*'.
Process finished with exit code 1


text:
Q: Junit test - how to mock class private member of type of private interface? I wrote few junits, using some mocking techniques.
But stucked here:
public class Lookup {
    private LookupMethod lookupMethod;

    private interface LookupMethod {
        String lookup(String input);
    }

   public String treatString(@Nullable String input) {
       ...
       String lookupResult = lookupMethod.lookup(lookupInput);
       ...
   }
}

I'm unit testing the treatString() method and looking how to mock the lookupMethod.lookup() call in the treatString() method above.
I can't change Lookup class.
I'll appreciate a tip (example would be even better).

A: Basically, this class is super hard to test when you can't modify it.
Using the dark magic of PowerMock it should be possible to mock things by name, meaning that you provide a raw string denoting the method you want to override. See here how to do that.
But as said: that is basically dark magic. It means to add PowerMock to your dependencies. Which will invite others to use PowerMock in the future. Which carries the risk of people writing even more hard to test code. Because you know have a tool that allows you to test that stuff. Instead of writing easy to test code.
And of course: in case someone else changes that class, like renaming that method, then your test breaks.
And then, ask yourself: what is the point of testing a class you aren't supposed to change? What if you find a bug, will it stay in?!


text:
Q: Did I find the basis of a subset of $\mathscr{P}_4(\mathbb{F})$? I need to find the basis of a subspace of $\mathscr{P}_4(\mathbb{F})$, called $U$, where $U=\{p\epsilon\mathscr{P}_4(\mathbb{F})|\ p''(6)=0\}$.  After finding this basis I need to find another set, $W$, such that $\mathscr{P}_4(\mathbb{F}) = U\oplus W$.
I've reasoned that the basis of $U$ should be $\{1,\ x,\ (x-6)^3,\ (x-6)^4\}$, and $W$ should be $\{x^2\}$.
Is this a valid solution?

A: You have given a correct basis. One needs to give justification. This involves the following steps: (i) the proposed basis elements satisfy the condition on the second derivative, and therefore (ii) all linear combinations of them satisfy the condition.
Also (iii) the proposed basis is a linearly independent set.
Thus the subspace generated by the proposed basis is a subspace of $U$ and has dimension $4$. However, $U$ itself is a proper subspace of the full space, and therefore has dimension $\le 4$. It follows that the space generated by the proposed basis is all of $U$.
Your $W$ is essentially correct, it should be the space generated by $x^2$.


text:
Q: Thin/Sinatra config/paths problem I have Sinatra application which I want to use Thin webserver.
I made following configs:
config/config.ru:
require 'rubygems'

require 'sinatra'
require 'sinatra/session'

require 'haml'
require 'sass'

require 'myapp.rb'

Rack::Handler::Thin.run Sinatra::Application, :Port => 4567

config/thin.yaml:
---
environment: development
chdir: /home/proj/myapp
pid: tmp/thin.pid
rackup: config/config.ru
log: log/thin.log
max_conns: 1024
timeout: 30
max_persistent_conns: 512
daemonize: true

I am using thin start -C config/thin.yaml in /home/proj/myapp to start thin with my application
PROBLEM:
Errno::ENOENT at /
No such file or directory - /home/proj/myapp/config/views/login.haml

I don't understand why it tries to look views in /home/proj/myapp/config/views/login.haml, when it needs to look in /home/proj/myapp/views/login.haml
When I am launching just: ruby myapp.rb everything works fine

A: The last line in config.ru should be:
run Sinatra::Application


text:
Q: Need help with JS syntax I want to show/hide a div based on the value of a SP dropdown/choice column on form.
I have written below code to this which is not written correctly.
Can anyone help me with syntax to correct this?
$(document).ready(function(){
if $("#mydropdownid").change(function(){
        == ""){
            document.getElementById("Badge").style.display = 'none';
            document.getElementById("NoBadge").style.display = 'none';
}

if
    $("#mydropdownid").change(function(){
        == "CDS ID") {
            document.getElementById("NoBadge").style.display = 'block';
            document.getElementById("Badge").style.display = 'none';
}

if
    $("#mydropdownid").change(function(){
        == "CDS ID + Badge") {
            document.getElementById("Badge").style.display = 'block';
            document.getElementById("NoBadge").style.display = 'none';
    }
}

A: The problem there is that you are hooking up three different change event handlers inside if statements, and not actually getting the value of the drop-down.  You need to hook up the change event only once, and then once it has changed, check what the new value is:
$(document).ready(function () {
    // hook up the change event handler
    $("#mydropdownid").change(function () {

        // once the drop-down has changed, then you can check its value
        if ($(this).val() === "") {
            document.getElementById("Badge").style.display = 'none';
            document.getElementById("NoBadge").style.display = 'none';
        }

        if ($(this).val() === "CDS ID") {
            document.getElementById("NoBadge").style.display = 'block';
            document.getElementById("Badge").style.display = 'none';
        }

        if ($(this).val() === "CDS ID + Badge") {
            document.getElementById("Badge").style.display = 'block';
            document.getElementById("NoBadge").style.display = 'none';
        }
    }
}

Keep in mind that drop-downs can have a different value for the current selection behind the scenes than what is actually displayed as the text representation for that choice, so if you are not getting the results you expect using this code, you might need to replace all of the
$(this).val()

bits with
$(this).text()

A: It can be difficult getting ahold of the controls on the forms and getting rid of them all the way.  I have answered this question once before here.  This should work to hide based on your logic.  Use that code to do the removal.  Good Luck!


text:
Q: Does mysql or mariadb have the concept of SQL Server's "included columns" for indexes? In SQL Server you can create an index and have additional columns included on that index that can help performance in certain circumstances. Is that same ability available for mysql or mariadb under a different name, perhaps? I was unable to find anything using the term "included columns".

A: Looking at the MySQL Documentation, the glossary indicates this about Covering Indexes:

An index that includes all the columns retrieved by a query. Instead of using the index values as pointers to find the full table rows, the query returns values from the index structure, saving disk I/O. InnoDB can apply this optimization technique to more indexes than MyISAM can, because InnoDB secondary indexes also include the primary key columns. InnoDB cannot apply this technique for queries against tables modified by a transaction, until that transaction ends.

Any column index or composite index could act as a covering index, given the right query. Design your indexes and queries to take advantage of this optimization technique wherever possible.

The implication here is that there is no direct equivalent of an INCLUDE statement in MySQL, however if the index provides coverage of the columns involved in an index, it can, rather obviously, still be considered to be covering, much like an index with included columns in SQL Server would be.
MariaDB has the following in their documentation for covering indexes:

A "Covering" index is an index that contains all the columns in the SELECT. It is special in that the SELECT can be completed by looking only at the INDEX BTree. (Since InnoDB's PRIMARY KEY is clustered with the data, "covering" is of no benefit when considering at the PRIMARY KEY.)

Mini-cookbook:

*

*Gather the list of column(s) according to the "Algorithm", above.

*Add to the end of the list the rest of the columns seen in the SELECT, in any order.

Examples:

SELECT x FROM t WHERE y = 5; ⇒ INDEX(y,x) -- The algorithm said just INDEX(y)
SELECT x,z FROM t WHERE y = 5 AND q = 7; ⇒ INDEX(y,q,x,z) -- y and q in either order (Algorithm), then x and z in either order (covering).
SELECT x FROM t WHERE y > 5 AND q > 7; ⇒ INDEX(y,q,x) -- y or q first (that's as far as the Algorithm goes), then the other two fields afterwards.

The speedup you get might be minor, or it might be spectacular; it is hard to predict.
But...

*

*It is not wise to build an index with lots of columns. Let's cut it off at 5 (Rule of Thumb).

*Prefix indexes cannot 'cover', so don't use them anywhere in a 'covering' index.

*There are limits (3KB?) on how 'wide' an index can be, so "covering" may not be possible.

A: MySQL does not support included columns.
However, if you use the InnoDB storage engine (which is the default), all columns are physically included in the primary key. In other words, the primary key is the table. If you define the primary key as PRIMARY KEY (id) the rows will be physically ordered by id; but for all queries that use the primary key, the primary key will be a covering index.
The following query uses the primary key as a covered index:
SELECT * FROM tab WHERE pk = 10;

As Akina pointed out in a comment, InnoDB secondary indexes include a reference to the primary key. So if you index the email fiels, in the index you'll have all emails in order, and for each you'll have the corresponding id. So for each secondary index the primary key column(s) are included column(s).
The following query uses a secondary index as a covering index:
SELECT indexed_column, pk FROM tab WHERE indexed_column=100;

As a curiosity, I can also tell you that the TokuDB storage engine supports clustering indexes, which is just another name for included columns. Unfortunately TokuDB is not maintained anymore by its vendor, Percona.


text:
Q: Can RxJS be used in a pull-based way? The examples in the RxJS README seem to suggest we have to subscribe to a source. In other words: we wait for the source to send events. In that sense, sources seem to be push-based: the source decides when it creates new items.
This contrasts, however, with iterators, where strictly speaking new items need only be created when requested, i.e., when a call is made to next(). This is pull-based behavior, also known as lazy generation.
For instance, a stream could return all Wikipedia pages for prime numbers. The items are only generated when you ask for them, because generating all of them upfront is quite an investment, and maybe only 2 or 3 of them might be read anyway.
Can RxJS also have such pull-based behavior, so that new items are only generated when you ask for them?
The page on backpressure seems to indicate that this is not possible yet.

A: Short answer is no.
RxJS is designed for reactive applications so as you already mentioned if you need pull-based semantics you should be using an Iterator instead of an Observable. Observables are designed to be the push-based counterparts to the iterator, so they really occupy different spaces algorithmically speaking.
Obviously, I can't say this will never happen, because that is something the community will decide. But as far as I know 1) the semantics for this case just aren't that good and 2) this runs counter to the idea of reacting to data.
A pretty good synopsis can be found here. It is for Rx.Net but the concepts are similarly applicable to RxJS.

A: Controlled observable from the page you referenced can change a push observable to pull.
var controlled = source.controlled();

// this callback will only be invoked after controlled.request()
controlled.subscribe(n => {
  log("controlled: " + n);
  // do some work, then signal for next value
  setTimeout(() => controlled.request(1), 2500);
});

controlled.request(1);

A truly synchronous iterator is not possible, as it would block when the source was not emitting.
In the snippet below, the controlled subscriber only gets a single item when it signals, and it does not skip any values.

var output = document.getElementById("output");
var log = function(str) {
  output.value += "\n" + str;
  output.scrollTop = output.scrollHeight;
};

var source = Rx.Observable.timer(0, 1000);
source.subscribe(n => log("source: " + n));

var controlled = source.controlled();
// this callback will only be invoked after controlled.request()
controlled.subscribe(n => {
  log("controlled: " + n);
  // do some work, then signal for next value
  setTimeout(() => controlled.request(1), 2500);
});
controlled.request(1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.2/rx.all.js"></script>

<body>
  <textarea id="output" style="width:150px; height: 150px"></textarea>
</body>

A: I'm quite late to the party, but it's actually very simple to combine generators with observables. You can pull a value from a generator function by syncing it with a source observable:
const fib = fibonacci()
interval(500).pipe(
  map(() => fib.next())
)
  .subscribe(console.log)

Generator implementation for reference:
function* fibonacci() {
  let v1 = 1
  let v2 = 1
  while (true) {
    const res = v1
    v1 = v2
    v2 = v1 + res
    yield res
  }
}


text:
Q: How do you use `switch` in C# to conditionally branch based on only a type parameter? My context is that I'm building a simple factory method for creating instances of derived types of a given base type.  The factory method only takes a type parameter, i.e. doesn't have any arguments.  This is obviously possible with an if-else if construct:
public Vehicle Create<T>()
{
    if (typeof(T) == typeof(Car))
        return new Car(); // just an example; could be more complex logic.
    else if (typeof(T) == typeof(Truck))
        return new Truck(); // just an example; could be more complex logic.
    else
        throw new ArgumentException(
            $"The type {typeof(T).Name} is not known by this method.");
}

It's well-known by now how to use pattern matching in C# (as of C# 7.0) to branch based on the type of a variable but this doesn't work for a type parameter:
switch (T) { ... } // error: "'T' is a type, which is not valid in the given context"

or...
switch (typeof(T))
{
    case Car c: ...
    // err: "An expression of type 'Type' cannot be handled by a pattern of type 'Car'"
}

So I'd like to know if it's possible to use switch to achieve the same result?

Research: I'm surprised this hasn't been asked before, but I can't find it.  I found this post which has a name and a few answers that come pretty close but it's dealing with (numeric) value types and methods that have an argument of type T -- the generic type parameter.  Similarly, this post also uses an argument.

A: I know your question specifically asked about using the switch statement, but another alternative would be to create a dictionary of factories keyed on the type.
You should note that at this point, you are doing an operation similar to dependency injection.  You are asking for a Vehicle of type X and risking a run-time error if the Create method does not have the information needed to Create a Vehicle of type X.
public class Car : Vehicle { }
public class Truck : Vehicle { }

public abstract class Vehicle
{
    private static readonly IReadOnlyDictionary<Type, Func<Vehicle>> vehicleFactories = new Dictionary<Type, Func<Vehicle>>
    {
        { typeof(Car), () => new Car() },
        { typeof(Truck), () => new Truck() }
    };

    public static Vehicle Create<T>() where T : Vehicle, new()
    {
        if (vehicleFactories.TryGetValue(typeof(T), out var factory))
        {
            return factory();
        }
        else
        {
            throw new ArgumentException(
                $"The type {typeof(T).Name} is not known by this method.");
        }
    }
}

A: EDIT: Note that I'm not making any statement as to whether this is good or bad.  It's entirely to show that it's possible to do it.
This can be accomplished in C# 7.0 or later using a switch block with pattern matching and the when keyword:
public Vehicle Create<T>() where T : Vehicle
{
    switch (true)
    {
        case bool x when typeof(T) == typeof(Car): return new Car();
        case bool x when typeof(T) == typeof(Truck): return new Truck();
        default: throw new ArgumentException(
            $"The type {typeof(T).Name} is not known by this method.");
    }
}


text:
Q: how to properly shutdown instance of class that uses asio for event queuing In my project, I am extensively using boost asio to be able to uniformly queue non-uniform events to the modules in my application, using io_service.post() and strand.post()/dispatch().
In the main(), these modules are created and held in shared_ptrs until the program exits and they get deleted:
simplified main:
{
  [some initialization]

  boost::asio::io_service service;

  [create pool of worker threads that drive the io_service]

  {
    boost::shared_ptr<manager_a> a(new manager_a(service, foo));
    boost::shared_ptr<manager_b> b(new manager_b(service, bar, blah));
    ...

    [wait for signal to shutdown (SIGINT (release), cin.getc() (debug), or similar)]
  }

  [some shutdown (join thread pool)]
}

The "managers" (I don't know what to call them) derive from boost::enable_shared_from_this.
In their constructors, they may register callbacks with other modules:
manager_a::manager_a(boost::asio::io_service& service, module *m) :
  m_service(service),
  m_strand(service),
  m_module(m)
{
  // manager_a implements some callback interface
  // that "module" may call from another thread
  m_module->register(this);
}

In the destructor:
manager_a::~manager_a()
{
  m_module->unregister(this);
}

The manager implements the callback interface by posting a call through the strand:
void manager_a::on_module_cb(module_message m)
{
  // unsafe to do work here, because the callback is from an alien thread
  m_strand.dispatch(boost::bind(&manager_a::handle_module_message, shared_from_this(), m));
}
void manager_a::handle_module_message(module_message m)
{
  // safe to do work here, as we're serialized by the strand
}

Now the dilemma I'm in:
If "module" calls the callback immediately after the register(this) in the constructor, the shared_ptr in the main has not taken over the instance yet, and shared_from_this() in the callback function throws an exception. Same problem with the destructor - the shared_ptr has determined it had the last reference and when the destructor is called, if the callback gets called before the unregister(this), shared_from_this() throws.
The reason why shared_from_this() is needed is because queued function calls are stored in the io_service that hold a pointer to the manager instance, and that are independent from the manager's lifetime. I can give a raw this to the "module" because I can unregister with it before manager_a is destroyed, but the same is not true for queued function calls in the io_service, so a shared_from_this() is needed to keep the instance alive as long as there's some message posted. You can't cancel those either, and you can't blocking-wait in the destructor until all pending posts are delivered. Unfortunately as it is now, I can't even prevent new posts from being (tried to be) queued during the critical constructor/destructor phases.
Some ideas:

*

*Write start/stop functions and do register/unregister there. E.g. create a factory function like this:
boost::shared_ptr<manager_a> manager_a::create(io_service& s, module *m)
{
  boost::shared_ptr<manager_a> p(new manager_a(s, m));
  p->start();
  return p;
}

This only works for the creation, not for destruction. Giving a custom deleter to the shared_ptr, that calls stop() before delete, doesn't help, as it is too late anyhow.

*Have the main() call start() and stop(), but I don't see how main() could do this in an exception-safe way for the stop() call, i.e. be sure to call stop() even if some later code throws. Having another RAII class just to call stop() seems awkward.

*Just wrap the strand.dispatch() call in a try/catch and ignore the exception. This is an indication that destruction is in progress (or construction not finished), so just ignore the callback. This feels hackish, and I'd rather not do that. If I had access to the embedded weak_ptr in the enable_shared_from_this base class, I could call the non-throwing lock() and check the return value to see if it is valid. But shared_from_this does not give you access, and it still would seem hackish anyway... Besides, missing a callback during construction is not helpful, even If I could work around that.

*Let manager_a have it's own io_service and a thread driving it. Then, in the destructor, I can stop the service and join the thread and be sure there are no pending posts in the io_service. There's also no need for shared_from_this() anymore, or for a strand. This would work, I guess, but then, having a thread pool in the main() for all managers becomes pointless, and I'd have much more threads in my application than seems sensible. There are enough threads already in other modules that don't use an asio io_service...

A: It's not clear from your question, but if all your manager objects are created at start-up and deleted on exit, then the solution to your problem is to create the managers before you start the IO threads, and stop the IO threads before you delete the managers. That will stop you getting callbacks when you don't want them.


text:
Q: To push the checkbox values to the present array list values using javascript i wanted to push the list of values selected from the checkbox to the text box that already has the array list of values......i mean when the data is been retrieved the textbox has its value (the retrieved value  with the checkbox being checked)......when i select the new checkbox value and push that to the retrieved value.....the textbox only displays the newly selected checkbox values(the old checkbox values get removed)..........i want the textbox to display the old retrieved values with the currently selected checkbox values with checkbox being checked

var pc = [];

function getPc(myname1) {

 var text1 = myname1;

 if (document.getElementById(myname1).checked){

  pc.push(myname1);

 }
 else
  {
     pc.splice( pc.indexOf(myname1), 1 );

  }
       console.log(pc);
 document.getElementById("pca").value = pc.join("/");

 }

Product Categories

             <input type="text" class="form-control" id="pca" name="pc" form="form1" onclick="getPc()" value="myname1/check2/check3">

<input type="checkbox" name="myname1" id="myname1" onclick="getPc(this.id)"  checked>
<input type="checkbox" name="check2" id="check2" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check3" id="check3" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check4" id="check4" onclick="getPc(this.id)"  >
<input type="checkbox" name="check5" id="check5" onclick="getPc(this.id)" >
<input type="checkbox" name="check6" id="check6" onclick="getPc(this.id)" >

A: When the page loads check which checkboxes are checked and add them to the array.

var pc = [];

var checkboxes = document.getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].type == "checkbox") {
        if (checkboxes[i].checked) {
            getPc(checkboxes[i].id);
        }
    }
}

function getPc(myname1) {
    var text1 = myname1;
    if (document.getElementById(myname1).checked) {
        pc.push(myname1);
    } else {
        pc.splice(pc.indexOf(myname1), 1);
    }
    console.log(pc);
    document.getElementById("pca").value = pc.join("/");
}

Product Categories

             <input type="text" class="form-control" id="pca" name="pc" form="form1" onclick="getPc()" value="myname1/check2/check3">

<input type="checkbox" name="myname1" id="myname1" onclick="getPc(this.id)"  checked>
<input type="checkbox" name="check2" id="check2" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check3" id="check3" onclick="getPc(this.id)" checked>
<input type="checkbox" name="check4" id="check4" onclick="getPc(this.id)"  >
<input type="checkbox" name="check5" id="check5" onclick="getPc(this.id)" >
<input type="checkbox" name="check6" id="check6" onclick="getPc(this.id)" >


text:
Q: How to open a new file in the current directory with gvim on Windows? If I'm working on a file located on e.g. ~\myprojects\testproject\hello.txt and then want to open a new file in the same directory e.g. todo.txt (located on ~\myprojects\testproject\todo.txt), how can I do that efficiently with gvim on Windows?
Today I have to type this command, maybe using tab-completion for the paths:
:e ~\myprojects\testproject\todo.txt

Is there any shorter command e.g:
:e .\todo.txt

in gvim on Windows?
If I use .\todo.txt, that file will be located on C:\Windows\system32, that's not even my home directory. Is there any setting to specify my home directory as default instead? or any other diectory?

A: The following should work, provided your current dir is where the file is:
:e todo.txt

For the second question I don't know a good answer. You can of course do
:cd ~

every time you start up, or you could edit your vimrc to do that. It's a hack and not a good solution.
There's also 'autochdir' if you want to cd to the file every time. I found it here: http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file
In your vimrc you would put in this line:
set autochdir

Edit2: add answer to second question

A: I have the following in my vimrc:
map <Leader>e :e <C-R>=expand("%:p:h") . "/" <CR>

This opens the command line, enters the 'e'  command and pre-populates the file argument with the path to the file in the currently active buffer. The  key is mapped to the backslash key by default.

A: For completeness, if you are editing a file in that directory at the moment, set autochdir in vim.rc should be enough.
If you are however in the vim file explorer (netrw)
:e .
%filename

you will have to precede the creation of a new file with %.
For more information: :help netrw-intro-browse.


text:
Q: Animation After Background Thread Complete (iOS / Swift) I'm looking to animate a few things when a long process (parsing) is complete. My barebones code currently looks like such:
func run_on_background_thread(code: () -> Void)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), code)
}

func run_on_main_thread(code: () -> Void)
{
    dispatch_async(dispatch_get_main_queue(), code)
}

func manage_response()
{
    run_on_background_thread
    {
        long_process()
        run_on_main_thread
        {
            UIView.animateWithDuration(animation_duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseInOut, animations:
                {
                    some_view.transform = CGAffineTransformMakeScale(0, 0)
                }, completion: nil)
        }
    }
}

Quite obviously, the animation does not occur. The UI just updates to the final stage. What is the proper way to thread this (I know animateWithDuration() dispatch's it's own thread, but I don't know how to hold this animation until the long process is complete.
Thanks.

A: I think U way can work. just change
some_view.transform = CGAffineTransformMakeScale(0, 0)

to :
some_view.transform = CGAffineTransformMakeScale(0.01, 0.01)

change the scale value close to zero; U can see the animation occur. if scale value == 0,there is no animation occur. U can try this.


text:
Q: Relationship between the on-shell and BPHZ renormalization schemes In his book Quantum Field Theory - A Tourist Guide for Mathematicians, Gerald Folland introduces the on-shell renormalization scheme for the $ \phi^{4} $-scalar field theory. According to my understanding, this is a scheme by which counter-terms are determined, one order at a time, by fixing the pole and residue of the sum $ \Pi(p) $ of all non-trivial $ 1\text{PI} $-diagram insertions into a propagator with external momentum $ p $.
I know how to make calculations with this scheme up to second loop order, so naïvely, one would think that this process can be continued, without difficulty, to higher orders. However, I also know that this kind of thinking is wrong (because this is supposed to be a non-trivial problem!), but I do not see how it can be wrong. I am aware of the problems posed by sub-divergences, but given the algorithmic nature of the on-shell renormalization scheme, I do not see why calculating higher-order corrections might interfere with the calculations for lower-order ones.
The BPHZ renormalization scheme gives a rigorous proof of renormalization to all orders, and it is rather elegant in the sense that it tells us how to renormalize individual Feynman integrals. Hence, I am trying to see how the on-shell scheme can be shown to be equivalent to the BPHZ procedure.
Thank you very much!

A: I believe that this may be what you're looking for. I don't claim to be an expert in renormalization, so all members of the Physics Stack Exchange Community are welcome to correct my answer.
To make the relationship between the two more precise, let's call the on-shell renormalization scheme the 'on-shell subtraction scheme' and the BPHZ renormalization scheme the 'BPHZ algorithm'.
The on-shell subtraction scheme tells us how to subtract the divergent parts of a Feynman diagram, while the BPHZ algorithm tells us how to apply the subtractions to a multi-loop Feynman diagram in a sensible manner so that the problem of overlapping divergences is overcome.
Hence, the relationship between the two concepts is precisely this:

One uses the on-shell subtraction scheme in conjunction with the BPHZ algorithm in order to cure the divergences of the $ \phi^{4} $-theory to all orders of perturbation theory.

Without a subtraction scheme that yields a subtraction operator, the BPHZ algorithm is useless, because we have to tell the algorithm how to subtract!
Without the BPHZ algorithm, the on-shell subtraction scheme is very limited in scope, because it doesn't tell us how to apply subtractions properly to address the technical difficulties associated with overlapping divergences.
The BPHZ algorithm also works with other subtraction schemes, like the minimal subtraction scheme. It can also be used with the momentum subtraction scheme, of which the on-shell subtraction scheme is just a single instance.
Now, Anthony Duncan explains what I've just mentioned in awesome detail in his book The Conceptual Framework of Quantum Field Theory. You may also consult John Collins' book Renormalization.


text:
Q: How to detect if expansion takes place while evaluating a \pgfmathparse-expression/if inside a \pgfmathparse-expression? I intend to write a macro which behaves differently depending on whether used within a \pgfmathparse-expression or used outside a \pgfmathparse-expression.
For example a commend \MyNicePi which expands to the sequence pi within a \pgfmathparse-expressions not nested between "..." and to the control-word-token \textpi otherwise.
(The sequence pi is a recognized function inside \pgfmathparse-expressions.
When loading the package textgreek, then\textpi in horizontal and vertical modes delivers the symbol π.
" is the quote-operator in \pgfmathparse-expressions, i.e., things in quotes are expanded but not evaluated by \pgfmathparse.)
So the questions are:
Does the mathematical engine of PGF bring along a test or a switch for finding out if currently evaluation of a \pgfmathparse-expression is taking place?
If not:

*

*What is the best way to implement such a test oneself?

*What criteria can be used for determining whether currently evaluation of a \pgfmathparse-expression is taking place?

Something like:
\documentclass{article}
\usepackage{textgreek}
\usepackage{tikz}

\newcommand\MyNicePi{%
  % A test for checking if pgfmathparse-evaluation takes place and either
  % pi or \textpi
}%

\begin{document}

\leavevmode\MyNicePi{} is approximately
\pgfmathparse{\MyNicePi}\pgfmathprintnumber[fixed, precision=3]{\pgfmathresult}\,.

\end{document}

delivering the same as
\documentclass{article}
\usepackage{textgreek}
\usepackage{tikz}

\begin{document}

\leavevmode\textpi{} is approximately
\pgfmathparse{pi}\pgfmathprintnumber[fixed, precision=3]{\pgfmathresult}\,.

\end{document}

A: I see no particular way to recognize whether TeX is in the middle of performing \pgfmathparse, but it's not difficult to add a test, exploiting the fact that the definition of \pgfmathparse begins with \begingroup.
\documentclass{article}
\usepackage{textgreek}
\usepackage{tikz}
\usepackage{etoolbox}

\newif\ifudparse
\patchcmd{\pgfmathparse}
  {\begingroup}
  {\begingroup\udparsetrue}
  {}{}

\newcommand\MyNicePi{\ifudparse pi\else\textpi\fi}

\begin{document}

\MyNicePi{} is approximately
\pgfmathparse{\MyNicePi}\pgfmathprintnumber[fixed, precision=3]{\pgfmathresult}\,.

\MyNicePi{} is approximately half of
\pgfmathsetmacro\foo{2*\MyNicePi}\pgfmathprintnumber[fixed, precision=3]{\foo}\,.

\end{document}

The example shows that also \pgfmathsetmacro works (because it calls \pgfmathparse internally).

Also Phelype Oleinik's idea to test for \pgfmath@parse@next is good, but has the defect of depending on the particular name. Instead, \begingroup has to be performed by \pgfmathparse. Of course, if the maintainers decide to change the top level definition and to hide \begingroup in another macro, we're doomed.
I think this should be a feature request to the developers of TikZ/PGF.


text:
Q: How to define a user in postgreSQL I want to define a variable user similar to this set up in mongoose, except I want to do it in postgreSQL:
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var User = mongoose.model('User', new Schema({
  id: ObjectId,
  firstName: String,
  lastName: String,
  email: { type: String, unique: true },
  password: String,
})));

Essentially, I have a database currently set up that stores the user information after they register in postgreSQL, but now I want to create sessions that allow me to easily retrieve and display a user's data after the user signs in. In the example that I watched, (https://www.youtube.com/watch?v=yvviEA1pOXw&list=UUJI9gByFSXE1ABDRcLQjWgQ) someone used mongoose as their DB and I was not sure how to establish sessions with postgreSQL as they did with mongo.