text:
Q: DXGI: trying to get correct display mode from output (monitor) I'm currently stuck with a pesky little issue. I developed an application that zeroes out the DXGI mode desc. structure and calls FindClosestMatchingMode() to, as advertised, "gravitate towards the desktop resolution".
This works fine if the laptop(s) run fully on their own display -- as soon as I plug in another monitor it goes berserk. In the case I extend my desktop it will still correctly get the laptop monitor resolution, yet the attached one (running 1080p) will yield a preference for 800*480 :) (sure, poor man's 16:10, but...)
Doing the same thing with the monitors cloned/combined (results in 1 output device), even if their resolution is equal, gives the same 800*480 crap.
What gives? And has anyone perhaps found a way to properly get a display's current mode through DXGI or a pointer for a wholly different yet functional approach to this here problem?
Life was easier back in the D3D9 days =)
-- Update
As it turns out any FindClosestMatchingMode() call made on the IDXGIOutput instance belonging to the external monitor behaves differently (and in most cases plain wrong) compared to the internal display, even though their native resolution is identical. To top it all off, other systems don't have this issue yet I can't get around supporting this particular laptop including it's drivers.
Time for a good old setup dialog.

A: Not the best solution but as I was constrained to these exact machines I settled for getting the monitor's current resolution through GetSystemMetrics() (SM_CXSCREEN/SM_CYSCREEN), which admittedly only works for the primary monitor but there's other ways, and feeding this resolution to the ModeToMatch structure fed to FindClosestMatchingMode().
It then settles for the correct (desktop) resolution.
Better answers are very welcome of course ;)


text:
Q: What is the syntax for named parameters in Laravel 4 routes? I would like to use named parameters for all my routes in Laravel 4, rather than relying on the position in the route definition.  I cannot find anything in the manual that describes how to do this.
I saw this github issue that indicates this feature exists in Laravel 4: https://github.com/laravel/laravel/pull/832#issuecomment-8217765
I've tried setting up routes with a colon prefix, e.g.
Route::get('{:foo}/{:bar}', function($bar, $foo) {})

I also tried using what appears to be the old syntax, with (:foo)/(:bar) rather than curly braces, but that doesn't work either.  The parameters always come through in the order they were defined in the route.
Example:
The application I'm working supports some routes that I need to maintain.  But they were not designed in a proper restful style.

/autoaccount/user/2/3 refers to to the auto account with id=2 of the user with id=3

The new design for this is:

/users/{userid}/autoaccounts/{autoaccountid}

So the parameters are in a different order for the new route.  I would like to point both of these routes to the same function.

A: Laravel 4 supports this as you said.
You need the variables in curly brackets as you have done, but without the colon:
Docs are routing are here.
Relevant example:
Route::get('user/{id}/{name}', function($id, $name)
{
    //
})
->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))

Note that the where() portion is optional.
Check out the docs linked above for available options. Note that you can define a controller method and other options in an array passed to the Route::method() calls.
Lastly, see also the controller docs for routing to a controller.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google's cloud SDK doesn't return `createTime` I'm trying to list info about some instances using cloud sdk, but for some reason the createTime field is not returned. Any idea why?
$ gcloud compute instances list --format="table(name,createTime)" --filter="name:florin*"
NAME                         CREATE_TIME
florin-ubuntu-18-playground

This should work according to this https://cloud.google.com/sdk/gcloud/reference/topic/filters

A: The command gcloud compute instances list does not show the instances creation time by default. But the gcloud --format flag can change the default output displayed.
gcloud compute instances list --format="table(name,creationTimestamp)"
It is also possible to retrieve the instance creation time from the gcloud compute describe command:
gcloud compute instances describe yourInstance --zone=yourInstanceZone | grep creationTimestamp

Or:
gcloud compute instances describe yourInstance --zone=yourInstanceZone --flatten=creationTimestamp


text:
Q: Template specialization to check whether a member is present This is a follow up to my question SFINAE with variadic templates. I was trying to construct a variadic template named has_member for checking whether a class has a member (called member).
I tried to see if I could use size_t instead of void in the answer to that question and not use variadic templates, as follows:
#include <iostream>
#include <vector>
using namespace std;

class ClassWithMember
{
    public:
    int member;
};
class ClassWithoutMember
{
};

template <typename T,typename=size_t>
class has_member: public std::false_type
{
};
template <typename T>
class has_member<T,decltype(sizeof(typename T::member))>: public std::true_type
{
};

template <typename T1,
          std::enable_if_t<has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes with member"<<endl; }

template <typename T1,
          std::enable_if_t<!has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes without member"<<endl; }

int main()
{
    ClassWithMember objWithMember;
    ClassWithoutMember objWithoutMember;
    my_function (objWithMember);
    my_function (objWithoutMember);
}

I get no errors, but the specialization is never used. Only the function for classes without the member gets called. Could someone please explain why?

A: The typename before T::member is needless.
#include <iostream>
#include <vector>
using namespace std;

class ClassWithMember
{
    public:
    int member;
};
class ClassWithoutMember
{
};

template <typename T,typename=size_t>
class has_member: public std::false_type
{
};

template <typename T>
class has_member<T,decltype(sizeof(T::member))>: public std::true_type
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
{
};

template <typename T1,
          std::enable_if_t<has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes with member"<<endl; }

template <typename T1,
          std::enable_if_t<!has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes without member"<<endl; }

int main()
{
    ClassWithMember objWithMember;
    ClassWithoutMember objWithoutMember;
    my_function (objWithMember);
    my_function (objWithoutMember);
}

Demo
[OT] Just a tip for further metaprogramming: you can also test by using the real types instead of templates.


text:
Q: How to create a full window of a 30 days on a pandas dataframe with groupby if some days are missing I have the following dataframe:
Data       type   state   price

2021-01-01 CHR     NSW     1.2
2021-01-01 CHR     VIC     8
2021-01-04 Kia     NSW     2
2021-01-05 CHR     NSW     2

