text:
Q: add a tab to facebook page programmatically I have a site that hosts music (stereokiller.com) - a sample band page would be http://www.stereokiller.com/rapture .
I am attempting to create a facebook application that will insert a new tab into a user's band page on facebook loaded with the player and some other information from my site. However, i'm not sure how to pass the iframe app any parameters to determine which band information to show? I'm aware of the FB_SIG_PAGE_ID which I could then get the owner page name from the Graph API, but if there are multiple bands on my site with the same name then we could have issues.

[solved]
I figured it out.
do an http call to graph.facebook.com/me/accounts?access_token={access token}. loop through results with the access token retrieved through the prior call, then do http post to graph.facebook.com/{PAGE_ID}/tabs with the form param {app_id} for the app of which you want to add.

A: You can install a profile_tab at the end of the current list of installed tabs for a page by issuing an HTTP POST request to PAGE_ID/tabs with a Page Access Token:
Parameter   Description                                             Type    Required
app_id          ID of the application for which to install the tab.     string  Y
If the create is successful, you get the following return:
Description                 Type
If the create succeeded     boolean


text:
Q: How to know the number of contacts per Business Unit? I am on a multi org instance.
From the Parent BU, I would like to know the number of contacts per child business unit.
For the moment, I have not found a solution other than filtering on the attribute.
Is there any other way to know the distribution of my contacts?
Thanks
Davy_C

A: Unfortunately, there isn't a great way to do this. You would have to build a custom solution for when your subscribers entered, appending an attribute to their record upon entry. You could then build a table to match back to their SubscriberID. This isn't a perfect solution, because it would only capture when a customer first entered a particular business unit, and wouldn't account for being in Multiple BUs. For example, if I have multiple BUs with overlapping subscribers, they technically could be attributable to either BU.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET Core WebApplication IIS Express Error IIS Express server is not starting and throwing the following error.

The following error occurred when trying to configure IIS Express for project <project_name>.
Filename : redirection.config
Error: cannot read configuration file

I have reinstalled IIS Express server, removed and installed all the packages and even repaired visual studio. But nothing worked.
I removed .VS folder, even this didn't worked :-(.

A: I got the fix, I don't know how my %userprofile% directory has two Documents named folder. Really Strange. I have no idea why there were two folders with exact name "Documents".I copied IISExpress and Mysites folders from Second Documents Folder to First Documents folder, And it worked.
Edit:
Those Documents folders were actually not in same folder there were in

*

*C:\Users\<username>\Documents

*C:\Users\<username>\OneDrive\Documents


text:
Q: jquery-ui sortable placeholder wrong position I need to sort bootstrap blocks and I have some problems with placeholder.
$('.buildBlockContainer').sortable({
  handle: '.sortableHandler',
  connectWith: '.buildBlockContainer',
  cancel: '',
  placeholder: 'buildBlockPlaceholder',
  start: function(e, ui) {
    ui.placeholder.height(ui.item.height());
    ui.placeholder.width(ui.item.width());
  }
});

Full example here: https://jsfiddle.net/ShinShil/74grstLs/

A: Firstly placeholder must have the same float, position and display styles as item.
Secondary the width of bootstrap cols have paddings and they not in width, but in offsetWidth: ui.placeholder.width(ui.item[0].offsetWidth)
complete example https://jsfiddle.net/ShinShil/0d22bo83/5/


text:
Q: Sprites optimized for retina display I'm building a responsive website so I've been reading about css sprites on mobile devices and iphones. I found this article, I think it's the right tecnique but the explanation could've been better. I ended up with this:
http://jsfiddle.net/H9FcH/
Can somebody tell me if it looks ok on the iphone? I'm not sure about that 50%.
Also, does anyone have a better article?

A: The background-size property you specify for Retine enabled devices, should contain the size of the non-Retina sprite, i.e., half the width and half the height of the Retina sprite. It should be the size of the total sprite, so not just the size of a single icon within the sprite.
Updated Fiddle: http://jsfiddle.net/jhogervorst/qr5fs/2/
Screenshot (Retina): http://i.stack.imgur.com/sIDnE.png
CSS:
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (min--moz-device-pixel-ratio: 1.5),
       only screen and (min-resolution: 240dpi) {
        .action {
            background-image: url(http://dl.dropbox.com/u/13823768/masonry/img/test-sprite2x.png);
            -moz-background-size: 153px 64px;
            -o-background-size: 153px 64px;
            -webkit-background-size: 153px 64px;
            background-size: 153px 64px;
        }
}


text:
Q: Vlookup only display first two rows in a table I have a cell that has a list data validation type with 5 options. I am using vlookup to search a table, find that selected option and then display the results. However, when i pick option 3-5, the results do not change.
This is what I am using for the vlookup.
=IFERROR(VLOOKUP(C13,Veggies,2)*D13, "")

In a second case where i have the same setup, it will only display the first row in the table as results even if i select other options.


text:
Q: partial update to dataframe with Multi-index index with integer labels I am using multi index dataframe with mixed index labels i.e. first level contains string labels, 2nd and 3rd level are integer labels and 4th level labels are dates.
Dataframe looks like below (master_df)
                                           X1   X2  X3
bucket       Start    Stop       Date
B1             1       1         1/3/2000   2   2   3
                                 1/4/2000   4   3   3
B1             1       2         1/3/2000   4   2   3
                                 1/4/2000   6   2   2

I want to take out sub_df as master_df.ix['B1',1,2,:], do some operations on sub_df and store it back into master_df at the same location. I am able to take out sub_df using various methods, but when comes to storing it back, all the options I have tried dont seem to be working. I guess this issue is related to having 'Integer' labels(at 2nd and 3rd lavel - start-stop). I have tried below options/methods without any success
    sub_df = master_df.ix['B1'].ix[1].ix[2]

    #do some operations on sub_df

    master_df.xs('B1').xs(1).xs(2).update(sub_df)

    master_df.ix['B1'].ix[1].ix[2].update(sub_df)

    merge(master_df.ix['B1',1,2,:],sub_df)

none of the above operations reflect changes in master_df (i dont get any error messages either.)
Can you suggest proper way to do it?
Update :
sub_df and master_df do not have same index as operations on sub_df expect date index only.
sub_df look like below.
          X1   X2  X3
Date
1/3/2000   2   2   3
1/4/2000   4   3   3

If I try
sub_df = master_df[master_df.index.get_loc(('B1', 1, 2))]

I get following error -
TypeError: unhashable type: 'numpy.ndarray'
Main purpose here is to operate on only small chunk of master_df and store those results back at original location in master_df. I tried using update method, however any other alternative to achive this purpose will do.

A: This doesn't exactly solve your question, but I this might
provide some inspiration
Here's a way to set the values directly
In [75]: df
Out[75]:
  bucket  start  stop                date  x1  x2  x3
0     B1      1     1 2000-10-03 00:00:00   2   2   3
1     B1      1     1 2000-01-04 00:00:00   4   3   3
2     B1      1     2 2000-01-03 00:00:00   4   2   3
3     B1      1     2 2000-01-04 00:00:00   6   2   2

In [76]: df2 = df.set_index(['bucket','start','stop'])

In [77]: df2
Out[77]:
                                 date  x1  x2  x3
bucket start stop
B1     1     1    2000-10-03 00:00:00   2   2   3
             1    2000-01-04 00:00:00   4   3   3
             2    2000-01-03 00:00:00   4   2   3
             2    2000-01-04 00:00:00   6   2   2

In [78]: df2.ix[('B1',1,2)].ix[:,'x1'] = 5

In [79]: df2
Out[79]:
                                 date  x1  x2  x3
bucket start stop
B1     1     1    2000-10-03 00:00:00   2   2   3
             1    2000-01-04 00:00:00   4   3   3
             2    2000-01-03 00:00:00   5   2   3
             2    2000-01-04 00:00:00   5   2   2

Here's another way, where you select out a series that has a multi-index, modify it,
then assign it back (only works with series).
In [89]: df2.ix[:,'x1']
Out[89]:
bucket  start  stop
B1      1      1       2
               1       4
               2       4
               2       6
Name: x1, dtype: int64

In [90]: new_s = df2.ix[:,'x1'].copy()

In [91]: new_s
Out[91]:
bucket  start  stop
B1      1      1       2
               1       4
               2       4
               2       6
Name: x1, dtype: int64

# can also do a more complicated selctor than the 0th row
In [92]: new_s[0] = 5

In [93]: new_s
Out[93]:
bucket  start  stop
B1      1      1       5
               1       4
               2       4
               2       6
Name: x1, dtype: int64

In [94]: df2.ix[:,'x1'] = new_s

In [95]: df2
Out[95]:
                                 date  x1  x2  x3
bucket start stop
B1     1     1    2000-10-03 00:00:00   5   2   3
             1    2000-01-04 00:00:00   4   3   3
             2    2000-01-03 00:00:00   4   2   3
             2    2000-01-04 00:00:00   6   2   2

Here's what you can do in 0.11
# this is sessentially saying give me the first 2 rows (equivalent
# to selecting via complicated tuple)
In [107]: df2.iloc[0:2,:]
Out[107]:
                                 date  x1  x2  x3
bucket start stop
B1     1     1    2000-10-03 00:00:00  10   2   3
             1    2000-01-04 00:00:00   4   3   3

In [108]: df2.iloc[0:2,:].loc[:,'x1']
Out[108]:
bucket  start  stop
B1      1      1       10
               1        4
Name: x1, dtype: int64

In [109]: df2.iloc[0:2,:].loc[:,'x1'] = 5

In [110]: df2
Out[110]:
                                 date  x1  x2  x3
bucket start stop
B1     1     1    2000-10-03 00:00:00   5   2   3
             1    2000-01-04 00:00:00   5   3   3
             2    2000-01-03 00:00:00   4   2   3
             2    2000-01-04 00:00:00   6   2   2

A: It's important that sub_df has the same index as master_df.
One way to get the correct index is to use get_loc:
sub_df = df[df.index.get_loc(('B1', 1, 2))]
# operations not changing index
master_df.update(sub_df)

A: Thanks all for the help. At the end I switched to charater indexing from number indexing at level 2 and 3, and now things are working fine (this also helped in doing propering sorting on levels, which is i suppose made things more unambiguous.)

A: For the example you give (selecting ('B1', 1, 2, ...)) you can use xs iso ix. In contrast to ix, xs can return a view on the data when using labels (more details on ix returning view/copy see docs).
In the example below, colum X1 of sub_df is changes, which also impacts master_df.
In [48]: master_df
Out[48]:
                              X1  X2  X3
bucket Start Stop Date
B1     1     1    2000-01-03   2   2   3
                  2000-01-04   4   3   3
             2    2000-01-03   4   2   3
                  2000-01-04   6   2   2

In [49]: sub_df = master_df.xs(['B1', 1, 2], copy=False)

In [50]: sub_df
Out[50]:
            X1  X2  X3
Date
2000-01-03   4   2   3
2000-01-04   6   2   2

In [51]: sub_df.X1 -= 4

In [52]: sub_df
Out[52]:
            X1  X2  X3
Date
2000-01-03   0   2   3
2000-01-04   2   2   2

In [53]: master_df
Out[53]:
                              X1  X2  X3
bucket Start Stop Date
B1     1     1    2000-01-03   2   2   3
                  2000-01-04   4   3   3
             2    2000-01-03   0   2   3
                  2000-01-04   2   2   2

A: In 0.13 parameter 'drop_level' has been added to 'xs' so that will solve your problem as all index levels will be present in sub_df:
sub_df = master_df.xs(['B1', 1, 2], level=['bucket','Start','Stop'], drop_level=False)
Now merge will work.
Have not tried but it should work.
ref: "Large data" work flows using pandas


text:
Q: How do you create a SQL expression to calculate the total of multiple data fields? I am trying to add the final data fields in each row of a list report.  These data fields tally the number of hours worked by an applicant.  The desired result is that the expression displays a total of 442 hours.  This is due to the fact that the first field value is 420 hours and the second field value is 22 hours.  The other field values are zero.  In the first example below, the report generates a concatenation of the characters, 420220000.
=Fields!EstHrsTotal1.Value+Fields!EstHrsTotal2.Value+Fields!EstHrsTotal3.Value+Fields!EstHrsTotal4.Value+Fields!EstHrsTotal5.Value+Fields!EstHrsTotal6.Value
In the second example, using the SUM operator results in #Error in the report.
=SUM(Fields!EstHrsTotal1.Value+Fields!EstHrsTotal2.Value+Fields!EstHrsTotal3.Value+Fields!EstHrsTotal4.Value+Fields!EstHrsTotal5.Value+Fields!EstHrsTotal6.Value)
What is the correct method to caculate the sum of the total values for these six data fields?

A: It looks like your EstHrsTotal values are strings. You'll need to convert them to integer (or decimal if you will need to account for fractions of hours). You can do this in the sql or in the SSRS Report:
SQL:
select
    cast(EstHrsTotal1 as int) EstHrsTotal1,
    cast(EstHrsTotal2 as int) EstHrsTotal2,
    cast(EstHrsTotal3 as int) EstHrsTotal3,
    cast(EstHrsTotal4 as int) EstHrsTotal4,
    cast(EstHrsTotal5 as int) EstHrsTotal5,
    cast(EstHrsTotal6 as int) EstHrsTotal6
from dbo.YourTable

SSRS Report:

=CInt(Fields!EstHrsTotal1.Value)+CInt(Fields!EstHrsTotal2.Value)+CInt(Fields!EstHrsTotal3.Value)+CInt(Fields!EstHrsTotal4.Value)+CInt(Fields!EstHrsTotal5.Value)+CInt(Fields!EstHrsTotal6.Value)


text:
Q: How to downgrade iPad 2 from iOS 5.1 to 5.0 for development I am developing an Application for iPad (iOS)on Xcode 4.2 on MAC OS X 10.6.5 i.e snow leopard and apple has not released sdk for ios 5.1 for snow leopard.
i was using my iPad for testing it was working great with ios 5.0.1.
i just recently upgrade iPad to 5.1 and now i am unable to deploy code on iPad , i checked the registration of my device for development on development.apple.com and its still exist.
i even checked in Organizer-Devices and in that window it show me following message :
The version of iOS on "My iPad" does not match any of the versions of iOS supported for development with this installation of the iOS SDK. Please restore the device to a version of the OS listed below, or update to the latest version of the iOS SDK; which is available here.

OS Installed on My iPad
5.1.1 (9B206)

Xcode Supported iOS Versions
Latest
5.0 (9A334)
4.3 (8F190)
4.3
4.2

can anybody help me with this.
Thanks in advance.

A: Click on your project name in the left top, then on your target, and then click on the "build settings" tab
In all the option there is a "iOS deployment target" i think this is what you want ^^

A: I had the same issue. Turns out you have to download/install the newest version of Xcode from the App Store.
https://developer.apple.com/devcenter/ios/checklist/


text:
Q: SDL unicode keyboard input: filter none character inputs I'm using this code to to determine keyboard inputs as unicode character:
while(SDL_PollEvent(&event))
{
    switch (event.type)
    {
        case SDL_KEYDOWN:
        {
            SDL_KeyboardEvent* keyboard = (reinterpret_cast<SDL_KeyboardEvent*> (&event));

            //unicode input
            std::cout << (int)keyboard->keysym.unicode << std::endl;

            //conversion
            ...

            break;
        }
    }
}

My problem is that keysym.unicode has also a value if I would only press the Shift-key (printed value is 1249).
But I only need valid unicode-charactars (e.g.: pressing Shift+A)
Any hints?

A: I fixed it using: SDL_StartTextInput(); to enable textinput-events with:
SDL_TEXTINPUT-event instead of SDL_KEYDOWN is working fine.


text:
Q: Show sheet when the main window first loads I am trying to get a sheet to load when the main window first loads.
This sheet is so that it asks the user for a file so that they are sort of forced to open a file for use in the program when they first start.
I tried to put performSegue(withIdentifier: sender:) in viewDidLoad(), however it just loads the sheet and nothing else.
override func viewDidLoad() {
    super.viewDidLoad()
    performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "browse"), sender: self)
}