I applied the below:
df_daily_grouped = df_daily.groupby(['type','state])
the output is the below for CHR:
Data       type   state   price

2021-01-01 CHR     NSW     1.2
2021-01-04 CHR     NSW     2
2021-01-05 CHR     NSW     2
2021-01-01 CHR     VIC     8

As seen above, the dates of "2021-01-02" and "2021-01-03" for CHR in  NSW are missing. I want the below output:
Data       type   state   price

2021-01-01 CHR     NSW     1.2
2021-01-02 CHR     NSW     Nan
2021-01-03 CHR     NSW     Nan
2021-01-04 CHR     NSW     2
2021-01-05 CHR     NSW     2
2021-01-01 CHR     VIC     8
2021-01-02 CHR     VIC     Nan
2021-01-03 CHR     VIC     Nan
2021-01-04 CHR     VIC     Nan
2021-01-05 CHR     VIC     Nan

A: df['Data'] = pd.to_datetime(df['Data'])#Coerce Data to datetime
df1=(df.groupby(['type','state'])['Data'].apply(lambda x: x.reindex(pd.date_range(min(df.Data), max(df.Data),freq='D')))
     .reset_index().drop('Data',1).rename(columns={'level_2':'Data'})#Insert missing dates by reindexing in a new df
     .merge(df, how='left', on=['type','state','Data'])#Merge new and old df
)

# Apply filter
df1[(df1['type']=='CHR')&(df1['state']=='NSW')]


text:
Q: Info on setting up TFS2010 and SharePoint 2010 for 10 Developers I am looking for information on how I can easily setup an environment where I can have about 10 developers working and testing independent SharePoint 2010 projects and having all the source code in TFS2010.  I'd like to have TFS accesible to the PMs as well but that's optional.  I have 11 VM's to work with but our Security folks do not want them listed in DNS.  We are thinking of having 10 VM's each running the same configuration "Contoso.com" and an eleventh running TFS2010.  I'm not sure this is the correct design.  Some ideas on how I could get 10 developes doing independent SharePoint projects and storing code in TFS would be helpful.
Bismarck

A: The DNS limitation is going to be a headache for you; it will complicate the use of Kerberos.  Using stand-alone SharePoint servers to develop against will likely cause deployment and stabilization issues as well.  Developing against a stand-alone server will not allow you to test things like double hops.
Instead of using the VMs as duplicates of each other I would stand up a full domain.  Use two of them for domain controllers, a database server, one or two Web servers, one or two application servers, and the TFS server.  Deploy it in a manner that most closely resembles the production environment.
To partition the environment for developers, just create individual Web applications in SharePoint.  Each developer can code against one or more Web applications on an as needed basis.  By doing this you'll be in control of the domain, which in my opinion is just about mandatory for efficient SharePoint development.  You can create DNS records when you need them, service accounts, SPNs, etc.  The other advantage is that you aren't going to clutter up the corporate domain with a bunch of development based items.
Finally, by using an actual development domain for this you'll be able to test solutions in a more "real world" setting.  This will help to mitigate any risk surrounding deployment.

A: I have some thoughts:

*

*Developers will need credentials into TFS for checkins/checkouts and for any other TFS features they need. Your PMs will need credentials too. It is likely TFS will exist in your corporate domain.

*It is probably a good idea to have all of the VMs in a single domain as opposed to each VM hosting its own contoso.com domain (I'm not clear which way you were thinking, but point this out). This way you can create the same service and user accounts that can be shared between development machines.

*Your best bet is to create a PowerShell script that will automate the configuration of the farm, and make copies for each development VM. The only change you will need to make is the server name. This way, each server is identically configured and you should be able to verify bugs in different farms

*Use a SQL alias. Make sure you configure both 32-bit (C:\Windows\system32\cliconfg.exe) and 64-bit (C:\Windows\SysWOW64\cliconfg.exe) aliases.

*I'm not sure why your security folks don't want to list your VMs in DNS. If this is a policy you cannot change, I suggest creating your own domain with DNS that the VMs join. If possible, have your development domain trust your corporate domain so users in the corporate domain can access your development environments.

*Is your TFS server going to handle builds? Don't forget the build service.


text:
Q: How to check deallocation of memory How to check if memory to which pointer p points has been succesfully deallocated?

A: Sorry, very short answer "You can't"

A: Use IBM rational purify tool to check correct deallocation of memory.

A: Define successfully!  Define deallocated!
After deallocating memory (whether it is free or delete) you must not use that pointer again.  All other assumptions are irrelevant.
After all, you call the C/C++ runtime to deallocate memory, but the C/C++ runtime also calls functions of the operating system to free the page.  You could even have a custom memory allocator on top of the C/C++ runtime that e.g. uses caching to implement a faster memory allocation algorithm.
All of these layers may keep the deallocated memory for themselves (because of fragmentation or just because they like to keep it to themselves) or may tell the underlying layer to deallocate it.  Anything can happen, just don't use that pointer anymore.

A: In few words: you can't.
Check out tools like Valgrind to help you debugging memory leaks issues.
Some other things you should consider:

*

*Use smart pointers so that you don't have do think about memory management,

*Set your pointers to 0 after you free them, so that a further delete has no effect,

*Use standard classes (vector, ...) instead of rolling your own,

*Finally, don't use pointers (actually you almost can)

A: *

*Some tools which are doing static code analysis can point some problems regarding the memory deallocation.

*Use valgrind to check whether you have memory leaks

*Avoid raw pointers - use smart pointers instead

A: Exception handling. I.e. try/catch blocks.

A: In C++, you can safely assume deallocation never fails.  Destructors must not throw exceptions, and the actual memory reserved should never fail to be released, so given those two points, nothing can go wrong.
However, if you delete a pointer that has already been deleted, your program will probably crash.  This isn't a problem with deallocation itself though - the original delete worked successfully.  It's a problem with your program's memory management if it tries to delete a pointer twice, but that's rarely necessary with modern STL and smart pointers like std::vector, std::unique_ptr, etc...


text:
Q: Ipython/Jupyter: Timeout waiting for kernel_info reply I am using python 2.7 through ipython and anaconda. I've restarted my computer, tried different notebooks and tried updating stuff through the conda command line. Yet every time I try to open a notebook the kernel times out and that seems to crash the notebook. Does anyone know how to fix this?
Update: After restarting the kernel from within the notebook the terminal gave this message:
[E 17:45:18.308 NotebookApp] Exception restarting kernel
    Traceback (most recent call last):
      File "C:\Users\bidby\Anaconda\lib\site- packages\notebook\services\kernels\handlers.py", line 88, in post
    yield gen.maybe_future(km.restart_kernel(kernel_id))
  File "C:\Users\bidby\Anaconda\lib\site-packages\tornado\gen.py", line 870, in run
    value = future.result()
  File "C:\Users\bidby\Anaconda\lib\site-packages\tornado\concurrent.py", line
 215, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
TimeoutError: Timeout waiting for restart
[E 17:45:18.308 NotebookApp] {
  "Origin": "http://localhost:8888",
  "Content-Length": "0",
  "Accept-Language": "en-US,en;q=0.8",
  "Accept-Encoding": "gzip, deflate",
  "Host": "localhost:8888",
  "Accept": "application/json, text/javascript, */*; q=0.01",
  "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHT
ML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
  "Connection": "keep-alive",
  "X-Requested-With": "XMLHttpRequest",
  "Referer": "http://localhost:8888/notebooks/Desktop/The%20Prodge/For%20bidby
/SVC-CycleAverages-New-Copy2.ipynb"
}
[E 17:45:18.308 NotebookApp] 500 POST /api/kernels/8df55a56-0cb9-431c-8034-db6c1
6fee7ba/restart (::1) 31152.00ms referer=http://localhost:8888/notebooks/Desktop
/The%20Prodge/For%20bidby/SVC-CycleAverages-New-Copy2.ipynb
[I 17:45:19.460 NotebookApp] Kernel shutdown: 8df55a56-0cb9-431c-8034-db6c16fee7ba

Also the notebook gives this:
The kernel has died, and the automatic restart has failed. It is possible the kernel cannot be restarted. If you are not able to restart the kernel, you will still be able to save the notebook, but running code will no longer work until the notebook is reopened.
When I close and reopen the notebook the terminal says this:
[I 17:46:17.394 NotebookApp] Saving file at /Desktop/The Prodge/For bidby/SVC-CycleAverages-New-Copy2.ipynb
[W 17:46:17.398 NotebookApp] Saving untrusted notebook Desktop/The Prodge/For bidby/SVC-CycleAverages-New-Copy2.ipynb
[W 18:01:59.888 NotebookApp] Session not found: session_id=u'1768b420-e3ba-4f69-a392-d476b76a5774'
[W 18:01:59.905 NotebookApp] 404 DELETE /api/sessions/1768b420-e3ba-4f69-a392-d476b76a5774 (::1) 17.00ms referer=http://localhost:8888/notebooks/Desktop/The%20Prodge/For%20bidby/SVC-CycleAverages-New-Copy2.ipynb
[I 18:02:00.019 NotebookApp] Kernel started: a7d04bdf-d0c8-4b53-be62-3344c6b0f453
[W 18:02:10.052 NotebookApp] Timeout waiting for kernel_info reply from a7d04bdf-d0c8-4b53-be62-3344c6b0f453
[W 18:03:28.661 NotebookApp] Notebook Desktop/The Prodge/For bidby/SVC-CycleAverages-New-Copy2.ipynb is not trusted
[W 18:03:28.815 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20160405174149 (::1) 12.00ms referer=http://localhost:8888/notebooks/Desktop/The%20Prodge/For%20bidby/SVC-CycleAverages-New-Copy2.ipynb
[I 18:05:34.392 NotebookApp] Saving file at /Desktop/The Prodge/For bidby/SVC-CycleAverages-New-Copy2.ipynb
[W 18:05:34.395 NotebookApp] Saving untrusted notebook Desktop/The Prodge/For bidby/SVC-CycleAverages-New-Copy2.ipynb

A: I had the same problem and it was fixed by deactivating the antivirus (AVG). This is probably a security issue...
To replicate the problem I reinstalled Anaconda2-4.0.0-Windows-x86_64 and I got the same error with AVG activated.
Kind regards
Adrian


text:
Q: Android - ActionBarSherlock Navigation Drawer and Fragments with Activities I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project.  I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock.  I have an error under the selectItem(int position) section of the code.  I will paste it here:
package com.rufflez.absnavdrawer;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;

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

    mTitle = mDrawerTitle = getTitle();
    mFragmentTitles = getResources().getStringArray(R.array.fragments);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
    mDrawerList = (ListView)findViewById(R.id.drawer_list);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this,
            mDrawerLayout,
            R.drawable.ic_drawer,
            R.string.drawer_open,
            R.string.drawer_close){
        public void onDrawerClosed(View v){
            getSupportActionBar().setTitle(mTitle);
            supportInvalidateOptionsMenu();
        }
        public void onDrawerOpened(View v){
            getSupportActionBar().setTitle(mDrawerTitle);
            supportInvalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    if (savedInstanceState == null){
        selectItem(0);
    }

}

@Override
public boolean onPrepareOptionsMenu(Menu menu){
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getSupportMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
    case android.R.id.home:
        if (mDrawerLayout.isDrawerOpen(mDrawerList)){
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
        return true;
    case R.id.action_settings:
        Intent i = new Intent(MainActivity.this, Sources.class);
        startActivity(i);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

private class DrawerItemClickListener implements ListView.OnItemClickListener{
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        selectItem(position);
    }
}

private void selectItem(int position){
    Fragment newFragment = new Fragment_1();
    FragmentManager fm = getSupportFragmentManager();
    switch(position){
    case 0:
        newFragment = new Fragment_1();
        break;
    case 1:
        newFragment = new Fragment_2();
        break;
    case 2:
        newFragment = new Fragment_3();
        break;
    case 3:
        newFragment = new Fragment_4();
        break;
    case 4:
        newFragment = new Fragment_5();
        break;
    }
    fm.beginTransaction()
    .replace(R.id.content_frame, newFragment)
    .commit();

    mDrawerList.setItemChecked(position, true);
    setTitle(mFragmentTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

@Override
public void setTitle(CharSequence title){
    mTitle = title;
    getSupportActionBar().setTitle(title);
}

@Override
protected void onPostCreate(Bundle savedInstanceState){
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

}

As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();.  The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;

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

  //  pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);

  //  webview = (WebView) findViewById(R.id.WebView);

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {
           if(progress < 100 && pd.getVisibility() == View.GONE){
               pd.setVisibility(View.VISIBLE);
           }
           pd.setProgress(progress);
           if(progress == 100) {
              pd.setVisibility(View.GONE);
           }
        }
    });

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url){
            // do your handling codes here, which url is the requested url
            // probably you need to open that url rather than redirect:
             if (url.startsWith("tel:")) {
                 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
             } else if (url.startsWith("mailto:")) {
                 url = url.replaceFirst("mailto:", "");
                 url = url.trim();
                 Intent i = new Intent(Intent.ACTION_SEND);
                 i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
                 startActivity(i);

             } else {
                 view.loadUrl(url);
             }
             return true;
             // then it is not handled by default action
       }
    });

    webview.loadUrl("file:///android_asset/about.html");
}

@Override
public void onBackPressed()
{
    if(webview.canGoBack())
        webview.goBack();
    else
        super.onBackPressed();
}

public void setUrl(String url) {
    this.url = url;
}

public String getUrl() {
    return url;
}
}

A: I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.

A: Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:

A: Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{

i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;

public class Fragment_1 extends SherlockFragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);

//change frag1 to corresponding XML
}
}


text:
Q: make specific css code for IE10 I bind some type for my site:
@font-face {
font-family:WILLS;
src:url(WILLS.TTF);
}

In most browsers this types recognize perfectly but IE don't see this type because of ttf extensions. But the problem is that IE10+ aren't support this condition.
<!--[if IE]>...<![endif]-->
Is there any way to make specific css code for IE10 to change type to usuall, for example Tahoma or times and ofcourse change font-size?

A: You will need to specify a EOT file for IE9+ and a TTF file for <= IE8
@font-face {
font-family:WILLS,
src:url(WILLS.TTF),
url(WILLS.EOT); /* IE9+ */
}

If you convert the TTF file to an EOT file and upload both files. IE9 and above will use the EOT file

A: I would suggest you look into a webfont generator. It will give you the font types you need to also support IE10 and will make css code which ensures best support cross-platform.
Font Squirrel is the most used/popular out there but there are more
http://www.fontsquirrel.com/tools/webfont-generator


text:
Q: BiWeekly Iterating over daylight savings change I am trying to iterate an event across a daylight savings change with the Java BiWeekly library.
Say the event starts at 8am, I want it to stay at 8am regardless of whether daylight savings is in effect or not.
The following code is from the BiWeekly website: https://github.com/mangstadt/biweekly/wiki/Examples#calculating-the-dates-in-a-recurring-event
ICalendar ical = ...
TimezoneInfo tzinfo = ical.getTimezoneInfo();

VEvent event = ical.getEvents().get(0);
DateStart dtstart = event.getDateStart();

TimeZone timezone;
if (tzinfo.isFloating(dtstart)){
  timezone = TimeZone.getDefault();
} else {
  TimezoneAssignment dtstartTimezone = tzinfo.getTimezone(dtstart);
  timezone = (dtstartTimezone == null) ? TimeZone.getTimeZone("UTC") : dtstartTimezone.getTimeZone();
}
DateIterator it = event.getDateIterator(timezone);

If I have a celendar created as:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Michael Angstadt//biweekly 0.6.3//EN
BEGIN:VEVENT
UID:deb01413-942a-4ea9-a53c-541493fa668a
DTSTAMP:20200213T051827Z
SUMMARY;LANGUAGE=en-us:Team Meeting
DTSTART;TZID=/Pacific/Auckland:20200213T181827
DURATION:PT1H
RRULE:FREQ=WEEKLY;INTERVAL=2
END:VEVENT
END:VCALENDAR

Iterating over this, the time changes by an hour as it crosses the daylight savings boundary.
How should it be done to keep the occurrences occurring at the given time? (It is correct that it occurs at the same time in UTC, but I want it to occur at the same time locally.)

A: For some reason the dtstartTimezone in the code above is returning null even though there was a timezone in the DTSTART of the event. (That might be another issue to track down.)
Because this was null the iterator was getting a UTC timezone and hence the dates iterated were UTC based and changed when crossing the daylight saving boundary in the target timezone.
Removing the timezone assignment code that pulled the timezone out of the calendar and replacing it with val timezone = TimeZone.getTimeZone("Pacific/Auckland") (or the proper timezone) and using that in the iterator fixes this issue.


text:
Q: Parslet Alternatives Not parsing whole string I have the following specs
  it "parses a document with only an expression" do
    puts parser.document.should parse("[b]Hello World[/b]")
  end
  it "parses a document with only text" do
    puts parser.document.should parse(" Hello World")
  end
  it "parses a document with both an expression and text" do
    puts parser.document.should parse("[b]Hello World[/b] Yes hello")
  end

For the following Parslet Parser
class Parser < Parslet::Parser

rule(:open_tag) do
  parslet = str('[')
  parslet = parslet >> (str(']').absent? >> match("[a-zA-Z]")).repeat(1).as(:open_tag_name)
  parslet = parslet >> str(']')
  parslet
end

rule(:close_tag) do
  parslet = str('[/')
  parslet = parslet >> (str(']').absent? >> match("[a-zA-Z]")).repeat(1).as(:close_tag_name)
  parslet = parslet >> str(']')
  parslet
end

rule(:text) { any.repeat(1).as(:text) }

rule(:expression) do
  # [b]Hello World[/b]
  # open tag, any text up until closing tag, closing tag
  open_tag.present?
  close_tag.present?
  parslet = open_tag >> match("[a-zA-Z\s?]").repeat(1).as(:enclosed_text) >> close_tag
  parslet
end

rule(:document) do
  expression | text
end

The first two tests pass just fine, and I can see by puting them out to the command line that the atoms are of the correct type. However, when I try to parse a document with both an expression and plain text, it fails to parse the plain text, failing with the following error
Parslet::UnconsumedInput: Don't know what to do with " Yes hello" at line 1 char 19.

I think I'm missing something regarding defining the :document rule. What I want is something that will consume any number of in sequence expressions and plain text, and while the rule I have will consume each atom individual, using them both in the same string causes failure.

A: What you were looking for is something like this...
require 'parslet'

class ExampleParser < Parslet::Parser
  rule(:open_tag) do
    str('[') >>
      match["a-zA-Z"].repeat(1).as(:open_tag_name) >>
    str(']')
  end

The open_tag rule doesn't need to exclude the ']' character as the match only allows letters.
  rule(:close_tag) do
    str('[/') >>
      match["a-zA-Z"].repeat(1).as(:close_tag_name) >>
    str(']')
  end

same here
  rule(:text) do
    (open_tag.absent? >>
      close_tag.absent? >>
        any).repeat(1).as(:text)
  end

If you exclude the open and close tags here.. you know you are only dealing with text.
Note: I like this technique of using "any" once you have excluded the things you don't want, but bare it in mind if you are refactoring later as your exclusion list may need to grow.
Note2: You could simplify this further as below..
  rule(:text) do
    (str('[').absent? >> any).repeat(1).as(:text)
  end

.. if you don't want any square brackets in your text at all.
  rule(:expression) do
    # [b]Hello World[/b]
    open_tag >> text.as(:enclosed_text) >> close_tag
  end

This becomes much simpler as the text can't include a close_tag
  rule(:document) do
    (expression | text).repeat
  end

I've added in the repeat you missed (as pointed out by matt)
end

require 'rspec'
require 'parslet/rig/rspec'

describe 'example' do
  let(:parser) { ExampleParser.new }
  context 'document' do
    it "parses a document with only an expression" do
      parser.document.should parse("[b]Hello World[/b]")
    end
    it "parses a document with only text" do
      parser.document.should parse(" Hello World")
    end
    it "parses a document with both an expression and text" do
      parser.document.should parse("[b]Hello World[/b] Yes hello")
    end
  end
end

RSpec::Core::Runner.run([])

Hope this give you some tips on using Parslet. :)

A: For your document rule you want to use repeat:
rule(:document) do
  (expression | text).repeat
end

You'll also need to change your text rule; currently if it starts matching it will consume everything including any [ that should start a new expression. Something like this should work:
rule(:text) { match['^\['].repeat(1).as(:text) }


text:
Q: Voltmeter reading in a bridge circuit Why would it be wrong to calculate the voltmeter reading in the following diagram as one plus 2 ohms is 2/3 ohms as they are in parallel, hence the p.d. reading on the voltmeter must be the current times the resistance which is 1.5 V. Why does this not work?

A: Instead of presenting a solution, I'd like to point out where you're going the wrong way.
You're talking about "the" resistance and "the" current, as if there were only one resistance and one current in the whole circuit. You need to be much more explicit in expression (and probably also in thinking) when talking about circuits.
The circuit has:

*

*4 resistors, each having its own resistance value, a voltmeter, which might or might not have a resistance value. By simplifying the circuit, you might introduce additional, computed resistances.

*6 branches (battery branch, 4 resitor branches, voltmeter branch), each with one current value flowing throught the branch, and one voltage across the branch.