I want the main window to load, then the sheet to slide down immediately after asking the user to open a file.
Where should I put the performSegue or is there another way I should be doing this?

A: @mschmidt is right, I believe; you'll need to perform the segue from viewDidAppear() or windowDidBecomeMain() or similar; the view needs to have been displayed before you can segue from it.
Note that viewDidAppear() will fire when the view is drawn, whether or not it has focus; windowDidBecomeMain() will only fire when your app becomes the frontmost app; you may be working in another app but still be able to see your app's windows on-screen, and in this state windowDidBecomeMain() may not have fired yet.
And yes, both viewDidAppear() and windowDidBecomeMain() will fire every time the view appears or the window becomes main, meaning if you minimise the app then un-minimise it, both will fire again. So you'll need some way of ensuring your segue doesn't show again each time, unless you want it to. A simple boolean flag eg segueHasShown should achieve that.


text:
Q: Python Import Class With Same Name as Directory Lets say I have the following python source file layout:
lib/foo.py
lib/foo/bar.py

and then in my source code:
from foo import gaz

I get an import error:
ImportError: No module named foo

How can I have a .py file and a directory with the same name so I can do the following:
 from foo import gaz
 from foo.bar import wakawaka

A: I'm pretty sure this is not something you should do, but you can force Python to import specific file as a module using imp:
import imp

with open("foo.py") as source:
    foo = imp.load_module("foo", source, "./", ('', '', imp.PY_SOURCE))

now you can do:
gaz_instance = foo.gaz()

A: The actual problem you are having, using a single import, is due to the packages having the precedence over modules:

Note that when using from package import item, the item can be either
  a submodule (or subpackage) of the package, or some other name defined
  in the package, like a function, class or variable. The import
  statement first tests whether the item is defined in the package; if
  not, it assumes it is a module and attempts to load it. If it fails to
  find it, an ImportError exception is raised.

Anyway I'd strongly suggest to rename the file or the directory since you cannot import more than one module with a given name. The problem occurs because each module/package object is stored into sys.modules, which is a simple dict and thus it cannot contain multiple equal keys.
In particular, assuming foo.py and the foo directory are in different directories(and if they aren't you still can't import foo.py), when doing:
from foo import gaz

It will load foo.py and put the module into sys.modules, then trying to do:
from foo.bar import wakaka

Will fail because the import tries to use the module foo.py instead of the package.
The opposite happens if you first import foo.bar; the imports will use the package instead of the module.


text:
Q: Error with Android View Binding library after updating Android Studio to 4.0 Last night I upgrade my Android Studio 4.0, it shows error in View Binding. I have tried the below code in my Gradle. But it shows error like this,
Could not find method buildFeatures() for arguments [build_99kmfmmumw2bmow3xjrnbxlx1$_run_closure1$_closure5@4155ecc3] on extension 'android' of type com.android.build.gradle.internal.dsl.BaseAppModuleExtension.

android {
   buildFeatures {
       viewBinding = true
   }
}

A: Try with:
dataBinding{
    enabled = true
}


text:
Q: Nuxt.js auth middleware problems I have created admin dashboard for one client. Project is created using Vue.js with Nuxt.js. Backend is Directus and it was created by my colleague.
Problem is that auth middleware is not working as I need.
When I log in, I save AUTH_TOKEN and REFRESH_TOKEN in cookies. Then, I am firing up one API call, if response.message is: 'Token expired', I send new API call with REFRESH_TOKEN to refresh. Then, from response I save new REFRESH_TOKEN and new AUTH_TOKEN to cookies again and if response is not 200, I redirect user to /login.
Here is my code (/middleware/authenticated.js):
import authService from '../services/authService';