*4 nodes where the branches meet (left-hand and right-hand end of the bridge plus the two nodes in between, where the voltmeter is connected.

If you want to be clearly understood, without the risk of mis-interpretation, it's a good idea to give individual names to all of these circuit elements.
With "one plus 2 ohms" you probably mean the two resistors to the left (but that's already guesswork...).
You write "as they are in parallel". That isn't true. To be parallel, they need to be both at the same network nodes, at both ends. To the left, they share a node, but to the right, they are connected to different ends of the voltmeter, so they are not directly connected there.
The "parallel resistance rule" isn't only a formula to do some calculations, but also defines pre-conditions and states what to do with the result.
If you have two resistors that are directly connected to one another at both ends, then you can effectively replace them with a single resistor whose value is calculated as $R_p = \frac{R_1 \cdot R_2}{R_1 + R_2}$
So, you can understand it as a redrawing rule, that allows you to replace a circuit with a simpler one, having the same effect to the outside.
You tried to apply this rule although its preconditions weren't fulfilled.
If the voltmeter were a direct connection (behaving like an ideal wire), then you could treat the resistors as being parallel. But then there would be no voltage difference between the two ends of the voltmeter, and it would always show zero, rendering it useless. And that's why an ideal voltmeter does not behave like a wire but like a resistor with infinite resistance, effectively removing its "connection" from the circuit.
You write "...must be the current times the resistance which is 1.5 V". Which current? Again, you apply a rule (Ohm's law) without ckecking whether its preconditions are met.
The voltage U across a resistor is the current flowing through this resistor times its resistance value.
The formula is true only if you take voltage, current and resistance at one single resistor, not if you mix a current from here with a voltage from there and the resistance from still another place.
If you want to directly use Ohm's law to compute the voltage across the voltmeter, you need

*

*the resistance value of the voltmeter (unknown, typically assumed to be infinite for an ideal voltmeter),

*the current through the voltmeter (hard to compute without a given voltmeter resistance, typically assumed to be zero for an ideal voltmeter),

*an assertion that the voltmeter behaves like a resistor (not necessarily true).

At best, you end up with $U = \infty \cdot 0$, which can be any number you like.

A: Yes, you can imagine the upper and lower branch to be in parallel. The assumption here is that the voltmeter is ideal, that is only a negligible current flows through it.
But draw the upper and lower branch separately first as two loops. As we established that no current flows between the two branches. Then what is the potential difference as you go along these two individual loops at each point?


text:
Q: Algorithm that matches people based on multiple possible matches Let's say I have a set of 5 people P = {1, 2, 3, 4, 5} and I know that there are the following possibilities of matching them together:
{1,2}, {1,3}, {1,5}, {2,1}, {2,4}, {2,5}, {3,1}, {3,4}, {4,2}, {4,3}, {4,5}, {5,1}, {5,2}, {5,4}

For example they could symbolise who likes who (everyone is bisexual,
  gender doesn't matter).

Visualised as a graph:

Now I want to actually know who to match with each other so that everybody is matched with someone. Ideally no one is left out.

So based on the example: Who should get married with whom? Ideally no one should stay single.

A little twist: Also up to 3 people could be matched together.

So based on the example: polyamorous marriage is allowed.

So I can do it manually and get a result that works. So I know that because of {1,2}, {1,5} and {2,5} I can match {1,2,5} together.
Now that means that persons 1,2 and 5 are out, which only leaves the following combinations:
{3,4}, {4,3}

Which leads to {3,4}.
So the final result could be: {1,2,5} and {3,4}

So based on the example: Person 1, 2 and 5 get married and person 3
  and 5 get married.

Again, visualised as a graph:

Now, this is a toy example. It get's much more complicated if the number of people and possible matches goes up.
I am looking for a push in the right direction on how to solve such a problem with a computer.

A: You can take a somewhat brutal recursive Python function like
# people is a frozenset
# conflicts is a set of frozenset pairs
def match(people, conflicts):
    if not people:  # people is empty
        return {}
    for group in next_groups(people, conflicts):
        solution = match(people - group, conflicts)
        if solution is not None:
            solution.add(group)
            return solution
    return None

def next_groups(people, conflicts):
    a = min(people)
    for b in people - {a}:
        if frozenset({a, b}) in conflicts:
            continue
        yield frozenset({a, b})
        for c in people - {a, b}:
            if frozenset({a, c}) in conflicts or frozenset({b, c}) in conflicts:
                continue
            yield frozenset({a, b, c})

and memoize it (look up people in a dictionary to see what the output was last time).


text:
Q: When should I use "that"? I'm not sure whether I should take it out or keep it in Here are the sentences I'm trying to rewrite:
"No one will ever work hard enough to achieve something higher than what society has planned for them… well, 3 years ago I found out that this saying is completely false."
"Almost everyone told me I (that?) was going to be a nobody."
"It was crazy to think that a few years ago my best chance at life was becoming a customer service employee at Walmart, now I'm getting funding to build my ideas."
"This is what I want to contribute to Rice, the idea that no matter how low you feel or how many people tell you that "You suck", your passion and drive will get you anywhere you want to go."

A:
After a verb of attribution (said, stated, announced, disclosed), the word "that" often can be omitted with no loss of meaning:
      He said (that) he was tired. No need for "that." Better to omit.

But if the words that follow "said" (or any verb of attribution) might be mistaken as objects of the verb, omitting "that" might lead the reader down a false trail:

*

*The governor announced his new tax plan would be introduced soon.

Here "that" is needed after "announced. Without it, the reader's first impression is that the plan itself has been put forth. Remember that even momentary confusion provides readers with a handy place to stop — and that's not good. A reader should never have to pause to understand what the writer (or speaker) is trying to convey. If that happens too often (and once may be once too often), a reader stops reading.
Time element: When a time element is linked to the verb of attribution, the conjunction "that" must be used. For example:

*

*The mayor announced June 1 the fund would be exhausted.

The reader needs to know if the time applies to the material that precedes or follows it. Did he make the announcement June 1? ("...announced June 1 that...") Or did he say the fund then would be exhausted? ("...announced that June 1...") In either case, the need for "that" should be obvious. The need remains when the time element is not a date but a day of the week (Monday, Tuesday, today, yesterday, etc.).
"Thats" that travel in pairs
     Often a sentence with two parallel clauses requires the expression "and that" to introduce the second clause and link it to the antecedent common to both clauses:

*

*The senator said he might run again and, if he did, Myra Henry would be his campaign manager.

A "that" is needed after "and" to make it clear for the reader. Therefore, a "that" must be inserted after "said" because of a rule called parallelism — if you've got one "that" referring to the same antecedent, you need another. The "that" after "said" is required even though none would be required had the sentence ended after "again."

*

*The senator said that he might run again and that, if he did, Myra Henry would be his campaign manager.

So, just remember. If you need one "that" for clarity, make sure you put in another "that" in any compound sentence.
To use "that" or not to use "that"?
That is the question.
The decision to use or omit "that" is not always a simple one. Sometimes it's a judgment call. But don't let your desire to lop off unnecessary words lead you into bad judgment.
    As a rule of thumb in questionable cases, remember: Using "that" is never really wrong, though it may be unnecessary; omitting "that" in some cases indeed may be wrong.


text:
Q: How to make spamassassin not check whether an authenticated user is in a blacklist? I am sure this is a common occurrence: a user (who has an IP that is in a blacklist or two ) is sending mail using his email provides server (with SMTP authentication), then that server is forwarding the message to the recipient.
Here's a sanitized header of such message.

Received: from email-com-hosting.com ([1.2.3.4])
    by mail.email2.com with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
    (Exim 4.84_2)
    (envelope-from <sender@email.com>)
    id 1aaaaa-000000-aa
    for recipient@email2.com; Fri, 30 Sep 2016 00:01:00 +0300
DKIM-Signature: some-valid-signature-added-by-1.2.3.4;
Received: from [5.6.7.8] (helo=[10.0.0.1])
    by email-com-hosting.com with esmtpa (Exim 4.76)
    (envelope-from <sender@email.com>)
    id 1aaaaa-000000-ab
    for recipient@email2.com; Fri, 30 Sep 2016 00:00:00 +0300

Server 1.2.3.4 is the actual server for email.com, the mx record points to it ant everything.
IP 5.6.7.8 is in a couple of blacklists.
Spamassassin marks this email as spam because 5.6.7.8 is in a blacklist.
How do I make it ignore all received headers that have "esmtpa" - autenticated SMTP and all headers below it? The idea is this:

*

*If the header is genuine and the user is actually authenticated, do not check if the IP is in a blacklist.

*If the header is spoofed, then it is useless anyway.

*If the user is not authenticated, then check his IP too.

For now I can add -lastexternal or -notfirsthop to all checks, but maybe there is a way to do this incorporating the presence/absence of "a" in the received header.


text:
Q: Number of consumer not shrinking when there is not load in JMS queue I am writing a JMS consumer using spring-jms to consume message from the ActiveMQ Artemis broker. I am investigating the behaviour of 3 properties: concurrentConsumers, maxConcurrentConsumers, and idleConsumerLimit.
Expected behaviour is when load in queue increase consumer should scale up to maxConcurrentConsumers and when load decreases consumer should scale down to idleConsumerLimit.
But this is not happening with spring-jms and ActiveMQ Artemis. When there is no message in the queue consumer count is not coming down instead it retaining all the maxConcurrentConsumers.
I am using spring DMLC container
    <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destinationName" value="TestingInQueue" />
        <property name="messageListener" ref="messageListener" />
        <property name="concurrentConsumers" value="1"/>
        <property name="maxConcurrentConsumers" value="20"/>
        <property name="idleConsumerLimit" value="5"/>
    </bean>

Complete context XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
        <property name="environment">
            <props>
                <prop key="java.naming.factory.initial">org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory</prop>
                <prop key="java.naming.provider.url">tcp://localhost:61616</prop>
                <prop key="java.naming.security.principal">admin</prop>
                <prop key="java.naming.security.credentials">admin</prop>
            </props>
        </property>
    </bean>

    <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiTemplate" ref="jndiTemplate"/>
        <property name="jndiName" value="ConnectionFactory"/>
    </bean>

    <bean id="destinationQueue" class="org.apache.activemq.artemis.jms.client.ActiveMQQueue">
        <constructor-arg index="0" value="TestingInQueue" />
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destinationQueue" />
    </bean>

    <bean id="messageListener" class="com.practise.SampleListener">
        <property name="jmsTemplate" ref="jmsTemplate" />
        <property name="queue" ref="destinationQueue" />
    </bean>

    <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destinationName" value="TestingInQueue" />
        <property name="messageListener" ref="messageListener" />
        <property name="concurrentConsumers" value="1"/>
        <property name="maxConcurrentConsumers" value="20"/>
        <property name="idleConsumerLimit" value="5"/>
    </bean>
</beans>

A: Note:

*

*maxConcurrentConsumers : Your maximum consumers under load

*concurrentConsumers : You will eventually get here if you are idle for some time. (The time it takes to reach here depends on next 3 params)

The following 3 are to avoid consumers drastically scaling up and down between maxConcurrentConsumers and concurrentConsumers without any time delay.

*

*idleConsumerLimit

*maxMessagesPerTask

*idleTaskExecutionLimit
Example
If you start with heavy load, you will have 20 (maxConcurrentConsumers) consumers. Then if you make the queue empty, it will scale down to 5 (idleConsumerLimit) . Then it will wait idleTaskExecutionLimit attempts to be reached and then scale down to 1 (concurrentConsumers).
idleTaskExecutionLimit is number of fetch attempts which resulted in empty fetch where each fetch take receiveTimeout (default 1000ms) time unit.
Issue:
Default value of maxMessagesPerTask is -1 and idleConsumerLimit is not taking effect if maxMessagesPerTask is not greater than zero
Solution:
When specifying idleConsumerLimit, specify maxMessagesPerTask too.

Specify a number of 10 to 100 messages to balance between rather long-lived and rather short-lived tasks here for maxMessagesPerTask

Reference

*

*https://access.redhat.com/solutions/1412643

*DefaultMessageListenerContainer


text:
Q: Set default option for `md-radio-group` I have an extremely simple md-radio-group and I am having a tough time setting the default value.  The group is using an object (which I am assuming is related to the problem).
Please reference my codepen example.
I am defaulting the md-radio-group to the 2nd option but the radio button is never selected.
Am I missing something?

A: Couple of changes here:
You are interpolating the value of the radio. Doing so is unncessary, and loses reference to the object in the array for which you are iterate. Change your value to ng-value="option".
In your controller, set your default option. Since array positions start at 0, for your second option, you'll use [1].
$scope.optionExample = $scope.options[1];

A: A simple way if you add another attribute to make default selection, like below
$scope.statusList = [{ id: "APN", status: "Approved", isChecked: true }, { id: "VIP", status: "Scheduled", isChecked: false }, ];

in HTML
<input type="checkbox" ng-model="item.isChecked" ng-repeat="item in statusList"/>
<label class="form-control" style="width:305px"> {{item.status}}  </label>


text:
Q: Getting data with nodeJs with or without php Lately I was watching a lot nodeJS tutorials and from one live chat app with nodeJs and mongo db the user logs in and send the message, insert in database and output in real time to all users.
Is that secured enough or should we use php as well?


text:
Q: Receive a message on a device with GCM Actually I am working on the notifications for an Android app.
My two main source of information are this tutorial and the android developer web site.
Let me quickly describe my app:

*

*In my app I use web services (WS) which work with POST HTTP request.

*For the Notification I use the GCM system.

*My app uses the 'POST HTTP' request system above to be register on my server.

*Actually my server does exactly the same job as the one in the tutorial (that means to register an account in the database with to two parameters and the register ID of the device, and send a message to the device with GCM)

Actually all of these steps work:

*

*My app receive successfully gets register ID (gcm.register(SENDER_ID); work)

*My app get successfully registered on my server

*My server receives a successful message when I try to send a message from my device
{"multicast_id" : 6276079906208554309 , "success" : 1 , "failure" : 0 , "canonical_ids" : 0 , "results" : [{"message_id" : "0:1374826298092960%978fee92f9fd7ecd"}]}
The Problem:

*

*I receive nothing on my device
What I did:
I try to do two versions of the application:

*

*First I made an app using a part of the code of the tutorial, but with using the package com.google.android.gms.gcm.GoogleCloudMessaging instead of the com.google.android.gcm which are deprecated (and used in the tutorial), but I was unable to receive a message, so I try a second version …

*This time I took the entire tutorial and just change the register function on the server to use mine, but like the first app, I receive nothing on my device. (I did this to try to understand how work the reception but it did not help me, and now I will forget this way)

Where do I need your help:
I need some/more explanation how to receive the message sent by my server.

*

*My main activity uses the code describe on the android developer web site.

*I create a broadcast class using the code on the android developer web site.

*I don't create any IntentService or service, maybe it is my error, but according what I read I understood that I don't need one, like before with the deprecated GCMBaseIntentService

To conclude:

*

*I really will appreciate some help to understand what I need to receive the message on my device, because actually I don't know where I can found the information I need to be able to use this system.

Thanks.
PS: if you need some part of my code , just ask me.
EDIT
my manifest:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.pushnotifications2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="com.androidhive.pushnotifications2.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.androidhive.pushnotifications2.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <!-- Main activity. -->
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <!-- Register Activity -->
        <activity
            android:name="com.androidhive.pushnotifications2.cop.RegisterActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Main Activity -->
        <activity
            android:name="com.androidhive.pushnotifications2.MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name" >
        </activity>

        <receiver
            android:name=".GcmBroadcastReceiver"

            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- Receives the registration id. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.androidhive.pushnotifications2" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

And my GcmBroadcastReceiver (who come from the tutorial)
the WakeLocker is the same as the tutorial too.
package com.androidhive.pushnotifications2;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GcmBroadcastReceiver extends BroadcastReceiver {
    static final String TAG = "GCMDemo";
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context ctx;
    @Override
    public void onReceive(Context context, Intent intent) {
        ///
        WakeLocker.acquire(context);
        ///
        System.out.println("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        ctx = context;
        String messageType = gcm.getMessageType(intent);
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + intent.getExtras().toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " +
                    intent.getExtras().toString());
        } else {
            sendNotification("Received: " + intent.getExtras().toString());
        }
        WakeLocker.release();
        setResultCode(Activity.RESULT_OK);
    }

    // Put the GCM message into a notification and post it.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                new Intent(ctx, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
        .setSmallIcon(R.drawable.common_signin_btn_icon_focus_light)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}


text:
Q: mvc 5 form validation email address message window over wrong field I am using MVC 5 form validation to validate the email address field on a form, but the message window that pops up is not over the correct field, see below:

This is the code for the 3 fields:
<input class="underlineBox text-box single-line filledIn" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" placeholder="ex. Jon Doe" type="text" value="" data-com.agilebits.onepassword.user-edited="yes">

<input class="underlineBox text-box single-line filledIn" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Email" name="Email" placeholder="ex. jdoe@unkown.org" type="email" value="" data-com.agilebits.onepassword.user-edited="yes">

<textarea class="underlineBox text-box multi-line filledIn" data-val="true" data-val-required="The Message field is required." id="Message" name="Message" placeholder="ex. Hi Syd, I would like to start a project together." rows="5"></textarea>

Any ideas?

A:
I am using MVC 5 form validation to validate the email address field on a form, but the message window that pops up is not over the correct field

That's not a picture of jQuery Validate.  By default, jQuery Validate simply inserts text next to the field.
That popup you're showing is the HTML5 validation as per your browser.  This simply means that your JavaScript/jQuery validation is not working for whatever reason.


text:
Q: Filtering array attributes with knockout. Should I working with nested objects or another way exist? Using this http://jsfiddle.net/rniemeyer/NFbxc/ I make almost same stuff(http://jsfiddle.net/uhtshka/HE94X/), which realize almost all my needs, but one trouble still exist. As you can see by the folowing links, array that we use is pretty simple. Kind of:
var simpleArray = [
                   {... som data ...},
                   {... som data ...},
                   {... som data ...}];

But Im trying to realize same functionality with more complicated array structure like:
var notsosimpleArray = [{
     dayname: 'Monday', rows:[
             col1: 'data1',
             col2: 'data2',
             col3: 'data3',
     ]},{dayname: 'Tuesday', rows:[
             col1: 'data1',
             col2: 'data2',
             col3: 'data3',
     ]}];

Is that possible to do with saving same functionality?

A: You can certainly use knockout with complex objects as you describe.
There's some issues with the JSFiddle you referenced (var1-5 set and referenced on the window object?), so I didn't try address the add row function, but I did update the fiddle with an example of using a rows array in the data for each day.
Here's the link:  http://jsfiddle.net/HE94X/1/
Just remember that in your filter function, you are wanting to return an array, which you can find just by looking for the day.  The ko.utils.arrayForEach function is not really needed now, because the array is embedded into the object data for that day.
You should be able to extend this logic to the add row function so that it can push an entry into the rows array for the current day.


text:
Q: how to delete all secrets of a specific type in Kubernetes? I have the kubectl to delete 1 secret:
kubectl delete -n my_name_space secret secret_name

If I want to delete all secrets of type my_type how can I do that?
Also how can I add filter to delete secrets older than 3 days?

A: In order to get secrets of a particular type, you can use --field-selector. Here, is an example:
kubectl get secret --all-namespaces --field-selector type=Opaque

For deleting resources older than x days, please check this thread.
Kubernetes: How to delete PODs based on age/creation time

A: Hello to get secret with a specific type :
kubectl get secret --all-namespaces --field-selector type=Opaque

Also you can get secret older than XXX-date days , you can use this :
kubectl get secrets -o json | jq -r "[.items[] | {name: .metadata.name, startTime: .metadata.creationTimestamp | fromdate } | select(.startTime < (now | . - XXX-date ))]" | jq -r ".[].name"

Don't forget to replace XXX-date by the number of seconds.


text:
Q: A game relevant to sum and sequences.
We have a set of k positive integers $a_i$ and $x$ coins. A and B take turns picking up the coins so that the last picker is the winner. Each turn, one person can only pick up a positive number of coins that in the given set. Knowing that, in the given set always contains number 1. A is the first person to go.

For examples:

*

*Suppose that: With $x=9,k=2$ and $a_1=1,a_2=4$. The result is $A$, because A and B will take turn: $A:4;B:1;A=4$.

*With $x=10,k=2$ and $a_1=1,a_2=4$. The result is $B$, because in any case, B always is the winner.
This is my try: I try build recursion to determine A or B win. I think that the importance in this problem is the number 1 in this set of $k$ positive integers.

*

*If $n$ is even, I will be find the maximize even number in this set and the rest is using the number 1.

*If $n$ is odd, I will be find the maximize odd number in this set and the rest is using the number 1.

But I can't think it clearly to come finally solution!!!

A: I would use two recursive functions: $V_p(r)$ is the value of the game to player A assuming that at the beginning of player $p$'s turn, there are $r$ coins left, and that both players play optimally. If $V_p(r)=1$ then player A will win and if 0 then player A will lose (regardless of the value of $p$).
Let $V_A(0) = 0$ and $V_B(0) = 1$. Then
$$\begin{align*} V_A(r) & = \max_{a\in \{a_1,\ldots,a_k\}} \{V_B(r-a)\} \\
V_B(r) & = \min_{a\in \{a_1,\ldots,a_k\}} \{V_A(r-a)\}
\end{align*}$$
The logic is: Player A wants to choose the value of $a$ (the number of coins to take) that maximizes the value of the game, accounting for the fact that on the next turn, there will be $r-a$ coins left and it will be player B's turn. If $r-a=0$, then player A wins since $V_B(0)=1$.
On the other hand, Player B wants to choose the value of $a$ that minimizes the value of the game (since the value is defined from player A's point of view), accounting for the fact that on the next turn, there will be $r-a$ coins left and it will be player A's turn. If $r-a=0$, then player B wins since $V_A(0)=0$.
Edit: To implement this approach, don't use recursion. Recursion would require you to calculate the value function over and over again for the same $p$ and $r$.
Instead, just loop through $r=1,\ldots,x$ and calculate $V_A(r)$ and $V_B(r)$ at each iteration. When you calculate $V_p(r)$, you use values of $V_p(s)$ for smaller $s$, which you have already calculated.


text:
Q: unable to prevent newline on save Upon saving a file, the editor adds a new line automatically. This is not wanted as it errors our CI tool (I have no control over the CI Tool).
Steps I've taken to remedy:

*

*Removed all extensions in case any were adding user preferences.

*Reviewed and updated user profile to prevent new line upon saving (didn't work)

*Reverted my user settings to default

Nothing seems to work. Does anyone else have this issue and was able to resolve?


text:
Q: codepen scroll function not working or console My code project on codepen has no working Javascript. The console.logs are not running within my javascript. I have a Div with the id and class set to "text1"
$(window).scroll(function(){
    $(".text1").css("color: red");
  });

const masterEl = document.getElementById('text1')
console.log(masterEl)
console.log("masterEl")


text:
Q: .NET Core build in docker linux container fails due to SSL authentication to Nuget I was given a .NET Core project to run in a Linux Docker container to do the build, everything seems to be okay on the docker configuration side, but when I run this command: dotnet publish -c Release -o out, I get the SSL authentication error below.
The SSL connection could not be established, see inner exception. Authentication failed because the remote party has closed the transport stream.
I did my research and apparently it seemed that I was missing:

*

*the environment variables Kestrel for ASPNET (as per https://github.com/aspnet/AspNetCore.Docs/issues/6199), which I add to my docker-compose, but I don't think it is the issue.

*a Developer .pfx certificate, so I updated my docker-compose with the Kestrel Path to the certs file as seen below.
version: '3'
services:
  netcore:
    container_name: test_alerting_comp
    tty: true
    stdin_open: true
    image: alerting_netcore
    environment:
      - http_proxy=http://someproxy:8080
      - https_proxy=http://someproxy:8080
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+;http://+
      - ASPNETCORE_HTTPS_PORT=443
      - ASPNETCORE_Kestrel__Certificates__Default__Password="ABC"
      - ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.dotnet/corefx/cryptography/x509stores/my
    ports:
      - "8080:80"
      - "443:443"
    build: .
      #context: .
    security_opt:
      - seccomp:unconfined
    volumes:
      - "c:/FakePath/git/my_project/src:/app"
      - "c:/TEMP/nuget:/root"
    networks:
      - net
networks:
  net:

I re-run the docker container and executed dotnet publish -c Release -o out with the same results.
From my host I can do this to my local NuGet:
A) wget https://nuget.local.com/api/v2 without issues,
B) but from the container I can't.
C) However from the container I can do this to official NuGet wget https://api.nuget.org/v3/index.json, so definetely my proxy is working okay.
Debugging SSL issue:
The given .pfx certificate is a self-signed one, and it is working okay from Windows OS (at least I was told that).

*

*strace shows me from where the certs are being pulled from as below

root@9b98d5447904:/app# strace wget https://nuget.local.com/api/v2 |& grep certs open("/etc/ssl/certs/ca-certificates.crt", O_RDONLY) = 3

*I exported the .pfx as follows:
openssl pkcs12 -in ADPRootCertificate.pfx -out my_adp_dev.crt then moved it to /usr/local/share/ca-certificates/, removed the private part, just left in the file public part (-----BEGIN CERTIFICATE----- -----END CERTIFICATE----- ) executed update-ca-certificates and I could see 1 added, double checked in file /etc/ssl/certs/ca-certificates.crt and the new cert was in there.

*Executed this again wget https://nuget.local.com/api/v2 and failed.

*I used OpenSSL to get more info and as you can see it is not working, the cert has a weird CN, because they used a wildcard for the subject and to me this is wrong, but they state that .pfx is working in Windows OS.
root@ce21098e9643:/usr/local/share/ca-certificates# openssl s_client -connect nuget.local.com:443 -CApath /etc/ssl/certs
CONNECTED(00000003)
depth=0 CN = *.local.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = *.local.com
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/CN=\x00*\x00l\x00o\x00c\x00a\x00l\x00.\x00c\x00o\x00m
   i:/C=ES/ST=SomeCity/L=SomeCity/OU=DEV/O=ASD/CN=Development CA
---
Server certificate
-----BEGIN CERTIFICATE-----
XXXXXXXXXXX
XXXXXXXXXXX
-----END CERTIFICATE-----
subject=s:/CN=\x00*\x00l\x00o\x00c\x00a\x00l\x00.\x00c\x00o\x00m
issuer=i:/C=ES/ST=SomeCity/L=SomeCity/OU=DEV/O=ASD/CN=Development CA
---
No client certificate CA names sent
Peer signing digest: SHA1
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 1284 bytes and written 358 bytes
Verification error: unable to verify the first certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-SHA384
    Session-ID: 95410000753146AAE1D313E8538972244C7B79A60DAF3AA14206417490E703F3
    Session-ID-ctx:
    Master-Key: B09214XXXXXXX0007D126D24D306BB763673EC52XXXXXXB153D310B22C341200EF013BC991XXXXXXX888C08A954265623
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1558993408
    Timeout   : 7200 (sec)
    Verify return code: 21 (unable to verify the first certificate)
    Extended master secret: yes
---

I don't know what issue I'm facing, but it appears to be that:
A) the self-signed .pfx was wrongly configured, and now that it is being used in Linux it doesn't work as it should.
B) I need some more config in the container, which I'm not aware of.
What else should I do?
I'm thinking on probaly create other cert to use from Linux hosts.
Is it feasible to create another self-signed cert with OpenSSL for IIS ver 8 and import it to IIS?.
Any ideas are welcome, cheers.

A: ANSWERING TO MYSELF
It was not a Linux container issue, it is a certificate issue in the web server (IIS), because we are using self-signed certificates and in this way the cert will be always an invalid certificate. Self-signed certs works okay on Windows OS side, doesn't matter the invalid error. Of course self-signed certs are just for a test environment or so.
From Linux OS when you are trying to pull packages from NuGet you will get the error below, because:
1) The cert is indeed invalid, and
2) because apparently there is not an option to ignore an invalid certificate from Linux side.
The SSL connection could not be established, see inner exception.
The remote certificate is invalid according to the validation procedure.

The solution is you are working in a corporate environment, is to request to System Administrator a proper signed certificate, for that you generate a CSR from your web server, in my case IIS, then pass it to them, so they will send you back a .cer file to install in that web server.
The other option that I was trying to do but I couldn't due to the limitations of my corporate environment, is to create a fake CA (with OpenSSL), then you sign the CSR's yourself to have some valid certificates for your Dev or test environment.
Apologizes for answering this myself, but I believe it is worth to share my findings.
Hope it helps.

A: I had a similar problem. Docker build would not restore my nugets.
Unable to load the service index for source https://api.nuget.org/v3/index.json.
The SSL connection could not be established, see inner exception.
Authentication failed because the remote party has closed the transport stream.
(On a Mac running Catalina)
I turned off Fiddler and then it all worked again.


text:
Q: Mapstraction, OpenLayers, LeafLet, etc? I've been looking through a few different sites and places about geocoding. I currently have a module with Google Maps that I'd like to switch out to a free alternative, like OpenStreetMaps.
However, I've been hearing that these API's are now abstracted away even further, and services like Mapstraction exist that are API-swappable.
However, I haven't been able to find out what OpenLayers really is, same with Leaflet. What are they? Can you swap API's? Do they default to a specfic API?

A: This article could prove helpful: "A Process for Keeping Pace with Evolving
Web Mapping Technologies. Roth et al 2014" (http://cartographicperspectives.org/index.php/journal/article/viewFile/cp78-roth-et-al/1347)
Especially the table on page 34 (page 10 of pdf) gives you a great overview of the different APIs and their capabilities.