export default function ({ $cookies, redirect, store, $toast, $router }) {
      const access_token = $cookies.get('access_token');
      const refresh_token = $cookies.get('refresh_token');

      if (!access_token) {
        $cookies.remove('access_token');
        $cookies.remove('refresh_token');
        store.commit('RESET_USER');
        return redirect('/login');
      }
      if(access_token){
        store.commit('SET_USER');
        setInterval(function(){
          try{
              authService.retrieveCurrentUser({headers: {
                "Content-type": "application/json",
                "Authorization": `Bearer ${access_token}`,
              }})
                .then(() => {
                  console.log('ok');
                })
                .catch ((error) => {
                  console.log('prvy catch error', error);
                  if(error.response.data.errors[0].message == 'Token expired.'){
                    const config = {
                        "refresh_token": refresh_token
                    }
                    authService.refreshToken(config)
                    .then((response) => {
                      $cookies.set('access_token', response.data.data.access_token);
                      $cookies.set('refresh_token', response.data.data.refresh_token);
                      store.commit('SET_USER');
                      return redirect();
                    })
                    .catch((err) => {
                      console.log('druhy catch error', err);
                      $cookies.remove('access_token');
                      $cookies.remove('refresh_token');
                      store.commit('RESET_USER');
                      $toast.error('Platnosť vášho prihlásenia vypršala, prihláste sa prosím znova.', { timeout: 5000 });
                      clearInterval(this);
                      return redirect('/login');
                    })
                  }
                })
              }
              catch (err){
                console.log('treti catch error', err);
                $cookies.remove('access_token');
                $cookies.remove('refresh_token');
                store.commit('RESET_USER');
                $toast.error('Platnosť vášho prihlásenia vypršala, prihláste sa prosím znova.', { timeout: 5000 });
                clearInterval(this);
                return redirect('/login');
              }
      }, 300000)
    }
};

Here is authService:
import api from '@/services/api';

export default {
    login (credentials){
        return api().post('/auth/login', credentials);
    },
    refreshToken(config) {
        return api().post('/auth/refresh', config);
    },
    logout (refresh_token){
        return api().post('/auth/logout', refresh_token);
    },
    retrieveCurrentUser(refresh_token){
        return api().get('/users/me', refresh_token);
    }
};

And this is how I call middleware inside page:
middleware: 'authenticated',

Also I need that setInterval because I want to check if token is still valid every 5 minutes.
When I use this code, I am receiving automatic log outs, or spamming of that toast notification.


text:
Q: What is the most popular reporting services solution available Are there any alternative to the reporting services from sql server?
I could not find any thing online of production use. Need the experts to answer here . Would love it, if sarcasm did not seep in
There is a team who is running a solution where they are running in to multiple security issues due to the setup where reporting server database is in a separate machine and the reporting service is in another machine. I am not asking for any fixes but rather what would be a viable alternative to sql-server in the industry today which allows the following in a Windows environment

*

*Domain joined users to login

*scaled deployment of servers

*SSL security for the report managers

A: Reporting services in Sharepoint integration mode is the pushed solution from Microsoft.
But reporting services in standalone mode on a separate machine works perfectly, if you have basic knowledge of IIS.
Or I can fix it for you through tse.
cheers.


text:
Q: Unable to retrieve a cached piece of information that was saved with Laravel app, but trying to get within a phalcon app I am trying to save a string with one application to memcached.  And then after an http redirect, trying to retrieve that information from a different application on the same server. I am able to save, but retrieving the information is not working.
I have made sure that both applications are not applying a prefix to the cache key. I have run 'memcached-tool localhost:11211 dump | less' on the memcache server to ensure the data exists, which it does.  I can access the data from the same application that saves the data. So if I save from the Laravel app, I can retrieve from the laravel app, and vice versa for the phalcon app.
The environment variables used are the same in both apps.
Setup in Laravel (cache.php):
'memcached' => [
            'driver' => 'memcached',
            'servers' => [
                [
                    'host' => env('MEMCACHED_HOST', '127.0.0.1'),
                    'port' => env('MEMCACHED_PORT', 11211),
                    'weight' => 0,
                ],
            ],
        ],

How I am saving in Laravel:
Cache::put($sha, $viewData, 60);
return redirect("someUrl/{$sha}", 302);

Setup in Phalcon:
$di->setShared('memcached', function(){
    // Cache data for one hour
    $frontCache = new \Phalcon\Cache\Frontend\Data(
        [
            'lifetime' => 60,
            'prefix' => ''
        ]
    );

// Create the component that will cache 'Data' to a 'Memcached' backend
// Memcached connection settings
    return new \Phalcon\Cache\Backend\Libmemcached(
        $frontCache,
        [
            'prefix' => '',
            'servers' => [
                [
                    'host'   => MEMCACHED_SERVER,
                    'port'   => MEMCACHED_PORT,
                    'weight' => 0,
                ]
            ]
        ]
    );
});

How I am trying to retrieve info in Phalcon:
$cache = $this->di->getShared('memcached');
$info = $cache->get($cacheKey);

Here is the output of the $cache var from xdebug:
Phalcon\Cache\Backend\Libmemcached::__set_state(array(
   '_frontend' =>
  Phalcon\Cache\Frontend\Data::__set_state(array(
     '_frontendOptions' =>
    array (
      'lifetime' => 60,
      'prefix' => '',
    ),
  )),
   '_options' =>
  array (
    'prefix' => '',
    'servers' =>
    array (
      0 =>
      array (
        'host' => 'servername',
        'port' => port,
        'weight' => 0,
      ),
    ),
    'statsKey' => '',
  ),
   '_prefix' => '',
   '_lastKey' => '38404efbc4fb72ca9cd2963d1e811e95fe76960b',
   '_lastLifetime' => NULL,
   '_fresh' => false,
   '_started' => false,
   '_memcache' =>
  Memcached::__set_state(array(
  )),
))

And here is the dump from memcached-tool:
Dumping memcache contents
add 38404efbc4fb72ca9cd2963d1e811e95fe76960b 4 1562346522 144
a:5:{s:3:"zip";s:0:"";s:10:"first_name";s:5:"Clint";s:9:"last_name";s:9:"Broadhead";s:5:"phone";s:0:"";s:5:"email";s:20:"blah@blah.com";}

I expected to be able to save to memcache from any application and then retrieve that cache from anywhere else that has access to the same server.  But when I try to retrieve in the phalcon app I receive 'null'.  Even though I can see the key/value pair on the server.  Thanks in advance for your assistance.

A: I bypassed using Phalcons built-in backend and frontend classes and just went with using the PHP ext-memcached on the phalcon app.
$di->setShared('memcached', function(){
if( !($this->_memcache instanceof \Memcached) ){
    if( !class_exists('Memcached') ){
        throw new CacheException('Unable to connect to cache');
    }
    $this->_memcache = new \Memcached();
    $this->_memcache->addServer(MEMCACHE_SERVER, MEMCACHE_PORT)
    return $this->_memcache;
}
});

I started to go down the path of phalcons use of '_PHCM', but once the above solution worked I abandoned that research. Not the best, but works well for my temporary situation.

A: Phalcon uses prefixes for all cache keys by default. For the Libmemcached adapter
For instance the get for the Libmemcached adapter has:
let prefixedKey = this->_prefix . keyName;
let this->_lastKey = prefixedKey;
let cachedContent = memcache->get(prefixedKey);

https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/cache/backend/libmemcached.zep#L160
Just make sure that there are no prefixes by setting the prefix option in your options
$di->setShared('memcached', function(){
    // Cache data for one hour
    $frontCache = new \Phalcon\Cache\Frontend\Data(
        [
            'lifetime' => 60,
        ]
    );

    // Create the component that will cache 'Data' to a 'Memcached' backend
    // Memcached connection settings
    return new \Phalcon\Cache\Backend\Libmemcached(
        $frontCache,
        [
            'prefix'  => '',
            'servers' => [
                [
                    'host'   => MEMCACHED_SERVER,
                    'port'   => MEMCACHED_PORT,
                    'weight' => 0,
                ]
            ]
        ]
    );
});

https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/cache/backend.zep#L59
Finally if the above does not work, install a utility that will allow you to query your Memcached instance and see what keys are stored there. Check it before you store data with Laravel and then afterwards. This way you will know whether you check the correct thing or not.
Alternatively you can use good old telnet if you are comfortable with the command line to check the keys.


text:
Q: Ant using waitfor to run task until a porperty is set I'm running the following code:
 <target name="_queryForRunningJobs">
   <ac:trycatch property="NODE_Reboot.failed">
     <try>

       <queryForRunningJob action="queryForRunningJob" jenkinsbaseURL="${targetRSSURL}" property="isRunningJobs" ignoreJobsLike="${ignore.jobs.like}"/>
       <echo message="${isRunningJobs}"/>
       <fail message="There is at least one job currently running on ${targetRSSURL}">
         <condition>
           <isset property="isRunningJobs"/>
         </condition>
       </fail>
     </try>

     <catch>
       <echo message="NODE_Reboot EXCEPTION: ${NODE_Reboot.failed}"/>
       <property name="reboot.failed.execution" value="${NODE_Reboot.failed"/>
       <ac:var name="isRunningJobs" unset="true"/>
     </catch>

     <finally>
     </finally>
  </ac:trycatch>
</target>

I'd like to change the try block so that queryForRunningJob happens every hour for say 6 hours until isRunningJobs is NOT set, if it is I unset it and wait an hour.
I've been trying to use waitFor, but I can't get it to run the custom task and also check that the property is not set.
Does anyone know how to do this?

A: You can use the not and isset conditions in the waitfor to make sure the variable is unset.
As for checking whether isRunningJobs is set or not, you can create a separate thread using parallel.


text:
Q: Why one code is giving tle while I think the other one which is same is only taking 15ms in online coding platform This is the code which is giving tle. I am using a 3d matrix for solving a problem through memoization.
class Solution {
    public:

         int dp[1001][2][101];

         int find(vector<int> nums, int k, int i, bool flag){
           if(i>=nums.size() || k==0)return 0;
           if(dp[i][flag][k]!=-1)return dp[i][flag][k];

           if(flag){
               return dp[i][flag][k]=max(-nums[i]+find(nums, k, i+1, !flag), find(nums, k, i+1, flag));
           }
             else{
                 return dp[i][flag][k]=max(nums[i]+find(nums, k-1, i+1, !flag), find(nums, k, i+1, flag));
             }
        }
        int maxProfit(int k, vector<int>& prices) {
            if(2*k>prices.size()){
                int res = 0;
                for (int i = 1; i < prices.size(); i++) {
                    res += max(0, prices[i] - prices[i - 1]);
                }
                return res;
            }
           memset(dp, -1, sizeof(dp));
           return find(prices, k, 0, 1);
        }
    };