A: I've made a small extension (plugin) to OpenLayers 3 which can use one of the following nominatim provider:

*

*OSM

*Mapquest

*Photon

It is called OpenLayers 3 Control Geocoder Nominatim
You can see a demo here.


text:
Q: Circle trail fade out on canvas I am trying to modify my Canvas and touch event so that the circles drawn to it eventually fade out while the user is still moving along the canvas.
Something like this:
Where the smaller circles fade out overtime.
I've gone through the majority of similar questions for this that deal with Bitmaps. I've been struggling to implement the tips suggested in those questions as my circle coordinates are stored to an ArrayList which is looped through and drawn, rather than an individual shape/image drawn to the canvas.
Below is what I've written so far:
 case MotionEvent.ACTION_MOVE: {
           if (inCircle(event, sceneView.circleRadius - 30)) {

               int pointer = event.getPointerCount();

               Point xyPoint = new Point();
               for (int i = 0; i < pointer; i++) {

                       xInput = (int) event.getX() - (50 / 2);
                       yInput = (int) event.getY() - (50 / 2);

                       colorList.add(getCircleColor(sceneView.myBitmap));

                       xyPoint.x = xInput;
                       xyPoint.y = yInput;
                       pointList.add(xyPoint);

               }
               invalidate();
                return true;
           }
        }

and the onDraw:
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

        for (int i = 0; i < pointList.size(); i++) {
            Point p = pointList.get(i);
            touchCircle.setColor(colorList.get(i));

            canvas.drawCircle(p.x, p.y, touchRadius, touchCircle);
        }
}

I've tried to modify the alpha value of the circles in the ArrayList bar the last element to reflect the fade out, but that causes a stuttering effect rather than a smooth fade out of all the previous points.
Apologies if this question comes across as repetitive, I'd just really appreciate some opinions on how to solve this issue.
Please let me know if there's anything I should clarify either.

A: If you want a smooth fade out, you need to animate using Handlers. The idea is, if you want your fade out to be very smooth, you need to call onDraw() at a very short interval. That's how you will make the fade out smooth. You are facing the stuttering effect because you are not calling onDraw() enough times.
What you need is a Handler and you need to post a Runnable at a very short interval. This way you will invalidate() multiple times and make the fade out as smooth as you want.
If you want to know how to use a Handler, you can google it. I have worked on a Pagination control in which I used this, you could refer this as well: https://github.com/Madrapps/pagination/blob/master/src/main/java/com/instrap/apps/pagination/views/MovingDots.java. This has nothing to do with your use case, but will give you an idea on how to use Handlers and Runnable to perform animations in a custom view.


text:
Q: Where can I find Java 8u241? I am looking for Java 8u241, as it is a requirement for a project I am working on. I have not been able to find it anywhere; not even Java's own website.
Any suggestions?
I appreciate your'alls help!

A: Java 8u241 is not available yet. The latest version of Java 8 available from Oracle is Java 8u231 which you can download from https://java.com/en/download/manual.jsp
Please check https://www.java.com/en/download/faq/release_dates.xml for more details.


text:
Q: Office Web Apps - Edit PDF - WopiFrame: failed to generate iframe URL Our Office Web Apps server seems to cause an error in SharePoint when opening a PDF:

*

*Clicking on the link to the PDF in the Document Library opens "Word Web App" and renders the PDF fine (in read-only mode). The URL Action is "Default":

*Clicking on the "..." ellipsis (ECB/callout) actions menu and then selecting "Open" causes an error. The URL Action is "Edit" which suggests "Word Web App" has an issue with editing a PDF (you'd expect it to give you the prompt to save it as a Word Doc):

The ULS seems to log some strange "Wopi" errors:
09/12/2013 15:19:41.88   w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           WOPI                            ah6ud   Unexpected  Exiting GetWOPITargetInternal Early - GenerateWacUrl failed to produce a URL/actionEntry for file [FILE].pdf with extension 'PDF' StackTrace:   at Microsoft.SharePoint.Utilities.SPWOPIHost.GetWOPITargetInternal(HttpContext httpContext, SPWeb web, Object& spPrimeObject, SPWOPIAction& requestedAction, SPRegionalSettings spSettings, String& wopiAppUrl, String& wopiFavIconUrl, String& wopiAccessToken, Int64& wopiAccessTokenTtl, String& errorMessageToDisplay, String& redirectUrl)     at Microsoft.SharePoint.ApplicationPages.WOPIFrameHelper.OnLoadHelper(WOPIFrame frame)     at Microsoft.SharePoint.ApplicationPages.WOPIFrameHelper.OnLoad(WOPIFrame frame)     at System.Web.UI.Control.LoadRecursive()     at System.Web.UI.Page.ProcessRequestMain(Boolean inc...    922c429c-d091-108c-7801-fd05116e821f
09/12/2013 15:19:41.88* w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           WOPI                            ah6ud   Unexpected  ...ludeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.HttpContext.InvokeCancellableCallback(WaitCallback callback, Object state)     at System.Web.UI.Page.LegacyAsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, Object extraData)     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()     at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)     at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) ...  922c429c-d091-108c-7801-fd05116e821f
09/12/2013 15:19:41.88* w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           WOPI                            ah6ud   Unexpected  ...    at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr ...  922c429c-d091-108c-7801-fd05116e821f
09/12/2013 15:19:41.88* w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           WOPI                            ah6ud   Unexpected  ...nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     922c429c-d091-108c-7801-fd05116e821f
09/12/2013 15:19:41.88  w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           WOPI                            aht19   High        WopiFrame: failed to generate iframe URL.   922c429c-d091-108c-7801-fd05116e821f
09/12/2013 15:19:41.94  w3wp.exe (0x1CD0)                           0x0A00  SharePoint Foundation           Upgrade                         aiaih   High        [Forced due to logging gap, cached @ 09/12/2013 15:19:41.92, Original Level: Verbose] desiredVersion: {0}   922c429c-d091-108c-7801-fd05116e821f
Anyone know how to fix?

Update: there was one possibly related issue I found on the net related to TMG - but I don't think this is the problem (we're inside the firewall and I tried putting an explicit proxy bypass on the server name - which didn't help).

http://video.ch9.ms/sessions/spc/2012/SPC096_Baginski.pptx

A: We raised the issue with Microsoft Support and apparently it's a bug. Will know more soon. In the meantime, the fix is to disable PDF's from being rendered in OWA:
Get-SPWOPIBinding –Application "WordPDF" | Remove-SPWOPIBinding -Confirm:$false
Control whether PDFs open in Word Web App or the default PDF reader
http://blogs.technet.com/b/office_resource_kit/archive/2013/07/24/control-whether-pdfs-open-in-word-web-app-or-the-default-pdf-reader.aspx

A: This bug was fixed in the October 2013 CU: http://support.microsoft.com/kb/2825665

A: On this page, http://www.adobe.com/devnet-docs/acrobatetk/tools/AdminGuide/planning.html, section 3.4.2.5 may help you.

A: If you want to use only the pdf preview in a doc lib and don't care about the opening the pdf in the webapp view you can use the SPwopiBinding -Action "interactivepreview" and remove the default -Action "view".  This will allow the doc preview within the doc lib be clicking the ellipsis and open the pdf in the browser.  Your webapp broswer file handling should be set to "Permissive".  The powershell to remove the SPWopibinding for -Action "view is as follows:
Get-SPwopiBinding -Action "view" -Application "WordPDF" | Remove-SPWopiBinding -Confirm $false


text:
Q: back button close the activity instead of going back to main activity in AndroidManifest.xml I put this
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

In onCreate() method I put this. I didn't override onOptionsItemSelected.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

The problem is when I press the Back button(on the action bar) The activity get closed instead of going back!  Help me to resolve this. Why I go for this method is I can easily place a back button on the left.


text:
Q: Is there an open source live support application using PHP, Jabber and Google Talk I have 2-5 support reps who use Google Apps including Google Talk
I want to provide a "Live Support" option on my web site.
When one or more employees log in to Google Apps the live support option should become available.
Ideally the live support feature should simply enable a 1:1 chat session with a support rep with the ability to add additional support reps.

A: Google offers a way to put Chat badges in your website so it's possible to chat with ONE user, but i've never heard of such thing. At least not open source.
You can see similar functionality in www.olark.com and www.zopim.com

A: There is no open source project, but there is this tutorial to make notification app and chat.
http://www.ibm.com/developerworks/xml/tutorials/x-realtimeXMPPtut/section5.html


text:
Q: A question about triangle inequality in complex plane When does equality hold in the triangle inequality
$$|z_1+z_2+\dots+z_n|\leq|z_1|+|z_2|+\dots+|z_n|$$
Interpret your result geometrically
how to solve this problem i am really don't have please help me with this
for n=2
$|z_1+z_2|^2=|z_1^2+2Re(z_1\overline{z_2)}+|z_2|^2\\
\leq |z_1|^2+2z_1\overline{z_2}+|z_2|^2$
hence $|z_1+z_2|\leq|z_1|+|z_2|$

A: Hint:)
For $n=2$ use ${\bf Re\,}(z_1\overline{z_2})\leqslant|z_1||z_2|$ and by induction prove the general case!
For geometrically result, consider $z_i$ as a vector and see parallelogram rule to obtain geometrically consideration.

here $z=z_1+z_2+z_3+z_4+z_5$.


text:
Q: How to parse a Mbox file with JavaMail API? I want to use JavaMail to parse an .mbox file just like this one http://mail-archives.apache.org/mod_mbox/lucene-java-user/201210.mbox.
What I thought of doing was:
Session session = Session.getDefaultInstance(new Properties());
Store store = session.getStore("Here should go the .mbox file");
store.connect();

Folder folder = store.getFolder(server);
folder.open(Folder.READ_ONLY);
...

Which proved wrong. Any suggestions would be helpful.
Thank you in advance.
Update: Working example
public class MBoxFileReader implements MessageReader {
    private final Path path;  // Path to .mbox file

    public MBoxFileReader(Path path) {
        this.path = path;
    }

    @Override
    public Message[] readMessages() {
        Message[] messages = new Message[0];
        URLName server = new URLName("mbox:" + path.toString());
        Properties props = new Properties();
        props.setProperty("mail.mime.address.strict", "false");
        Session session = Session.getDefaultInstance(props);
        try {
            Folder folder = session.getFolder(server);
            folder.open(Folder.READ_ONLY);
            messages = folder.getMessages();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }
}

A: You can use the JavaMail mbox Store, but you'll need to build it yourself.

A: This can be done with Apache Mime4j:
    CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder();
    final File mbox = new File(mboxPath);