While this is the code which is only taking 15ms time. is getting accepted.
class Solution {
public:
   int find(vector<int> &prices,int ind,bool buy,int c,int k,vector<vector<vector<int>>> &memo)
    {
        if(ind>=prices.size()||c>=k) return 0; //counter

        else if(memo[ind][buy][c]!=-1) return memo[ind][buy][c];

        if(buy)
        {
        return memo[ind][buy][c]=max(-prices[ind]+find(prices,ind+1,!buy,c,k,memo),find(prices,ind+1,buy,c,k,memo));
        }
        else
        {
        return memo[ind][buy][c]=max(prices[ind]+find(prices,ind+1,!buy,c+1,k,memo),find(prices,ind+1,buy,c,k,memo));
        }

    }
    int maxProfit(int k, vector<int>& prices) {
        if (2 * k > prices.size()) {
             int res = 0;
             for (int i = 1; i < prices.size(); i++) {
                 res += max(0, prices[i] - prices[i - 1]);
             }
             return res;
         }

        vector<vector<vector<int>>> memo(prices.size()+1,vector<vector<int>>(2,vector<int>(k+1,-1)));
        return find(prices,0,1,0,k,memo);
    }
};

While both are doing the same job but the first one is getting tle while the other one is getting accepted with great time complexity. I want to know the reason. BTW the question is Best time to Buy or Sell stock 4.

A: You need to learn the basics of debugging.
First, you need to learn commenting. Each function needs a comment that specifies precisely what the function is supposed to do. Especially here, where at least one function doesn't do what it's supposed to do, so I can't look at the source code.
Then debugging. Put some variables static long count1, count2, etc. into your code. At strategic places, increment those variables and print them. Then you know how often which steps are executed. If one code executes a lot more steps you can figure out why that is.


text:
Q: Performance loss when using HashMap.put method in SSJS In my XPages applications I frequently use SSJS objects (com.ibm.jscript.std.ObjectObject) to cache data. To check if the performance improves if I use java.util.HashMaps instead, I benchmarked the execution times of the following code snippets (SSJS):

All three code snippets do the same: they create and fill either a SSJS Object or a HashMap with different types of data / objects. For each of the snippets I measured the average execution times over 1000 runs, with n (=maximum loop index in the snippet) being 1000000 (1 million). The benchmarks were performed on a Domino 9.0.1 server using java.lang.System.nanoTime .
The ratios of the execution times are as follows:

*

*154% for T[HashMap] / T[SSJS Object]

*266% for T[HashMap with put method] / T[SSJS Object]

*172% for T[HashMap with put method] / T[HashMap]

In other words:

*

*filling a HashMap took ~54% longer than filling a SSJS object

*filling a HashMap using the put method took ~166% longer than filling a SSJS object

*filling a HashMap using the put method took ~72% longer than filling a HashMap using the SSJS "." notation
My questions are as follows:

*

*I frequently see SSJS code where HashMaps are used to store data.
Why not use the standard SSJS objects if they provide better
performance?

*Why is it so much more inefficient to use the put
method instead of the SSJS "." notation to set the value of a
HashMap?

A: Looking at your code (you should put code there, not an image), you are comparing apples and oranges.
  oo = {};

initializes the JS object once, in the second loop it overwrites the existing object.
 hw = new HashMap();

generates a new object each time and throws the old one to the garbage collector. That will be slower.
Your conclusion: "Filling a Hashmap took xx longer" is not supported by your data. The code you wrote supports "Creating and discarding HashMaps in quick sequence is slower".
If you want to run a reasonable test you need to:

*