    for (CharBufferWrapper message : MboxIterator.fromFile(mbox).charset(ENCODER.charset()).build()) {
        System.out.println(message);
    }

you'll need:
<dependencies>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.james</groupId>
        <artifactId>apache-mime4j</artifactId>
        <version>0.8.1</version>
        <type>pom</type>
    </dependency>

</dependencies>


text:
Q: How do I fetch cookie data with React? I have a MERN + Passport.js application that is using fetch to make a call to my express API in order to retrieve data stored in a cookie. I have my React frontend routed to localhost:3000, and my backend routed to localhost:3001. My cookies are not being saved, and thus my session is not persisting within my browser. It is not an issue with the express-sessions or passport middleware, as when I use POSTMAN to execute the necessary calls to my API, the cookie is stored and the session persists.
It is only when I attempt to pass this information through/to my front end that things go wrong. I have been stumped for a while and can't seem to find an answer anywhere.
This is the line that I am using to save the cookie:
handleLogin(event) {
        event.preventDefault();
        fetch("http://localhost:3001/users/login", {
            // credentials: 'include',
            credentials: 'same-origin',
            method: "post",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password
            })
        })
        // .then( (response) => response.json())
        .then( (response )=> {
            if(response.message){
                alert(response.message);
            }
        })

Which correctly calls my API, which logs the current session, user data, and cookie.
Upon refreshing and making another request, I lose the cookie (it was never properly stored in the first place I think), and all session data.
This is the get request that I make whenever I navigate to a new page:
componentDidMount(){
        var current_user = "";
        fetch("http://localhost:3001/users/", {
            // credentials: 'include',
            credentials: 'same-origin',
            method: "get",
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/json'
            }
        })
        // .then( (response)=> response.json())
        .then( (response)=> {
            if(response.user){
                current_user = response.user;
                this.setState({
                    user: current_user
                }), ()=> console.log(response);
            }
        })
    }

In response, I get an undefined user and no other response, and the cookie is never stored in my browser. But again, if I do this in POSTMAN, strictly doing the POST request followed by that GET request, the proper user data is returned and the cookie is shown in POSTMAN as well.
Any idea as to why fetch is not passing the cookie information back to my front end? I have tried both credentials: 'include' and credentials: same-origin.
Thank you!

A: It seems like the problem, or at least part of it, is your use of same-origin. From Mozilla docs (italics my own):

omit: Never send cookies.
same-origin: Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. This is the default value.
include: Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls.

The definition of "same origin" does not include different ports.
If you change same-origin to include, fetch should start managing your cookies correctly.
If not - do you know for sure that the cookie is "never stored in the browser"? With Chrome, you can check chrome://settings/siteData.


text:
Q: How to search in a particular column in a Listview? I am trying to adjust a code that I have found on a forum and so far my little tweaks have made the code work for my form. However, I am only allowed to search Column 0 on my listview when I want it to search Column 1 and Column 2 (at least column 1). Does anyone know how to adjust my code so I can search a name in Column 1 and/or column 2? A
Also the line where it starts "Console" has a "Expression expected" issue. How do I end this expression?
Below is my code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim itm As ListViewItem
    Dim i As Integer

    For i = 0 To InstitutionAddContactListView.Items.Count - 1
        itm = InstitutionAddContactListView.SelectedItems(i)
        Console.WriteLine(ContactFirstColumnHeader = {1} ContactLastColumnHeader = {2},itm.SubItems(1),itm.SubItems(2))
        InstitutionAddContactListView.Items(i).Selected = False
        InstitutionAddContactListView.Items(i).BackColor = Color.White
    Next

    With InstitutionAddContactListView
        itm = .FindItemWithText(TextBox1.Text, False, 0, True)

        If Not itm Is Nothing Then
            .Items.Item(itm.Index).BackColor = Color.Blue
            .Items.Item(itm.Index).EnsureVisible()
        Else
            MsgBox("No Record Found!")
            For i = 0 To InstitutionAddContactListView.Items.Count - 1
                InstitutionAddContactListView.Items(i).Selected = False
                InstitutionAddContactListView.Items(i).BackColor = Color.White
            Next
            .Items(0).EnsureVisible()
            .Items.Item(0).BackColor = Color.Blue
            TextBox1.SelectionStart = 0
            TextBox1.Focus()
        End If
    End With
    itm = Nothing
End Sub

A: With InstitutionAddContactListView
        itm = .FindItemWithText(TextBox1.Text, TRUE, 0, True)


text:
Q: Timezone issue: `$ date -R` says `+0300`, but `timezone` says `-7200` Executing $ date -R gives me +0300 BUT when I print the timezone global variable timezone, it shows me -7200.
Ideas what's happeninig?
It looks like the DST is NOT included AND the timezone is sign is different, but why?

A: timezone does not know about D(aylight)S(aving)T(ime) by defintion. Time zones are constant sections on earth all over the year (update: at least their naming was constant during the days Sandford Fleming invented them). So as referring to those by the offset to Greenwich is common, it would not make sense to add the temporary DST offset.

The different sign dues to the different view point and direction of the date/time and timezone.
The offset given by date is referring from where you are to Greenwich.
The timezone  is measured to where you are from Greenwich .

Regarding the C system calls: gettimeofday() provides DST info. (Update: This in not the case for the glibc implementation)

A: according to my man pages timezone is set to

seconds West of GMT

and I would anderstand that like 'the more in the west you are the larger timezone becomes'. So the sign differs from date -R and also DST is not included.
You can use  the struct tm * obtained by localtime() to check whether or not there is actually DST in your environment. If the field tm_isdst > 0 then it is.


text:
Q: Построение элементов в линию HTML CSS JS Почему-то блоки с полями ввода не выстраиваются в линию, хотя их ширина  = 50% и поставил display:inline-block.
Пожалуйста, помогите.
PS: в CSS коде есть лишние классы с прошлого проекта.
HTML:
```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <script src="script.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="container-fluid">
        <div class="header">
            <div class="logo-block">POMODORO TIMER</div>
        </div>
        <div class="content">
            <div class="timer-block">
                <!-- <div class="minuts" id="min" >00</div>
                <div class="razdel">:</div>
                <div class="seconds" id="sec">00</div> -->
                <div class="minInputBlock">
                    <input type="number" class="minInput">
                </div>
                <div class="secInputBlock">
                    <input type="number" class="secInput">
                </div>
            </div>
        </div>
    </div>
</body>
</html>
```

CSS:
@import "http://fonts.fontstorage.com/import/intro.css";
body, html{
    height: 100%;
    box-sizing: border-box;
    display: inline-block;
    overflow-x: hidden;
}
.header{
    width: 100%;
    text-align: center;
    box-sizing: border-box;
}
.logo-block{
    width: 100%;
    height: 100%;
    color: black;
    font-family: Intro, Arial, Helvetica, sans-serif;
    color: #8eca98;
    font-size: calc(1em + 3vw);
    border-radius: border-box;
}
.container-fluid{
    padding: 3%;
}
.content{
    margin: 5% 0% 0% 0%;
    padding: 5%;
    height: 500px;
    box-sizing: content-box;
}
.timer-block{
    position: relative;
    display: inline-block;
    margin-left: 20%;
    font-size: 20px;
    color: #ff9000;
    font-family: Intro, Arial, Arial, Helvetica, sans-serif;
    box-sizing: border-box;
    width: 30%;
    height: 30%;
    box-sizing: content-box;
}
.minSec-block{
    display: inline-block;
}
.minuts{
    position: relative;
    margin-left:0%;
    margin: 0 auto;
    width: 50%;
    left: -20%;
    height: 0%;
    box-sizing: content-box;
    font-size: 20vw;
}
.seconds{
    position: relative;
    display: inline;
    margin-bottom: -100%;
    top: 0%;
    width: 50%;
    height: 100%;
    left: 55%;
    font-size: 20vw;
}
.timer{
    height: 100%;
    width: 100%;
    left: 50%;
    display: inline-block;
    box-sizing: border-box;
    display: inline-block;
}
.razdel{
    position: absolute;
    font-size: 17vw;
    height: 30vw;
    top: 0vw;
    margin-left: 43%;
    width: 3%;
    color: #8eca98;
}
.minInput{
    position:relative;
    display:inline-block;
    color:#ff9000;
    font-size: 10vw;
    border-radius: 7%;
    border: 1vw solid #8eca98;
    height: 10vw;
    width: 50%;
}
.minInputBlock, .secInputBlock{
    width: 50%;
}
.secInput{
    position:relative;
    display:inline-block;
    color:#ff9000;
    font-size: 10vw;
    border-radius: 7%;
    border: 1vw solid #8eca98;
    height: 10vw;
    width: 50%;
}


text:
Q: Arrayformula (google sheets) in Excel 2007 Is there a way to use Arrayformula function as used in google sheets in Excel?
For example:
 A     B

1|  23
2|  45
3|  56
If I'll write in b1 =Arrayformula(A1:A3*2)
I'll get
 A     B

1|  23 | 46
2|  45 | 90
3|  56 | 112
How can I get same result on Excel 2007 using 1 formula (without dragging/ copying/ double clicking)
Thanks ahead!

A: Select the range were you want the answers.
In your example select range "B1:B3"
type =A1:A3*2
Now the trick is press Ctrl + Shift + Enter instead of Enter.

PS: Ctrl + Shift + Enter makes the formula as an arrayformula

A: Just highlight the range B1:B3 and enter your formula
=A1:A3*2

followed by  Ctrl   Shift   Enter
Note that the formula will be 'locked in' to B1:B3 and you won't be able to change an individual cell in the range without changing the other cells.

A: Not an array formula, but could be a good solution- put your data into a table on excel by selecting it and pressing Ctrl + L (excel will size the table to cover the cells with data).
Then enter your formula in the column just to the right, the table will expand to include it and the formula will be repeated for every row in the table.
If you add an extra row the formula will be automatically updated too.
(I would note that you need excel 2006+ to have this feature, it's one of my favourites)