*Create ONE object (that's the usual use case) and put "a lot of things" into it and to get real ideas: put 100,000 things in. Then read 100,000, then update 100,000 things.

The main reason for HashMaps: you can use them in Java too and you can't accidentally add functionality to them as you can with a JavaScript object. The dot vs. put conversion is due to the different type conversion mechanism.


text:
Q: iptables - NAT/PAT rules for HTTPS, HTTP, RDP, SSH I'm trying to set up a gateway/router box and can't seem to get my iptables quite right.  The goal is to have a private network of windows boxes that can talk to WAN for HTTPS, HTTP, and SSH.  I want RDP open for talking to the windows machines from the gateway box, but don't want to do any port forwarding for that from WAN.
Right now I do NAT between my network cards with masquerading, my WAN interface is eth0, and my LAN is eth1.  I can ssh into the box just fine,  however I can't RDP to my machines on the private network, or get HTTP/HTTPS.  The logs say I'm dropping packets with destination port 80/443 when I try to connect to google from the router box.
Currently what I've been trying is:
# Flushing all rules
iptables -F
# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
# Allow unlimited traffic on loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# set up nat
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
# allow DNS lookup
for ip in $DNS
do
    echo "Allowing DNS lookups to server '$ip'"
    iptables -A OUTPUT -p udp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
    iptables -A INPUT  -p udp -s $ip --sport 53 -m state --state ESTABLISHED     -j ACCEPT
    iptables -A OUTPUT -p tcp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
    iptables -A INPUT  -p tcp -s $ip --sport 53 -m state --state ESTABLISHED     -j ACCEPT
done
# allow http/https, ssh
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -o eth0 -p tcp -m multiport --dports 80,443 -m state --state RELATED,ESTABLISHED -j ACCEPT
# allow private RDP
iptables -A OUTPUT -o eth1 -p tcp -m multiport --dports 3389 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth1 -p tcp -m multiport --sports 3389 -m state --state ESTABLISHED -j ACCEPT
# log for debugging
iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A OUTPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
iptables -A LOGGING -j DROP

The only thing I can figure is that since I'm doing port address translation, specifying the destination/source ports on my WAN interface isn't cutting it.  Any iptables bosses willing to tell me how much I'm getting wrong?
UPDATE: After reading through my logs and testing, I have some rules that seem to be working.
# Flushing all rules
iptables -F
# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT DROP
#iptables -P FORWARD DROP
# Allow unlimited traffic on loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# set up nat
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# allow DNS lookup
for ip in $DNS
do
        echo "Allowing DNS lookups to server '$ip'"
        iptables -A OUTPUT -p udp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
        iptables -A INPUT  -p udp -s $ip --sport 53 -m state --state ESTABLISHED     -j ACCEPT
        iptables -A OUTPUT -p tcp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
        iptables -A INPUT  -p tcp -s $ip --sport 53 -m state --state ESTABLISHED     -j ACCEPT

    #DNS lookups for NAT
    iptables -A FORWARD -p udp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
    iptables -A FORWARD -p udp -s $ip --sport 53 -m state --state ESTABLISHED -j ACCEPT
    iptables -A FORWARD -p tcp -d $ip --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
    iptables -A FORWARD -p tcp -s $ip --sport 53 -m state --state ESTABLISHED -j ACCEPT
done

# allow service ports to be forwarded to local network
iptables -A FORWARD -i eth1 -o eth0 -p tcp -m multiport --dports 22,80,443,1727,8192,8194,36015 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -p tcp -m multiport --sports 22,80,443,1727,8192,8194,36015 -m state --state ESTABLISHED,RELATED -j ACCEPT

# allow service ports out/in from WAN
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT

# allow service ports in, only when outbound connection exists
# 80 - HTTP ( for yum )
# 443 - HTTPS ( for yum )
# 21 - FTP ( for yum )
iptables -A OUTPUT -o eth0 -p tcp -m multiport --dports 80,443,21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# allow local RDP
iptables -A INPUT -i eth1 -p tcp --sport 3389 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth1 -p tcp -m tcp --dport 3389 -j ACCEPT
iptables -A FORWARD -i eth1 -p tcp --dport 3389 -m state --state   ESTABLISHED,RELATED -j ACCEPT

I think that last FORWARD rule for 3389 is unnecessary but I haven't tested that yet.  To address some of the first comments:
    [root@localhost ~]# iptables -L -n -v
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   79  5224 ACCEPT     tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0           multiport dports 22 state NEW,ESTABLISHED
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    0     0 ACCEPT     tcp  --  eth1   *       0.0.0.0/0            0.0.0.0/0           tcp spt:3389 state ESTABLISHED
    1   229 LOGGING    all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     tcp  --  eth1   eth0    0.0.0.0/0            0.0.0.0/0           multiport dports 22,80,443,1727,8192,8194,36015
    0     0 ACCEPT     tcp  --  eth0   eth1    0.0.0.0/0            0.0.0.0/0           multiport sports 22,80,443,1727,8192,8194,36015 state RELATED,ESTABLISHED
    0     0 ACCEPT     tcp  --  eth1   *       0.0.0.0/0            0.0.0.0/0           tcp dpt:3389 state RELATED,ESTABLISHED
    0     0 LOGGING    all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      lo      0.0.0.0/0            0.0.0.0/0
   68  7488 ACCEPT     tcp  --  *      eth0    0.0.0.0/0            0.0.0.0/0           tcp spt:22 state NEW,ESTABLISHED
    0     0 ACCEPT     tcp  --  *      eth0    0.0.0.0/0            0.0.0.0/0           multiport dports 80,443,21 state NEW,ESTABLISHED
    0     0 ACCEPT     tcp  --  *      eth1    0.0.0.0/0            0.0.0.0/0           tcp dpt:3389
    0     0 LOGGING    all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain LOGGING (3 references)
 pkts bytes target     prot opt in     out     source               destination
    1   229 LOG        all  --  *      *       0.0.0.0/0            0.0.0.0/0           limit: avg 2/min burst 5 LOG flags 0 level 6 prefix `IPTables-Dropped: '
    1   229 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0

[root@localhost ~]# iptables -L -n -v -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 1 packets, 60 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all  --  *      eth0    0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 1 packets, 60 bytes)
 pkts bytes target     prot opt in     out     source               destination

I removed the chunks re: my DNS servers from this output.  The only additions I'd like to make to this configuration is to restrict ssh access to a subnet of ip's, but I'll do that last as it should be trivial.  Thanks for the comments so far, hopefully nothing seems out of place with what I have!


text:
Q: Do not create directory if already exists in php I am using the following to create a directory on an intranet app for each customer. The problem is, if the directory already exists I am getting the error :
Warning: mkdir() [function.mkdir]: File exists in     C:\server2go\server2go\htdocs\customermgr\administrator\components\com_chronoforms\form_actions\custo    m_code\custom_code.php(18) : eval()'d code on line 11
 Failed to create directory...

Is it possible for the script to not create the directory if it already exists ?, either that or not show an error ?.
    <?php
    $customerID = $_GET['cfid'];

    /* wherever this particular script will be installed, I want to create a subfolder */

    /* Step 1. I need to know the absolute path to where I am now, ie where this script is running from...*/
    $thisdir = getcwd();

    /* Step 2. From this folder, I want to create a subfolder called "myfiles".  Also, I want to try and make this folder world-writable (CHMOD 0777). Tell me if success or failure... */

    if(mkdir($thisdir ."/customer-files/$customerID" , 0777))
    {
       echo "Directory has been created successfully...";
    }
    else
    {
       echo "Failed to create directory...";

    }

    ?>

EDIT >>>>>>>>>>>>>
I have tried the following, but still no joy :-(
            <?php
            $customerID = $_GET['cfid'];
            $directory = "/customer-files/$customerID";
            if(file_exists($directory) && is_dir($directory)) {
            }
            else {
            /* wherever this particular script will be installed, I want to create a subfolder */

            /* Step 1. I need to know the absolute path to where I am now, ie where this script is running from...*/
            $thisdir = getcwd();

            /* Step 2. From this folder, I want to create a subfolder called "myfiles".  Also, I want to try and make this folder world-writable (CHMOD 0777). Tell me if success or failure... */

            if(mkdir($thisdir ."/customer-files/$customerID" , 0777))
            {
               echo "Directory has been created successfully...";
            }
            else
            {
               echo "Failed to create directory...";

            } }

            ?>

A: Just use is_dir and/or file_exists, and only call mkdir if they returns false.
[edit]
Wait, did I just spot an eval in your error message?

A: You can use is_dir with file_exists to see if the directory exists:
if(file_exists($dirname) && is_dir($dirname)) {


text:
Q: Convert vector of lists into vector of vectors I have the following data in a .txt file:
1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533

I get the data and convert it to a vector using the following code:
(def custContents (slurp "cust.txt"))
(def custVector (clojure.string/split custContents #"\||\n"))
(def testing (into [] (partition 4 custVector )))

Which gives me the following vector:
[(1 John Smith 123 Here Street 456-4567) (2 Sue Jones 43 Rose Court Street
345-7867) (3 Fan Yuhong 165 Happy Lane 345-4533)]

I would like to convert it into a vector of vectors like this:
[[1 John Smith 123 Here Street 456-4567] [2 Sue Jones 43 Rose Court Street
345-7867] [3 Fan Yuhong 165 Happy Lane 345-4533]]

A: I would do it slightly differently, so you first break it up into lines, then process each line.  It also makes the regex simpler:
(ns tst.demo.core
  (:require
    [clojure.string :as str] ))

(def data
"1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533")

  (let [lines       (str/split-lines data)
        line-vecs-1 (mapv #(str/split % #"\|" ) lines)
        line-vecs-2 (mapv #(str/split % #"[|]") lines)]
    ...)

with result:
lines => ["1|John Smith|123 Here Street|456-4567"
          "2|Sue Jones|43 Rose Court Street|345-7867"
          "3|Fan Yuhong|165 Happy Lane|345-4533"]

line-vecs-1 =>
   [["1" "John Smith" "123 Here Street" "456-4567"]
    ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
    ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]

line-vecs-2 =>
   [["1" "John Smith" "123 Here Street" "456-4567"]
    ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
    ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]

Note that there are 2 ways of doing the regex.  line-vecs-1 shows a regex where the pipe character is escaped in the string.  Since regex varies on different platform (e.g. on Java one would need "\|"), line-vecs-2 uses a regex class of a single character (the pipe), which sidesteps the need for escaping the pipe.

Update
Other Clojure Learning Resources:

*

*Brave Clojure

*Clojure CheatSheet

*ClojureDocs.org

*Clojure-Doc.org (similar but different)

A: > (mapv vec testing)

=> [["1" "John Smith" "123 Here Street" "456-4567"]
    ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
    ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]


text:
Q: The Stone-von Neumann theorem without exponentials? Consider $\hat{r} = (\hat{x}_1,\hat{p}_1,\ldots \hat{x}_n,\hat{p}_n)^\intercal$ with commutation relation
\begin{equation}
[\hat{r},\hat{r}^\intercal] = i\Omega.
\end{equation}
I want a simple statement like:

Any two irreducible representations of the canonical commutation relations are unitarily equivalent.

so that I can prove that $\hat{r}$ and $S\hat{r}$ are unitarily equivalent when $S \in \operatorname{Sp}(2n,\mathbb{R})$. I seek out the Stone von Neumann theorem! But here I am told that

There is substantial literature on solutions to the commutation relations that do not necessarily integrate to unitary groups and for these the Stone von Neumann theorem breaks down completely...We bypass these difficulties by going to the Weyl integrated form.

which provides a reason that the theorem is always stated along these lines:

Let $(V,\Omega)$ be a finite dimensional symplectic vector space. Let $(\mathcal{H},\hat{W}(y))$ and $(\mathcal{H}',\hat{W}(y))$ be strongly continuous, irreducible, unitary representations of the Weyl relations. Then $(\mathcal{H},\hat{W}(y))$ and $(\mathcal{H}',\hat{W}(y))$ are unitarily equivalent.

Can I say something like: 'I don't want to consider the horrible cases', rigorously? Something like

Any two irreducible representations of the canonical commutation relations ''that are nice'' are unitarily equivalent

A: From a random review:

There are many theorems that answer this question, due to Rellich, Dixmier, Tillmann, Foiaş-Gehér-Sz.-Nagy, Kristensen-Mejlbo-Poulsen, and the reviewer. (...) Some of the proofs obtain the result directly, mostly via considering the operator $A=2^{−1/2}(Q+iP)$ and its adjoint $A^*$ which satisfy the formal relation $AA^*=A^*A+I$. Others deduce the Weyl-von Neumann relation. {It seems to the reviewer that none of these theorems is quite satisfactory.}


text:
Q: Error when executing script in sqlplus, option not a valid number I am trying to execute this command in sqlplus, I've tried putting it in a
.sql file, and .txt file also.
set linesize 400;
set pages 999;
spool odi_query.txt
declare
v_extract_date DATE;
begin
select extract_date into v_extract_date
from LORIK_UNIT.Toad_zhurnal;
LORIK_UNIT.lorik_utils.p_create_daily_partitions (v_extract_date );
end;
/
spool off

This is the error which I received after executing it:
SP2-0268: linesize option not a valid number
SP2-0268: pagesize option not a valid number

Does anyone know what might be the cause of it?

A: It seems that this code had extra spaces after each line, by removing those, now it executes smoothly.
set linesize 400
set pages 999

spool odi_query.txt

declare
v_extract_date DATE;
begin

select extract_date into v_extract_date
from LORIK_UNIT.Toad_zhurnal;

LORIK_UNIT.lorik_utils.p_create_daily_partitions (v_extract_date );
end;
/
spool off

A: Remove semicolons ; at the end of the lines.


text:
Q: Why is my rails app at example.com:3000 and not example.com? I am building a rails app but it appears at example.com:3000, how do I make it appear at example.com?
Thanks

A: Presumably because you are running the development app on its default port.
Go through the deployment process for your live system.

A: If you run your app with rails server you can run it with rails server -p 80 but you must be root and this solution is not good for production. You'd better use a solution provided by Quentin's link.


text:
Q: Django: Any negative effect of assigning value to related object and save Example:
user = instance.user
user.updated_at = now()
user.save()

Apart from the "dot optimisation" and "readability", for the sake of curiosity, are there any technical reasons not to do like the following?
instance.user.updated_at = now()
instance.user.save()

A: No. It is exactly the same. Django will perform the SELECT the first time you access the instance.user object. This object behaves like any other (it doesn't matter if you use a new reference for it).
If you take into account the moment when the query is performed, you can treat your models pretty much like any python object.


text:
Q: How can I add a currency switcher to my language container at the top of rwd theme I am using my own custom version of the RWD theme and would like to know how I can display a currency switcher in the div .header-language-background, how would i go about doing this? thanks

A: Create local.xml at app/design/frontend/rwd/default/layout if it not exist, then call currency dropdown by below code:
<default>
<reference name="store_language">
           <block type="directory/currency" name="topcurrency"  template="directory/currency.phtml"/>
 </reference>
<default>

then call this block using <?php echo $this->getChildHtml('topcurrency') ?> in languages.phtml which located at app/design/frontend/rwd/default/template/page/switch/


text:
Q: Start and End Times by OperationName in Kusto? How to add a StartTime and EndTime for each OperationName in the example below?
Sample data:
datatable(TimeGenerated:datetime, OperationName:string, ChunkSize:string, StatusCode:string, Filename:string, UserAgent:string)
[
    datetime(2021-05-27T06:03:59.5708689Z), "CreateFilePath", "0MB", "201", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:04:03.3834404Z), "LeaseFile",  "0MB", "201", "test_file.csv",  "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:06.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:07.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:08.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:09.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:10.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:11.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:12.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:13.1334979Z), "FlushFile", "0MB", "200", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:14.1334979Z), "LeaseFile", "0MB", "200", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:15.1334979Z), "GetBlob", "256MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:16.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:17.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:18.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:19.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:20.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10"
]
| summarize MethodCount = count() by OperationName, Filename, UserAgent

Results:
OperationName   FileName        UserAgent                                       MethodCount
CreateFilePath  test_file.csv   Microsoft Azure Storage Explorer                1
LeaseFile       test_file.csv   Microsoft Azure Storage Explorer                2
AppendFile      test_file.csv   Microsoft Azure Storage Explorer                7
FlushFile       test_file.csv   Microsoft Azure Storage Explorer                1
GetBlob         test_file.csv   azsdk-python-storage-blob/12.8.1 Python/3.8.10  6

Need:
StartTime                       EndTime                         OperationName   FileName        UserAgent                                       MethodCount
2021-05-27T06:03:59.5708689Z    2021-05-27T06:03:59.5708689Z    CreateFilePath  test_file.csv   Microsoft Azure Storage Explorer                1
2021-05-27T06:04:03.3834404Z    2021-05-27T06:05:14.1334979Z    LeaseFile       test_file.csv   Microsoft Azure Storage Explorer                2
2021-05-27T06:05:06.1334979Z    2021-05-27T06:05:12.1334979Z    AppendFile      test_file.csv   Microsoft Azure Storage Explorer                7
2021-05-27T06:05:13.1334979Z    2021-05-27T06:05:13.1334979Z    FlushFile       test_file.csv   Microsoft Azure Storage Explorer                1
2021-05-27T06:05:15.1334979Z    2021-05-27T06:05:20.1334979Z    GetBlob         test_file.csv   azsdk-python-storage-blob/12.8.1 Python/3.8.10  6

Tried:
| summarize
  StartTime = min(TimeGenerated) by OperationName,
  EndTime = max(TimeGenerated) by OperationName`,
  MethodCount = count() by OperationName,
  Filename,
  UserAgent

A: Since the Filename value for all records for a specific OperationName is going to be the same, it's sufficient to take a value from any records with this OperationName using summarize any(Filename). Same with the UserAgent column.
datatable(TimeGenerated:datetime, OperationName:string, ChunkSize:string, StatusCode:string, Filename:string, UserAgent:string)
[
    datetime(2021-05-27T06:03:59.5708689Z), "CreateFilePath", "0MB", "201", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:04:03.3834404Z), "LeaseFile",  "0MB", "201", "test_file.csv",  "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:06.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:07.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:08.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:09.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:10.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:11.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:12.1334979Z), "AppendFile", "8MB", "206", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:13.1334979Z), "FlushFile", "0MB", "200", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:14.1334979Z), "LeaseFile", "0MB", "200", "test_file.csv", "Microsoft Azure Storage Explorer",
    datetime(2021-05-27T06:05:15.1334979Z), "GetBlob", "256MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:16.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:17.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:18.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:19.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10",
    datetime(2021-05-27T06:05:20.1334979Z), "GetBlob", "128MB", "206", "test_file.csv", "azsdk-python-storage-blob/12.8.1 Python/3.8.10"
]
| summarize StartTime=min(TimeGenerated), EndTime=max(TimeGenerated), Filename=any(Filename), UserAgent=any(UserAgent), MethodCount=count() by OperationName
| project-reorder StartTime, EndTime, OperationName, Filename, UserAgent, MethodCount

Output:

StartTime
EndTime
OperationName
Filename
UserAgent
MethodCount

2021-05-27 06:03:59.5708689
2021-05-27 06:03:59.5708689
CreateFilePath
test_file.csv
Microsoft Azure Storage Explorer
1

2021-05-27 06:04:03.3834404
2021-05-27 06:05:14.1334979
LeaseFile
test_file.csv
Microsoft Azure Storage Explorer
2

2021-05-27 06:05:06.1334979
2021-05-27 06:05:12.1334979
AppendFile
test_file.csv
Microsoft Azure Storage Explorer
7

2021-05-27 06:05:13.1334979
2021-05-27 06:05:13.1334979
FlushFile
test_file.csv
Microsoft Azure Storage Explorer
1

2021-05-27 06:05:15.1334979
2021-05-27 06:05:20.1334979
GetBlob
test_file.csv
azsdk-python-storage-blob/12.8.1 Python/3.8.10
6


text:
Q: remove space in bootstrap template I have the following markup:

+-----------------------+---------------+---+
| span9 contents here   | span3 content | ->|-----space appearing here
+-----------------------+---------------+---+

How can I remove spacing of right side. I can't see padding and or margin value applied in but also space is appearing?

Update:
I found the reason why it was showing the space! I have added the following css
body, [class*="span"] {margin: 0 !important; padding: 0 !important;}

So, without removing this css can I remove the space?

A: Give your target div a class:

Test1

Test2

then you can add these css rules:
.target [class*="span"] {
    margin-left: 20px !important;
}

.target [class*="span"]:first-child {
    margin-left: 0 !important;
}

Bootply Demo

A: Try it:


text:
Q: How to implement update value callback when peripheral itself is changing the characteristic value Suppose if the peripheral is listening to some socket or pipe in which I am sending a value which will modify the characteristic. How can I notify that change to the central device? Both peripheral and central devices are running on the Linux platform. Because whatever the Pizza example given for Linux device will notify the central only when central is writing something. Suppose if the value is changed by some program outside Bleno an noble where I should implement the updateValueCallback()? Is it on onSubscribe or onNotify?

A: You should use the  onSubscribe() event.
onSubscribe() fires when the central (GATT Server) subscribes to notifications from your peripheral, whereas onNotify() fires when a notification is sent, after the central has subscribed.
For example, I've defined my characteristic as follows:
var customCharacteristic = function() {
    bleno.Characteristic.call(this, {
        uuid: 'UUID_HERE',
        properties: ['read', 'notify', '... etc'],
        //Subscribe event
        onSubscribe = function(maxSize, updateValueCallback){
            console.log('subscribe'); //output that we've subscribed
            //Now the central has subscribed, poll something
            //(the sensor or whatever you're using) every half
            //second to see if the value has updated
            setInterval(function() {
                //poll sensor or get value or something
                updateValueCallback(new Buffer([VALUE]);
            }, 500);
        },
        //Notify event
        onNotify = function(){
            console.log('notify'); //to show when notification is being sent
        }
    });
}

//Don't forget to deal with when the central unsubscribes, you might want to stop the interval ticker!

Roughly based on this article, with some ideas from here.


text:
Q: will my message be added twice to the queue? I've got a function like below:
    [FunctionName("OnBlocksQueueTriggered")]
    public static void Run([QueueTrigger("processblocksqueue", Connection = "StorageConnectionString")
        ]string payload,
        [Queue("processschedqueue", Connection = "StorageConnectionString")] CloudQueue outputQueue,
        TraceWriter log)
    {
         outputQueue.AddMessage(new CloudQueueMessage("my awesome message"));

    }

Since we are specifying an output queue like so in the function signature:
        [Queue("processschedqueue", Connection = "StorageConnectionString")] CloudQueue outputQueue

as well as the line within the function:
         outputQueue.AddMessage(new CloudQueueMessage("my awesome message"));

Will the message between added twice?

A: The output binding is not working automatically for you. It just wraps the connection for you so that it is more convenient and optimized.
So, no, your message will not be added twice. The way you have implemented it, is the way you should.


text:
Q: EC2 retirement - Meteor / MongoDB I am hosting my Meteor Application on an Amazon EC2 instance. Today I got a mail that my instance is scheduled for retirement until the end of month. I don't have any experience with that and what are the best ways to handle the situation.
My root device type is ebs.
Amazon suggests: "We recommend that you launch replacement instances and start migrating to them."
I already created an AMI Image of my instance and launched it. Unfortunatly my app can't be reached. At the moment the running instance can be reached via web and ssh. Is there any best practice?
Thanks in advance

A: Since your root drive is EBS not ephemeral you are in good place to be. What is the difference and why EBS is better?
Amazon EC2 instance with ephemeral drive is stateless, you can reboot but you can't stop. Reboot or terminate are only options that available.
Amazon EC2 instance with EBS is statefull so Stop state is supported. Followed by subsequent Start event your EC2 is about to start on new hardware. It basically means no data lost and you can replicate the exact instance state on new hardware and this is what you need.
Amazon AMI is a snapshot of EBS, there is nothing more under the hood.
Once you have another machine up and running you need to connect via SSH and check everything is running exact the same way. If something failed this is the time for automation and making disaster recovery plan. You still have plenty of time and running original machine so consider yourself as very lucky person.


text:
Q: Android jni not use singleton mode I have a class named FJpegStreamReader, that has loaded a jni (.so):
System.loadLibrary("fjpeg");

and has a singleton constructor:
 private static volatile FJpegStreamReader mInstances;
    public static FJpegStreamReader getInstance() {
        if (mInstances == null) {
            synchronized (FJpegStreamReader.class) {
                if (mInstances == null) {
                    mInstances = new FJpegStreamReader();
                }
            }
        }
        return mInstances;
    }

when i invoke it with singleton, it work well,
FJpegStreamReader.getInstance().open("/sdcard/markers.jpg", FJpeg.MODEL_OPEN);

But now, i dont want to use singleton mode,  I try to change FJpegStreamReader   , and invoke like this :
FJpegStreamReader readerA = new FJpegStreamReader();
FJpegStreamReader readerB = new FJpegStreamReader();
readerA.open("/sdcard/markers1.jpg", FJpeg.MODEL_OPEN);
readerB.open("/sdcard/markers2.jpg", FJpeg.MODEL_OPEN);
Bitmap bmA = readerA.getBackgroundImage();
Bitmap bmB = readerB.getBackgroundImage();

and readerA work well, but readerB goes error.  i want it can be instanced more than one time in the same time,  how to make that readerA and readerB all work?
25884-25884 I: JNI_OnLoad Called
25884-25884 I: FilePath: /sdcard/markers1.jpg, and OpenMode: 0
25884-25884 I: offset is:15079
25884-25884 I: Start to Parser Data
25884-25884 I: Open Succeed
25884-25884 I: FilePath: /sdcard/markers2.jpg, and OpenMode: 0
25884-25884 E: Fired to Open File(code: -1001)

This is my c++ method:
unique_ptr<FJpeg> f(new FJpeg);

static jboolean
FJpeg_open(JNIEnv *env, jobject thiz, jstring fileName, jint model) {
    const char *c_path = NULL;
    c_path = env->GetStringUTFChars(fileName, NULL);
    LOG_I("FilePath: %s, and OpenMode: %d", c_path, model);
    int rel = f->openFile(c_path, model);
    if (rel < 0) {
        LOG_E("Fired to Open File(code: %d)", rel);
        return false;
    }
    LOG_I("Open Succeed");
    return true;
}

...

int FJpeg::openFile() {
    if (file_path == NULL || *file_path == '\0' || (open_mode != 0 && open_mode != 1)) return ERROR_CODE_UNSUPPORTED_OPERAND;
    if (open_mode == 0) {
        f_in.open(file_path, ios::in | ios::binary);
        if (f_in.fail()) return ERROR_CODE_FILE_NOT_FOUND;
        return checkOffsetAndEnd();
    } else {
        f_out.open(file_path, ios::out | ios::binary);
        if (f_out.fail()) return ERROR_CODE_FILE_NOT_FOUND;
        return 0;
    }
}

A: It looks like all your Java FJpegStreamReader objects share a single c++ FJpeg object.
You will need to change that to associate each Java object with a unique FJpeg object, for example bystoring either the raw address in a long field in the Java class, or a handle to it and converting both back to a pointer in your Jni methods.


text:
Q: Add a row from the checkedlistbox to the DataGridView I want to add an item to the DataGridView
If checked ListBox is checked. but add an item one time.Don't add it twice.
and I want the unchecked object in the checkedlistbox to be deleted as a row in the DataGridView. But my code is not working

Video
private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{
    foreach (int indexChecked in checkedListBox3.CheckedIndices)
    {
        if (checkedListBox3.GetItemCheckState(indexChecked) == CheckState.Checked)
        {
            dataGridView3.Rows.Add(checkedListBox3.SelectedItem.ToString());
        }
        else if (checkedListBox3.GetItemCheckState(indexChecked) == CheckState.Unchecked)
        {
            dataGridView3.Row[indexChecked].Delete;
        }
    }
}

A: I would suggest a DerivedCollection. This would work like this:
You have a ReacvtiveList bound to your left panel with checkbox. Person class has to implement INotifyPropertyChanged of course and have Checked property.
Then you can do something like that:
CheckedPeople = People.CreateDerivedCollection(x => x, x => x.Checked);
This will create observable read-only collection storing exactly the same objects that your original list, but filtered by Checked property. Then you can bind CheckedPeople as ItemsSource to your grid and still edit them (only the collection is read only, since it's fed by changes in People collections).

A: The problem is that each time the checkedListBox event is fired, you loop through all the checked items and add them to the DGV, hence the duplications.
Instead, you can do this:
private void checkedListBox3_SelectedIndexChanged(object sender, ItemCheckEventArgs e)
{

    int selectedIndex = checkedListBox3.SelectedIndex;

    // If item is checked, add it to DGV
    if (checkedListBox3.GetItemCheckState(selectedIndex) == CheckState.Checked)
    {
        dataGridView3.Rows.Add(checkedListBox3.Items[selectedIndex].ToString());
    }

    // If item is unchecked, search for its first occurence in the DGV and remove it
    else if (checkedListBox3.GetItemCheckState(selectedIndex) == CheckState.Unchecked)
    {
        DataGridViewRow row = dataGridView3.Rows
            .Cast<DataGridViewRow>()
            .First(r => r.Cells["ENTER_YOUR_COLUMN_NAME_HERE"].Value.ToString().Equals(checkedListBox3.Items[selectedIndex].ToString()));

        dataGridView3.Rows.Remove(row);

    }
}


text:
Q: XIRR function in pivot table I'm trying to add XIRR formula to pivot table but either I'm doing something wrong, either it's impossible.
Here on the picture is sample data, formula I've put and XIRR calculated in single cell with the same data (so It works outside pivot table)

A: I don't think so as the calculated field cannot work with arrays and will sum across the underlying data.

Look at how SUMPRODUCT misbehaves due to summing underlying data:
 click image to enlarge
Pivottable calculated fields will operate on the underlying data and the XIRR function needs at least one negative and one positive value, which it wouldn't have with the summed underlying data.
As per Microsoft XIRR guidance:

XIRR expects at least one positive cash flow and one negative cash
flow; otherwise, XIRR returns the #NUM! error value.


text:
Q: Handout is not the same as last displayed state of a frame
Possible Duplicate:
How to exclude certain slides from handout

OK. Here is the MWE that explains it all. When compiled as beamer (onscreen) option, the itemized items appear on every click. Are red colored and bold as they appear. But go back to normal view as soon as the slideshow advances. The final view of the slide is all lines except the 'permanently bold' line are normal.
But when compiled as a handout, the entire itemized list appears red colored and bold.
Is there a way in which handout view = last view of the frame on-screen can be achieved?
% this is for onscreen
 \documentclass[xcolor=dvipsnames,english,professionalfonts,smaller]{beamer}
% \documentclass[xcolor=dvipsnames,english,professionalfonts,smaller,handout]{beamer}

\usetheme{Madrid}
\usecolortheme[named=Black]{structure}

\begin{document}

\begin{frame}[<+->]{Leave the competition behind}

\pause

Some Text that remains normal all through.

\pause

    \begin{itemize}

    \item \alert <.>{\textbf <.> {Want this bold and alert when just displayed}}
    \item \alert <.>{\textbf <.> {But remains bold and alert in handout, too}}
    \item \alert <.>{\textbf <.> {The question is, how to avoid this}}

    \end{itemize}

    \uncover <+-> {Some other text that too remains normal all through}

    \uncover <+-> {\Large{\textbf{Want this bold permanently}}}

    \uncover <+-> {See, earlier text remains bold}

\end{frame}

\end{document}


text:
Q: How to /unregister a custom view (from xml) automatically on a bus I have a custom EditText View. It extends the default one and adds the ability to show a TimePickerDialogFragment, a NumberPickerDialogFragment and similar...
All my FragmentDialogs are working with a bus system, to make the reattaching to the parent activity unneccessary...
Normally, I register all objects on creation and unregister them in the onPause of their parent activity... I use a scoped bus for that, which saves references to all registered objects and unregisters them automatically in the onPause of the activity. That work's optimal so far. All my custom classes use a constructor, which receive a reference to the scoped bus... So the class only has to register itself on the scoped bus and does not need to unregister itself anymore, the scoped bus will do that automatically.
Now registering my custom edittext is no problem, but how to automatically unregister it? I'm adding the views in XML and I don't want to have to add all of them manually to my scoped bus.
Does anyone have an idea how the unregistering could be somehow automated?

A: Since you are using Otto. You could take a look how they are finding @Subscribe methods: https://github.com/square/otto/blob/master/library/src/main/java/com/squareup/otto/AnnotatedHandlerFinder.java
From the design point of view (IMO) your view are mixing two responsibilities - some UI representation and communicating with lower system layers. The common sense rule - class is responsible for one thing only.
You can think about this from other point of view. It will be much harder to reuse such components in any project that doesn't use bus. Think about your internal design like you are going to open source your system components.


text:
Q: Visual Stuidio Plugin Material Icon Theme4.5.0 isnt working My Problem #0.1
Check the SS
As you can see in the picture I already install the plugin and it's enabled, and in the left side of the picture you can see nothing is applied on my files, But it works fine when I'm uninstalling and reinstall again and when I close the visual studio and open it again it's not working.
I tried to make it a default for the visual studio but I didn't see any option in settings like that.
What should I do now? I want to use it default for every next time. I don't want to uninstall and install it again and again.


text:
Q: How can I fix a cursor position inside of a particular div? I am developing a simple 2d game where a user has to point a gun at different objects and shoot them. When a user moves his mouse, the crosshair's position always stays the same, but the environment (all other objects) move, creating an effect of a crosshair moving. The problem is, when a cursor leaves the div (where all of the above happens), everything stops moving.
So, the question is: how can I make the cursor never leave the div (with a game) unless the game is paused?
Example of what I expect: link. In this game, when a user's playing, their cursor is always inside a game screen, but when he's in the menu or the game is paused, their cursor can leave a game screen.


text:
Q: How to select all initialization cells? Is there an easy way to select all initialization cells (and only those) in a Mathematica notebook?

A: Here are a couple of new V9 approaches that use Cells.  I think the Cells function makes some of these kinds of tasks simpler.

The first solution achieves the goal mentioned in a comment: How to copy all the initialization cells.
nb = EvaluationNotebook[]; (* change as desired *)
CopyToClipboard @
  NotebookRead @ Select[Cells[nb], CurrentValue[#, InitializationCell] &]

The cells may be pasted in another notebook.  The Cells approach allows one to do many things with cells, even if they are not actually selected in the notebook.

This creates a palette that allows you to mover a slider to select each initialization cell in turn.  It won't select all of them as asked for, but one can locate them, which sometimes I want to do. (Thanks to @CarlWoll for suggesting an improvement.)
CreatePalette @ Manipulate[
  initcells = Pick[#, CurrentValue[#, InitializationCell]] &@ Cells[SelectedNotebook[]];
  whichCell = Clip[whichCell, {0, Length[initcells]}];
  If[whichCell > 0, SelectionMove[#[[whichCell]], All, Cell] &@initcells];
  whichCell,

  {whichCell, 0, Length[initcells], 1},
  {{initcells, {}}, None},
  TrackedSymbols :> {whichCell}
  ]

A: My method is to define a special style in stylesheet for initialization cells. Here is my definition:
Cell[StyleData["Initial"],
 CellFrame->{{1, 1}, {1, 1}},
 CellMargins->{{78, 10}, {5, 10}},
 Evaluatable->True,
 CellGroupingRules->"InputGrouping",
 TextClipboardType->"InputText",
 StripStyleOnPaste->True,
 PageBreakWithin->False,
 GroupPageBreakWithin->False,
 InitializationCell->True,
 DefaultFormatType->DefaultInputFormatType,
 ShowAutoStyles->True,
 "TwoByteSyntaxCharacterAutoReplacement"->True,
 HyphenationOptions->{"HyphenationCharacter"->"\[Continuation]"},
 AutoItalicWords->{},
 LanguageCategory->"Mathematica",
 FormatType->InputForm,
 NumberMarks->True,
 LinebreakAdjustments->{0.85, 2, 10, 0, 1},
 CounterIncrements->"Input",
 MenuCommandKey->"i",
 FontWeight->"Bold",
 Background->RGBColor[1., 1., 0.8666666666666667]]

Then you can use alt+i to insert an initialization cell / convert an existing cell to Initial-style, and use alt+left-click to select all cells of this style in current notebook.

A: Here is a method that can be run on existing notebooks, but has some drawbacks.
It leverages the Evaluate Initialization Cells option by redefining $Pre to set the CellTags  then NotebookFind will select all the initialization cells.
First, we have a function that will set the CellTags of a cell when it is evaluated.
tagFun[input_] := (SelectionMove[InputNotebook[], All, EvaluationCell,
    AutoScroll -> False];
  SetOptions[NotebookSelection[], CellTags -> "init"];
  SelectionMove[InputNotebook[], After, Cell, AutoScroll -> False];
  input)

Then, change $Pre and evaluate only initialization cells.
oldpre = $Pre;
    $Pre = tagFun;
FrontEndExecute[FrontEndToken["EvaluateInitialization"]];

Finally, change $Pre back and select the initialization cells.
$Pre = oldpre;
NotebookFind[InputNotebook[], "init", All, CellTags]

The drawbacks are:

*

*I could not package this into a function. In fact, the commands apparently need to be in separate cells (as I have them here).

*This evaluates the initialization cells when run.

*Overwrites CellTags on initialization cells


text:
Q: String.format() not working correctly with Printable (Using Graphics2D) I am trying to write some code that will print some numbers right-aligned but have noticed that when there is more than one digit, the formatting gets messed up and throws everything off. I also noticed that the Strings I am trying to print are not aligning correctly either.
Here is my code:
public class Printer implements Printable
{
    Object[][] data;
    String lines;

    public Printer(Object[][] data)
    {
        this.data = data;
        lines = convertArrayToString();

        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper paper = new Paper();
        paper.setImageableArea(9, 9, paper.getWidth() - (9 * 2), paper
                .getHeight());
        PrintRequestAttributeSet attributes =
                new HashPrintRequestAttributeSet();
        attributes.add(OrientationRequested.LANDSCAPE);
        job.setPrintable(this, pf);
        boolean ok = job.printDialog();
        if (ok)
        {
            try
            {
                pf.setOrientation(PageFormat.LANDSCAPE);
                job.print(attributes);
            } catch (PrinterException ex)
            {
                /* The job did not successfully complete */
            }
        }
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page)
            throws PrinterException {
        if (page > 0)
            return NO_SUCH_PAGE;

        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableY(), pf.getImageableX());
        g.setFont(new Font("ARIAL", Font.PLAIN, 11));
        drawString(g, lines, 10, 10);

        return PAGE_EXISTS;
    }

    private void drawString(Graphics g, String message, int x, int y)
    {
        for (String line : message.split("\n"))
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
    }

    private String convertArrayToString() {
        String line =  "ID |   REVERB |     GAIN |     PRESENCE |     MIDDLE | "
                + "   BASS |           ARTIST NAME |           AMPLIFIER NAME "
                + "|\n"
                + "------------------------------------------------------------"
                + "------------"
                + "------------------------------------------------------------"
                + "-------------------------\n";

        for (int i = 0; i < data.length; i++)
        {
            String currentLine = "";

            currentLine = String.format(" %2d |              %2d |           "
                    + "%2d |                     %2d |                %2d |"
                    + "           %2d |%30s |%30s |\n", data[i][0], data[i][1],
                    data[i][2], data[i][3], data[i][4], data[i][5], data[i][6],
                    data[i][7]);
            line += currentLine;
        }

        return line;
    }
}

And here is what the code prints:

If anyone has any idea as to why using the String.format() method only works sometimes, any input would be appreciated! Thank you!

A: The fix was to change the Font object to new Font(Font.MONOSPACED, Font.PLAIN, 11), as VGR suggested above.


text:
Q: Blazor - private component Is there way to create a Blazor component private for the project that it is being used in?
For example, let's look at Razor Class Library ProjectOne that contains two components: omponent ComponentA and component ComponentB. The component ComponentB is child of component ComponentA.
ProjectOne structure:
ProjectOne
---- Components
---------- ComponentA.razor
---------- ComponentB.razor
There is another project which is Blazor application ProjectTwo. There is a reference in this project to ProjectOne. When calling component ComponentA in razor page, the child component ComponentB is visible and accessable as well.
Is there a way to create this child component ComponentB internal only for project ProjectOne where it is being used within the component ComponentA?

A: As it looks like the sub-component needs to be public, rather than put it in another project, I just put it in a deeper namespace.
If the root component that I want to expose publicly is in
MyApp.Components.Widget

then I put the child components in
MyApp.Components.Widget.Internal

Achieves a similar outcome to the advice from the earlier answer without the need for another project, seeing as the best we can do is obfuscate it in lieu of making it 'internal' or 'private'.

A: Possibly not ideal but create another project to support your public project and only referenced by your public project.  Your consuming project only references your public project. So for you example it would change to ...

*

*ProjectTwo (App project)

*

*ProjectOne (Api component project)

*

*ProjectOneInternalUse (supporting project for API use)

(unfortunately you still need to refefence the 'internal use' project in ProjectTwo (the app project) but at least it will be marked as internal in the naming within the namespace)


text:
Q: The input is not a valid Base-64 string Facing issue for FromBase64String method.
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
Tried replacing - to +
var bytes = Convert.FromBase64String(id);
id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC"

Expected result is string should be converted to an equivalent 8-bit unsigned integer array.

A: It's not a Base64 encoded string. It's a Guid. You can read it into a byte array like this
var bytearray = new Guid("59216167-f9c0-4b1b-b1db-1babd1209f10").ToByteArray();

A:
The input is not a valid Base-64 string

The exact reason you are getting this type of error is because it's not a valid Base64 string, instead as already mentioned, it's a Guid; and not a valid Guid at that.
First you can check if you even have a valid Base64 string by trying to convert it.
public static bool StringIsBase64(string myString)
{
   Span<byte> buffer = new Span<byte>(new byte[myString.Length]);
   return Convert.TryFromBase64String(myString, buffer , out int bytesParsed);
}

Now if you call this function and it succeeds, then we would assume you do have a valid Base64 string, otherwise a conversion error would occur.
Your call can now look like this:
 string id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC";
 var bytes;
 if (StringIsBase64(id))
 {
    bytes = Convert.FromBase64String(id);
 }

Something else I would like to address that none of the other answers addressed, is the input is not valid for even a Guid. A GUID is a 128-bit integer (16 bytes) and that string isn't valid.
You actually would receive the error:

Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

The characters @ABC at the end of the string are causing this, if these are removed then we have an actual valid Guid.

A: Try this will Help
    using System;
    public class Program{

    public static void Main()
    {
        Guid gg = Guid.NewGuid();
        Console.WriteLine(gg);
        string ss = Encode(gg);
        Console.WriteLine(ss);
        Console.WriteLine(Decode(ss));
    }
    public static string Encode(Guid guid)
    {
        string encoded = Convert.ToBase64String(guid.ToByteArray());
        encoded = encoded.Replace("/", "_").Replace("+", "-");
        return encoded.Substring(0, 22);
    }

    public static Guid Decode(string value)
    {
        value = value.Replace("_", "/").Replace("-", "+");
        byte[] buffer = Convert.FromBase64String(value + "==");
        return new Guid(buffer);
    }

}


text:
Q: What's the meaning of "what it means for {someone} to be in some place"? There is this context:

"Since we are discussing the relationship of space, time, and logic, let us talk about time-travel paradoxes. We first have to ask ourselves what it means to travel back through time. What would it mean for me to go back to the Continental Congress held in Philadelphia in 1776, in order to witness the signing of the Declaration of Independence?"

What's the meaning of "what it means for {someone} to be in some place"?
I had a similar question about what it means for something to be something:
 What's the meaning of "what it means for {something} to be {something}"?
but in this context, I don't think the previous question has the answer for this one. I don't get it what it means for me to be in a certain place. if anyone can help I would appreciate it.

A: The author seems to be talking about having the ability to go back in time and to witness the events as if you were physically present when they first happened. In this case the author is talking about going back to when the representatives of the British colonies in America first gathered to assert their independence from Britain and wrote a document called The Declaration of Independence. Going back in time is of course, not possible for humans, at least, not yet. The author is just asking you to imagine what it would be like if you could go back in time.
This is of course speaking of something more than your physical location. I can say, "Imagine that you are in Sydney, Australia." This is saying, "Imagine that you are in America and the year is 1776, not 2019."

A: *

*To go live in Australia means everything to me.

*To visit New Zealand means so much to me.

*To visit Brazil means nothing to me.

*Getting a new job could mean lots more cash.

*Going back to some point in history means little to me.

*The new teacher means a lot to me.

Questions:

*

*What would it mean to you to go live in Australia?

*What would it mean to you to visit New Zealand?

*What does going back in history mean to you?

In English the verb mean can be signify. To have a meaning.
In short, x means y for [some person] means to have the meaning that comes after the verb mean.


text:
Q: How can I check the distribution for gender separately when the data is not separated by gender? I have to check if the data has a normal distribution for CREANZ for male and female, but my dataset has the genders mixed up and I don't how to separate them so that I can check the distribution for the genders separately. I did the following before:
df$Gender[df$Gender=="V"]=0.742
df$Gender[df$Gender=="M"]=1
df$Gender[df$Gender=="F"]=0.742
df$Gender<-as.numeric(df$Gender)
df$Gender<-as.numeric(df$Gender)

A: Take a look at reproducible examples if you want to get more answers.
You can check normality both with plots and tests. If you want a test, shapiro wilk may be a good choice. Using pipelines:
df %>%
   dplyr::select(CREANZ, gender) %>%
   group_by(gender) %>%
   summarise(across(.fns = ~shapiro.test(.))) -> result

and if you just want the p-value
df %>%
   dplyr::select(CREANZ, gender) %>%
   group_by(gender) %>%
   summarise(across(.fns = ~shapiro.test(.)$p.value)) -> result


text:
Q: Lightning with Lighting Spritekit I am learning Spritekit and I would like to know how I can convey the impression of lightning by lighting up the scene. I DON'T want to show the actual lightning bolt. But I want the clouds in the sky (for example) lighting up, or the entire scene (followed by appropriate sounds) to convey a lightning effect during stormy weather.
Any help will be greatly appreciated. Thanks.

A: One way I believe you could do this is by creating an if statement and the changing the color to white then back to it's form. Also, a new zPosition would be needed if everything would be lite up.
if lightUpThePlace = true {

background.color = SKColor.white

background.zPosition = 100

//and then do either  : (Because the language is read top to bottom)

background.color = SKColor.//the regular color

background.zPosition = //default zPosition

}

Otherwise, you could make a white sprite node big enough for the screen and move it to the center instantly and then have it despawn.
let flash = SKSpritenode(imageNamed: "//white sprite node")

let move = SKAction.moveTo...

let despawn = flash.removeFromParent()

let sequence = SKAction.sequence([move, despawn])

Hope This Helped!


text:
Q: Can i put the same package name and keyhashes in multiple facebook app? I am trying to develop a facebook app.I put the facebook login code but i am not abl eto get the facebook login dialog.I get error like cannot find com.facebook.katana.buttonid provider. I have the same package names and keyhashes in multiple apps. Can this create a problem in logging?

A: you will use the same Key Hash for all the Facebook Apps, But your Android apps that use that Facebook apps must be signed with the same Keystore what you use to create the Key Hash.