text:
Q: SQL to insert to a table I am using the below SQL to try and put content in a textbox, to a different table. It was working until I added the text 43, and text 109 section
DoCmd.RunSQL "INSERT INTO tbl_EmailsSent (AccountNumber, Email1, ID, LoggedUser, LoggedDate)
    VALUES (' " & Me.Text8 & "', 'Sent', ' " & Me.Text109 & ", ' " & me.Text43 "');

Can you see the mistake? Because I cant unfortunately

A: Yes, it's the date and the spaces ans missing quotes:
DoCmd.RunSQL "INSERT INTO tbl_EmailsSent (AccountNumber, Email1, ID, LoggedUser, LoggedDate)
VALUES ('" & Me.Text8 & "', 'Sent', '" & Me.Text109 & "', #" & Format(Me!Text43.Value, "yyyy\/mm\/dd") & "#);"

No ID:
DoCmd.RunSQL "INSERT INTO tbl_EmailsSent (AccountNumber, Email1, LoggedUser, LoggedDate)
VALUES ('" & Me.Text8 & "', 'Sent', '" & Me.Text109 & "', #" & Format(Me!Text43.Value, "yyyy\/mm\/dd") & "#);"


text:
Q: How to account for experimental errors when computing the derivative of a Gaussian process? When applying Gaussian process regression upon training data, the covariance function can be generally given in the form: $\Sigma_{i,j} = k(x_i, x_j) + \sigma(x_i) \delta_{i,j}$, where $k$ is a selected kernel and the variable $\sigma(x_i)$ is an error drawn from the experiment. But when the functional form of the error, i.e. $\sigma$, is unknown and simply observed from a small sample of experiments, how can one compute the gradient of the Gaussian process?
For example, an experiment may give $\sigma(x_i)$ at particular training points. But when taking the derivative of $\Sigma$ with respect to $x$ (to get the derivative of the GP), $\sigma$ will be treated as a constant. Consequently, the error on the derivatives will essentially be unaffected by $\sigma$. But surely this does not properly account for the error in the original training data. Are there suggestions for accounting for $\sigma$ when its precise functional form is unknown when trying to compute the derivative of a GP?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the state of a marker? I am using the the Google Maps JavaScript API v3. I have a map that has markers on each state. When I click the state marker, I need access to the state abbreviation in the callback function. Is there any way native to google maps that I can access the state of a marker?
google.maps.event.addListener(mark,'click',function(event){
    // how can I access the state abbreviation (e.g. 'MO') from in here?
}

I know that I can probably accomplish this via reverse geocoding, but is there any simpler (and less error-prone) way?
If this can only be accomplished using reverse geocoding, what is the simplest code to access the state? I assume my code would look something like this:
google.maps.event.addListener(mark,'click',function(event){
    geocoder.geocode({'latLng': event.latLng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            ... get state from results ...
        }
    }
}

What would be the simplest code to get the state from the results? Based on the documentation of the address component types, I assume I would be looking for the "short_name" of the "administrative_area_level_1". Is this correct? Is there an easier way to access it than looping over the results until I find the "administrative_area_level_1"? (I have jquery included on the page and so can code with it if it makes anything simpler)

A: Here's a working example:
<!DOCTYPE html>

<title>http://stackoverflow.com/questions/17144375/how-to-get-the-state-of-a-marker?noredirect=1#comment24816710_17144375</title>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />


text:
Q: Use Responsive Image together with Flexbox I want to use the flexbox and the responsive image (the image with scrset and sizes). But the result seems horrible. The images have different height even if I used flex-grow to pull aligned, because the browser will load the different image with different sizes. I want the height of all images to be the same.
I found out sizes of images is hard to set if I use flexbox, it's quit unpredictable. Is there any way to solve this?
Here is the JSfiddle (Please resize the result window larger and the I used inline css for flex-grow)

A: Set the image height property to:
height:100%;

And if you want your all images to be the same size set the same value for flex-grow.
flex-grow:1;


text:
Q: Filter PowerShell output values PS C:\> Get-EC2Instance |%{ $_.RunningInstance } | Select-Object InstanceId,ImageID,@{Name='TagValues'; Expression={ ($_.Tags |%{ $_.Value }) }}

InstanceId         ImageId             TagValues
----------         -------             ---------
i-230151d5         ami-20224b10        Scott
i-8c80f27a         ami-e7527ed7        {landscape123, test123}
i-3d3195cb         ami-0b5f073b        temp

How do I modify my command so only the "landscape*" is filtered and displayed?
InstanceId         ImageId             TagValues
----------         -------             ---------
i-8c80f27a         ami-e7527ed7        landscape123

A: It looks like in some cases the Tags property contains multiple values. Change your calculated property like this to restrict it to a single value:
@{Name='TagValues'; Expression={$_.Tags | select -Expand Value | select -First 1}}

And add a filter to restrict your results to the objects with a specific tag value:
Get-EC2Instance |
  select -Expand RunningInstance |
  select InstanceId, ImageID,
         @{n='TagValues';e={$_.Tags | select -Expand Value | select -First 1}} |
  ? { $_.TagValues -eq 'landscape123' }

If you want to keep multiple tags for an instance, do this instead:
Get-EC2Instance |
  select -Expand RunningInstance |
  select InstanceId, ImageID,
         @{n='TagValues';e={$_.Tags | select -Expand Value}} |
  ? { @($_.TagValues) -contains 'landscape123' }

If you need a partial match on one of the tags, do something like this:
Get-EC2Instance |
  select -Expand RunningInstance |
  select InstanceId, ImageID,
         @{n='TagValues';e={$_.Tags | select -Expand Value}} |
  ? { $_.TagValues | ? { $_ -like 'landscape*' } }


text:
Q: How to get OSGI (project) created/running under IntelliJ Community/Ultimate edition(s) Delving into IntelliJ for first time. First tried the Community edition, then the Ultimate (trial). Trying to get OSGI working. The IntelliJ website shows that OSGI works on the Ultimate edition, but not on the Community edition. I can't find any feature of the freshly installed Ultimate edition that allows any OSGI projects.
I installed the "OSGI" plugin first in the Community edition, and then in the Ultimate. It doesn't seem to work in either. In both cases, after installing, there's still no option to create an "OSGI" project, nor to create a specific OSGI module/plugin. There is an OSGI item in File | Settings | Languages & Frameworks | OSGI/OSGI Project Defaults that is a bare bones item that doesn't seem to do much of anything.
Unable to find any detailed instructions online online. Help me Overflow, you're my only hope.
Thanks much.


text:
Q: Wait() / notify() synchronization I'm trying to check how wait/notify works in java.
Code:
public class Tester {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
        synchronized (t) {
            try {
                System.out.println("wating for t to complete");
                t.wait();
                System.out.println("wait over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("entering run method");
        synchronized (this) {
            System.out.println("entering syncronised block");
            notify();
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("leaving syncronized block");
        }
        System.out.println("leaving run method");
    }
}

Output Returned
wating for t to complete
entering run method
entering syncronised block
//sleep called
leaving syncronized block
leaving run method
wait over

I was expecting when notify() is executed the wait will be over & System.out.println("wait over"); will get printed. But it seems it only gets printed when t finished its run().

A: Answer to updated code :
From Thread.sleep() javadoc:

Causes the currently executing thread to sleep (temporarily cease execution) for the
  specified number of milliseconds, subject to the precision and accuracy of system timers
  and schedulers. The thread does not lose ownership of any monitors.

If you call Thread.sleep while inside a synchronized block, other threads won't be able to enter the synchronized block. You should never do time consuming tasks while in a synchronized block to avoid this.

A: Note (as others pointed out as well) that you have to use the same object for locking/synchronizing in both threads.
If you want your main thread to continue immediately after notify is called, you have to relinquish the lock temporarily. Otherwise wait will get called only after the secondary thread leaves the synchronized block. And it's never a good idea to keep a lock in a long running computation!
One way how to achieve is to use wait(int) on the lock instead of sleep, because wait releases the synchronization lock temporarily:
public class Tester {
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
        synchronized (lock) {
            try {
                System.out.println("wating for t to complete");
                lock.wait();
                System.out.println("wait over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class MyRunnable implements Runnable {
        public void run() {
            System.out.println("entering run method");
            synchronized (lock) {
                System.out.println("entering syncronised block");
                lock.notify();
                try {
                    lock.wait(1000); // relinquish the lock temporarily
                } catch (InterruptedException ex) {
                    System.out.println("got interrupted");
                }
                System.out.println("leaving syncronized block");
            }
            System.out.println("leaving run method");
        }
    }
}

However, using these low-level primitives can be very error prone and I'd discourage from using them. Instead, I'd suggest you to use Java's high-level primitives for that. For example, you can use CountDownLatch which lets one thread wait until other threads count down to zero:
import java.util.concurrent.*;

public class TesterC {
    private static final CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();

        System.out.println("wating for t to complete");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("wait over");
    }

    static class MyRunnable implements Runnable {
        public void run() {
            System.out.println("entering run method");
            try {
                latch.countDown();
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                System.out.println("got interrupted");
            }
            System.out.println("leaving run method");
        }
    }
}

Here you don't have to synchronize anything, the latch does everything for you. There are many other primitives you can use - semaphores, an exchanger, thread-safe queues, etc. Explorer the java.util.concurrent package.
Perhaps even better solution is to use even higher level API, such as Akka provides. There you work with Actors or Software transactional memory, which can be composed easily and spare you of most of concurrency issues.

A: Object monitor locks need to be performed a single reference of the same lock...
In your example you are waiting on an instance of the Thread, but using notify from the Runnable.  Instead, you should use a single, common lock object...for example
public class Tester {

    public static final Object LOCK = new Object();

    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
        synchronized (LOCK) {
            try {
                System.out.println("wating for t to complete");
                LOCK.wait();
                System.out.println("wait over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class MyRunnable implements Runnable {

        public void run() {
            System.out.println("entering run method");
            synchronized (LOCK) {
                System.out.println("entering syncronised block");
                LOCK.notify();
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("leaving syncronized block");
            }
            System.out.println("leaving run method");
        }
    }
}

Output...
wating for t to complete
entering run method
entering syncronised block
leaving syncronized block
wait over
leaving run method

wait over and leaving run method could change positions depending on the thread scheduling.
You could try putting the sleep out side the synchronized block.  This will release the monitor lock allowing the wait section to continue running (as it can't start until the lock is released)
    public static class MyRunnable implements Runnable {

        public void run() {
            System.out.println("entering run method");
            synchronized (LOCK) {
                System.out.println("entering syncronised block");
                LOCK.notify();
                System.out.println("leaving syncronized block");
            }
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("leaving run method");
        }
    }


text:
Q: Render partial collection with association I am trying to render partials for a collection of @entries to a shared view.
In one controller, I am doing it directly to render all the @entries in the view.
<%= render(:partial => '/shared/entry', :collection => @entries) %>

On another controller, I am doing it through bookmarks. As a result, the collection is @bookmarks.entries
<%= render(:partial => '/shared/entry', :collection => @bookmarks.entries) %>

Here is my /shared/_entry.html.erb :

    <%= link_to_unless_current entry.tag_list, tag_path(entry.tag_list) %>

I get the following error from the Bookmark controller, but the other controller works fine:
undefined method `tag_list' for #<Bookmark:0x007fad659b32b8>

It looks like it happens because even thought the collection is @bookmarks.entries, it is still recognizing it as a Bookmark and not as an Entry. If I change the view to the following, it works on the Bookmark, but then fails on the other controller:

    <%= link_to_unless_current entry.entry.tag_list, tag_path(entry.entry.tag_list) %>

How can I make the Bookmark collection just to have entries?

A: What's happening here is that you've used the wrong syntax by mistake, and it just happens that there is a method with the name you've used, existing in Rails/Ruby already.
If you are expecting this
@bookmarks.entries

to return a list of Entry objects, then it won't.  If @bookmarks is a collection of Bookmark objects, and a @bookmark has_many :entries, and you want to get all entries associated with all the bookmarks, you would do something like @bookmarks.collect(&:entries).flatten.uniq.
So, the syntax is wrong, and it should break, except that it just so happens that the Enumerable module, which is included in the Rails collection class, has a method called "entries", which returns an array of the items, which in this case are all Bookmark objects.   So, the partial is expecting an Entry and it's getting a Bookmark, and that's what that error is telling you:  you're calling tag_list on a Bookmark object.


text:
Q: Firebase and AngularFire error in ng-repeat only in IE8 I have an app that is using angular and firebase.  It makes a call to my firebase url and does a simple ng-repeat of the 2 items in the object returned.
The app works great in every browser except Internet Explorer 8.  I tested it in IE 8 often and it was working.  Not that I have launched it, sometime in the last few days it began receiving this error. I have made changes in the app over this time, but nothing in my mind that would change the way IE8 would render it.
The error in IE8 is simply:
SCRIPT5007: Unable to set property 'artists' of undefined or null reference
firebase.js, line 1 character 28
I have simplified the code down to the basics and I still get the error.
You can see below, artists is the name of the object in $scope.xmatch that I am trying to repeat with ng-repeat.  I ahve to get this working, so any help would be greatly appreciated.
app.js
(function() {
'use strict';
angular.module('ipremiosApp', ['firebase']).config
}).call(this);

global.js
(function() {
  'use strict';
  angular.module('ipremiosApp').controller('GlobalCtrl',['$scope','$timeout',    function($scope, $timeout) {
}]);

angular.module('ipremiosApp').controller('MatchCtrl',['$scope','$timeout','$routeParams','angularFire', function($scope,$timeout,$routeParams,angularFire) {

  var url = 'https://my.firebaseio.com/myfirebase';
  $scope.xmatch = angularFire(new Firebase(url), $scope, 'xmatch');

}]);
}).call(this);

index.html
<!doctype html>

  <meta charset="utf-8">
  <title>test</title>

    {{artist.name}}

A: It looks like a bug was introduced into angularFire in this commit which affects IE 8 only. I've filed an issue here.
The problem stems from the fact that $scope.xmatch is not declared before angularFire() is initalized. You can work around this problem, until a fix is released, by declaring it to an empty object like so:
new Firebase(url).child('test').set('happy');
$scope.xmatch = {};
angularFire(new Firebase(url), $scope, 'xmatch');

Also, on a side note, you had a subtle bug in your code that could bite you later. You've accidentally set $scope.xmatch to the returned value (a promise) from angularFire:
// don't do this
$scope.xmatch = angularFire(new Firebase(url), $scope, 'xmatch');

It seemed to work out here without any negative effects, because you haven't used $scope.xmatch for anything before the data arrives from Firebase and overwrites the bad declaration, but you certainly don't want that hash set to a promise value :)


text:
Q: Using ui-router with Bootstrap-ui modal I know this has been covered many times and most articles refer to this bit of code: Modal window with custom URL in AngularJS
But I just don't get it. I don't find that to be very clear at all. I also found this jsfiddle which was actually great, very helpful except this doesn't add the url and allow for me to use the back button to close the modal.

Edit: This is what I need help with.
So let me try explain what I am trying to achieve. I have a form to add a new item, and I have a link 'add new item'. I would like when I click 'add new item' a modal pops up with the form I have created 'add-item.html'. This is a new state so the url changes to /add-item.
I can fill out the form and then choose to save or close. Close, closes the modal :p (how odd) . But I can also click back to close the modal as well and return to the previous page(state).
I don't need help with Close at this point as I am still struggling with actually getting the modal working.

This is my code as it stands:
Navigation Controller: (is this even the correct place to put the modal functions?)
angular.module('cbuiRouterApp')
  .controller('NavbarCtrl', function ($scope, $location, Auth, $modal) {
    $scope.menu = [{
      'title': 'Home',
      'link': '/'
    }];

    $scope.open = function(){

        // open modal whithout changing url
        $modal.open({
          templateUrl: 'components/new-item/new-item.html'
        });

        // I need to open popup via $state.go or something like this
        $scope.close = function(result){
          $modal.close(result);
        };
      };

    $scope.isCollapsed = true;
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.getCurrentUser = Auth.getCurrentUser;

    $scope.logout = function() {
      Auth.logout();
      $location.path('/login');
    };

    $scope.isActive = function(route) {
      return route === $location.path();
    };
  });

This is how I am activating the modal:

   New Item

new-item.html:

I'm a modal!

{{ item }}

Selected:{{ selected.item }}

  <button ng-click="ok()" class="btn btn-primary">OK</button>
  <button ng-click="close()" class="btn btn-primary">OK</button>

Also whilst this does open a modal it doesn't close it as I couldn't work that out.

A: Here is a provider that improves @nathan-williams solution by passing resolve section down to the controller:
.provider('modalState', ['$stateProvider', function($stateProvider) {
  var provider = this;

  this.$get = function() {
    return provider;
  }

  this.state = function(stateName, options) {
    var modalInstance;

    options.onEnter = onEnter;
    options.onExit = onExit;
    if (!options.resolve) options.resolve = [];

    var resolveKeys = angular.isArray(options.resolve) ? options.resolve : Object.keys(options.resolve);
    $stateProvider.state(stateName, omit(options, ['template', 'templateUrl', 'controller', 'controllerAs']));

    onEnter.$inject = ['$uibModal', '$state', '$timeout'].concat(resolveKeys);
    function onEnter($modal, $state, $timeout) {
      options.resolve = {};

      for (var i = onEnter.$inject.length - resolveKeys.length; i < onEnter.$inject.length; i++) {
        (function(key, val) {
          options.resolve[key] = function() { return val }
        })(onEnter.$inject[i], arguments[i]);
      }

      $timeout(function() { // to let populate $stateParams
        modalInstance = $modal.open(options);
        modalInstance.result.finally(function() {
          $timeout(function() { // to let populate $state.$current
            if ($state.$current.name === stateName)
              $state.go(options.parent || '^');
          });
        });
      });
    }

    function onExit() {
      if (modalInstance)
        modalInstance.close();
    }

    return provider;
  }
}]);

function omit(object, forbidenKeys) {
  var prunedObject = {};
  for (var key in object)
    if (forbidenKeys.indexOf(key) === -1)
      prunedObject[key] = object[key];
  return prunedObject;
}

then use it like that:
.config(['modalStateProvider', function(modalStateProvider) {
  modalStateProvider
    .state('...', {
      url: '...',
      templateUrl: '...',
      controller: '...',
      resolve: {
        ...
      }
    })
}]);

A: It's intuitive to think of a modal as the view component of a state.  Take a state definition with a view template, a controller and maybe some resolves.  Each of those features also applies to the definition of a modal.  Go a step further and link state entry to opening the modal and state exit to closing the modal, and if you can encapsulate all of the plumbing then you have a mechanism that can be used just like a state with ui-sref or $state.go for entry and the back button or more modal-specific triggers for exit.
I've studied this fairly extensively, and my approach was to create a modal state provider that could be used analogously to $stateProvider when configuring a module to define states that were bound to modals.  At the time, I was specifically interested in unifying control over modal dismissal through state and modal events which gets more complicated than what you're asking for, so here is a simplified example.
The key is making the modal the responsibility of the state and using hooks that modal provides to keep the state in sync with independent interactions that modal supports through the scope or its UI.
.provider('modalState', function($stateProvider) {
    var provider = this;
    this.$get = function() {
        return provider;
    }
    this.state = function(stateName, options) {
        var modalInstance;
        $stateProvider.state(stateName, {
            url: options.url,
            onEnter: function($modal, $state) {
                modalInstance = $modal.open(options);
                modalInstance.result['finally'](function() {
                    modalInstance = null;
                    if ($state.$current.name === stateName) {
                        $state.go('^');
                    }
                });
            },
            onExit: function() {
                if (modalInstance) {
                    modalInstance.close();
                }
            }
        });
    };
})

State entry launches the modal.  State exit closes it.  The modal might close on its own (ex: via backdrop click), so you have to observe that and update the state.
The benefit of this approach is that your app continues to interact mainly with states and state-related concepts.  If you later decide to turn the modal into a conventional view or vice-versa, then very little code needs to change.

A: I answered a similar question, and provided an example here:
Modal window with custom URL in AngularJS
Has a complete working HTML and a link to plunker.

A: The $modal itself doesn't have a close() funcftion , I mean If you console.log($modal) , You can see that there is just an open() function.
Closing the modal relies on $modalInstance object , that you can use in your modalController.
So This :  $modal.close(result) is not actually a function!
Notice :
              console.log($modal);
              ==>> result :
          Object { open: a.$get</k.open() }
           // see ? just open ! , no close !

There is some  way to solve this , one way is :
First you must define a controller in your modal like this :
   $modal.open({
      templateUrl: 'components/new-item/new-item.html',
      controller:"MyModalController"
    });

And then , Later on , :
    app.controller('MyModalController',function($scope,$modalInstance){
      $scope.closeMyModal = function(){
       $modalInstance.close(result);
        }
       // Notice that, This $scope is a seperate scope from your NavbarCtrl,
       // If you want to have that scope here you must resolve it

   });


text:
Q: (Unknown Source:7) error in kotlin android I just converted my java project to kotlin in android and after that I'm facing following issue. This isn't indicating whether the error is?
    Process: com.app.furr, PID: 12420
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.furr/com.app.furr.DashboardActivity}: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                   Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
                                                                      at com.app.furr.mall.list.MallListFragment.onCreateView(Unknown Source:7)
                                                                      at android.app.Fragment.performCreateView(Fragment.java:2611)
                                                                      at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1276)
                                                                      at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2415)
                                                                      at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2194)
                                                                      at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2148)
                                                                      at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2049)
                                                                      at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3044)
                                                                      at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2991)
                                                                      at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:178)
                                                                      at android.app.Activity.performCreateCommon(Activity.java:6969)
                                                                      at android.app.Activity.performCreate(Activity.java:6977)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                      at android.app.ActivityThread.p

erformLaunchActivity(ActivityThread.java:2770

A: In MallListFragment, you need to define onCreateView like this
fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) : View? {
    ...
}


text:
Q: Why its better (Return IList Instead of return List)?
Possible Duplicate:
C# - List<T> or IList<T>

When I return a list from my method I can do in 2 way.
As a List
Private List<datatype> MethodName()
{
    Return List
}

As a IList
Private IList<datatype> MethodName()
{
    Return IList
}

As I heard we should return it as a IList. Is anyone can explain whys that?

A: It separates the interface from the implementation. It is not important for the caller how you implement the result object, so using interfaces reduces coupling. If you return IList, you can switch to a different implementation at any time without breaking the caller's code.

A: You can't return an IList - you need to return an implementation of that interface (i.e. a List). Of course returning a 'List' will satisfy your method declaration of returning a IList because List implements IList.
Generally best practice is to accept parameters of the most generic type and to return the most specific. However, conventionally programmers tend to not want to tie themselves to the List implementation and normally return the IList interface. You could be returning an IEnumerable if you don't want callers to modify the array (call the .AsReadOnly() extension method on your IList).

A:
If you are exposing your class through a library that others will use,
  you generally want to expose it via interfaces rather than concrete
  implementations. This will help if you decide to change the
  implementation of your class later to use a different concrete class.
  In that case the users of your library won't need to update their code
  since the interface doesn't change.
If you are just using it internally, you may not care so much, and
  using List may be ok.

Read the solution of this question: Why is it considered bad to expose List<T>?

A: Returning the interface allows you to change your implementation later and thus reduces coupling.
However when RETURNING an object this usually is of little practical concern. This is much more relevant when accepting objects (e.g. as function parameter).

A: If you return as just List. then the caller of your function has to put the return into an instance of class List.
When you return an IList the caller can put it into an instance of anything that implements that interface. Suppose the caller has made an implementation that supports some kind of funky sorting, or maybe they have made an implementation that directly maps the list to a database table.
It's about freedom for the receiver to implement Lists.


text:
Q: Windows 10 Брандмауэр. Запретить все исходящие подключения с исключением пользователя В ОС находятся два пользователя: Администратор и обычный пользователь.
Цель: Заблокировать выход в интернет обычному пользователю.
Захожу в "Панель управления\Система и безопасность\Брандмауэр Защитника Windows" выбираю "Дополнительные параметры" далее "Правила для исходящих подключений".
Создаю новое правило с параметрами:
Для программы> Все программы > Блокировать подключение > Для всех профилей (Доменный, Частный, Публичный) > Имя > Готово.
Правило создано, доступ в интернет не работает на обеих учетных записях.
Захожу в свойства правила. Выбираю вкладку "Локальные субъекты" там находятся два чекбокса:

*

*Авторизованные пользователи (Разрешать подключения только от этих
пользователей)

*Исключения (Пропускать это правило при подключении от
этих пользователей)

Отмечаю второе и добавляю Администратора. После применения интернет доступен не только у Администратора. Но и у обычного пользователя.
Что не так?
Так же не работает и по первому чекбоксу.


text:
Q: Add a character to the text on mobile version using CSS I have a text block on my website:

Specialtyreagents

Specialtyreagents

Can I somehow add a - symbol to this block within CSS, so it should looks like this:

Specialty-reagents

I can use only CSS in my case!
Thank you for your help.

A: With just CSS you can't include that - but if you need to use it in a specific case you can write again the text like this with a pseudo-element:

h1 {
  font-size: 0;
}
h1:before {
  content: "Specialty-reagents";
  display: block;
  font-size: 1.5rem;
}

Specialtyreagents

Specialtyreagents

A: Use a pseudoelement with the word you want on mobile, and use font-size to hide or show it.
example
codepen

h1:after {
  content: 'Specialty-reagents';
  font-size: 0;
}

@media screen and (max-width: 500px) {
  h1 {
    font-size: 0;
  }
  h1:after {
    font-size: 32px;
  }
}

Specialtyreagents

A: On the long ride you can have two html elements, one for mobile and one for desktop:

Specialtyreagents

and

Specialty-reagents

Then, you should have some css code for handling it:
.desktop {
    display: block;
}
.mobile {
    display: none;
}

@media (max-width: 720px) {
    .desktop {
        display: none;
    }
    .mobile {
        display: block;
    }
}

A: With media query:

@media only screen and (max-width: 500px) {
  h1 > span:after {
    content: "-";
  }
}

Specialtyreagents

A: As others have said, you can use a pseudo element to achieve this.
The best way to go is to just add a new pseudo element when viewing on a small viewport (ie. a mobile phone). Here is some extra info on pseudo elements and how they can be used.
Example...

    @media screen and (max-width: 768px) {

        h1 {
            font-size: 0px;
        }

        h1::after {
            font-size: 30px;
            display: block;
            content: "Specialty-reagents";
        }

    }

Specialtyreagents

The only thing you may need to change if the max-width for the media query and the font size of the heading.

A: Try this code for the solution please:
@media only screen and (max-width: 500px) {
  h1 > span:after {
    content: "-";
  }
}


text:
Q: Javascript: Calling method of each object in array without iteration Is there an elegant way of calling a method on each object in an array without iteration?
Edit: The intent of the question was to ask "without a for loop, or without any iteration if possible" Sorry for the confusion
var dogs = [new Dog("Max"), new Dog("Buddy"), new Dog("Charlie")];

for(var i=0; i<dogs.length; i++){
    dogs[i].sayName();
}

function Dog(name){

    this.name = name;

    this.sayName = function(){
         console.log(this.name);
    }

}

A: Use .forEach()
dogs.forEach(function(elem) {
   console.log(elem.sayName());
}

Alternatively you can use .map(), which returns a new array
dogs.map(function(elem) {
   return elem.name;
}

If you are using array.map() you should return something so you don't end up with a new array of undefined values, if you intend on using the returned array.
Using forEach() seems like a better fit in your use case.
However as @Barmar points out, both methods still iterate over each element in the array.

A: No
Doing something on each array item means you iterate the array.
So it's not possible to do it without iterating the array.

A: You could use forEach. Even the object initialisation could be done in a similar way with map:

var dogs = ['Max','Buddy','Charly'].map(name => new Dog(name));
dogs.forEach(dog => dog.sayName());

function Dog(name){
    this.name = name;
    this.sayName = function(){
         console.log(this.name);
    }
}

A: You can use map:
dogs.map(function(thisDog) { thisDog.sayName(); })

The callback for map takes three arguments: the current value, the current index, and the array. But in your case you only need the current value so you don't need to provide the other two arguments.


text:
Q: UniversaIimageLoader not work well with viewflow: ImageView not as expacted Working with IUL is OK.
Working with ViewFlow is also OK.
while use these two together there is problem. The ImageView show different faces for the same URI picture!
For Detail:
Bitmap from cache is different from bitmap from Net.  I have a test project show this problem for detail. In order to see the same, you should click->Next-->beck menu -->next .
Any one can help?


text:
Q: Take TV program with XML I have a channel publishing sites and I wanna get into the channel CNN broadcast program. CNN broadcast the program here (you can see in source - XML file):
http://tvprofil.net/xmltv/data/cnn.info/weekly_cnn.info_tvprofil.net.xml

How the data according to the time of withdrawal?
For example:
Now program: "bitmez's table"
next program: "stack's table" in 30 minute

Is this possible?
Update 1:
I can take the XML data but to all of XML file-
<?php

$url = 'http://tvprofil.net/xmltv/data/cnn.info/weekly_cnn.info_tvprofil.net.xml';
$xml = simplexml_load_file($url);
if (!$xml) {
    trigger_error('XML file -- read error',E_USER_ERROR);
    return;
}

foreach ($xml as $programme) {
    echo 'Now: ', $programme->title, "<br>\n";
}

A: <?php

$url = 'weekly_cnn.info_tvprofil.net.xml';
$xml = simplexml_load_file($url);

$now = new DateTime('now');
$it  = new IteratorIterator($xml->programme);

foreach ($it as $programm)
{
  $start = DateTime::createFromFormat('YmdHis', $programm['start']);
  if ($start > $now)
    break;
}

echo 'Now: ', $programme->title;
$it->next();
if ($it->valid) {
    echo 'Next: ', $it->current()->title;
}

off-topic Please, don't email me with requests, just because I answered your question, doesn't mean I need to do it again. It's basically the same, learn by using manual, for your own sake. Cheeers.

A: You need to get the attributes and compare them
$url   = 'http://tvprofil.net/xmltv/data/cnn.info/weekly_cnn.info_tvprofil.net.xml';
$array = (array) simplexml_load_file($url);

// FLATTEN THE RESULT SET
$programmes = array();
foreach ($array as $k => $v)
{
    if ($k == 'programme'){
        foreach($v as $p)
        {
            $programmes[] = (array) $p;
        }
        break;
    }
}

$tim = time();
$now = array();
$nex = array();

foreach ($programmes as $show)
{
    $attr = $show['@attributes'];
    if ($tim >= $attr['start'] && $tim <= $attr['stop'])
    {
        // GETS THE CURRENT SHOW
        $now = $show;
    }
}

print_r($now);


text:
Q: Looping in Asynchronous programming I'm pretty new to async. programming. I confuse how to do iteration.
I'm trying to iterate db queries. And right after the iteration is done I want to redirect user to the home page. Here's my code:
for(var i =0; i < venue_1_split.length; i++){
    pool.query("INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?,?)",
              [id_event, venue_1_split[i], id_google_calendar,
              waktu_mulai_1, waktu_selesai_1, tanggal_peminjaman_1,
              tanggal_peminjaman_1, hari_event_rutin],
             function(err, rows, fields){
                if(err) throw err;
    })
}

   //when the iteration is done.
   res.redirect('/');

How to achieve that? Thank you

A: You'll want to map over your array instead of doing a for loop. Since this is asynchronous, you'll want to wrap your .map in a Promise.all and call .then to ensure that it awaits all the promises before continuing. Something like this should work for what you're trying to do:
Promise.all(venue_1_split.map(venue => {
  return new Promise((res, rej) => {
    pool.query(
      "INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?,?)",
      [id_event, venue], id_google_calendar,
      waktu_mulai_1, waktu_selesai_1, tanggal_peminjaman_1,
      tanggal_peminjaman_1, hari_event_rutin],
      (err, rows, fields) => {
        if(err) rej(err)
        res()
    })
  }
}))
.then(r => res.redirect('/'))
.catch(err => {console.log(err); res.status(500).send()}) // or whatever you want to do with errors


text:
Q: Get values from redis-cli.exe --stat I use Redis 3.2.100 on Windows and for monitoring have to get values from 'redis-cli --stat' with the help of Powershell, but I can not do it because it go on without stop. Do you know any commands to get this info in one line and stop command line?

A: You can run redis-cli INFO at regular intervals and extract the required information.
redis-cli INFO includes all metrics like SERVER, CLIENTS, MEMORY, PERSISTENCE, STATS, REPLICATION, CLUSTER,CPU, KEYSPACE etc.
To get individual metrics use redis-cli INFO <METRIC NAME> example: redis-cli INFO SERVER.
Also you can use redis-stat which internally uses INFO command.


text:
Q: How to inform date-fns about the input date format? I need to return all of my input dates in yyyy-MM-dd format. Some input dates are in German format (dd/MM/yyyy) while others are in US format (MM/dd/yyyy).
I expect/want the code below to return "1979-12-31" in both cases. Instead, the second console output reads "1979-31-12" which means date-fns didn't notice the input date was in German format. How can I tell it that it's in German format, other than by passing the German locale to it as below?
const dateUS = '12/31/1979';
console.log('result with dinput date in US format: ',
  format(new Date(dateUS), 'yyyy-MM-dd')
);

import { deLocale } from 'date-fns/locale/de';

const dateDE = '31/12/1979';
console.log('result with input date in DE format: ',
  format(new Date(dateDE), 'yyyy-MM-dd', {
    locale: deLocale
  })
);


text:
Q: NSArray vs array is this OK practice?
NSArray* myarray[3] = {nil,nil,nil}

...

myarray[0] = some NSArray

or is it better to stick with NSArray over all?
NSArray* myarray = [NSArray...] ?
...
[myarray addObject:..]

A: Depends on your needs.  Either way works, but I generally find that mixing Objective-C objects and C structures leads to madness as you have to maintain sanity over two different memory models; retain/release and malloc/free.
I also generally avoid multi-dimensional arrays entirely.    For example, a 3x4 array of arrays can be represented as a single array of 12 items.   An item at 2,3 is really at (2 + (3*width)).
Note that NSArrays can't have "holes".  You can represent the holes, if needed, with NSNull objects.  Or create a subclass of NS[Mutable]Array that allows holes.

A: I will go for the second one, because in my opinion, the NSArray already encapsulates some advanced technique to help you.
It depends on your needs, if you want to do something complex and need built in data structure and algorithm, I think you can go for NSArray.
I try to avoid mixing between 2 programming languages C and obj-C as much as possible.


text:
Q: How to invoke a method with the methods name as a string I am using Biopython's Restriction class to perform in silico restriction digestions. As I understand it, in order to digest a certain sequence with a certain enzyme, the .catalyze() method must be implemented.
digestTuple = Restriction.EcoRI.catalyse(this_seq)  # Or whichever enzyme is desired.

Right now I apply a conditional to see which enzyme is being used as input. For Example:
RS = restrictionSite         # From user
amb = IUPACAmbiguousDNA()
this_seq = Seq(sequence, amb) # sequence from user

if RS == 'EcoRI':
    digestTuple = Restriction.EcoRI.catalyse(this_seq)

I apply a conditional for any enzymes that I would foresee myself needing. This takes up a bunch of lines of code and is inefficient. I would like to be able to search for membership in Restrictions set of all possible enzymes, Restriction.AllEnzymes. Something like this:
if RS in Restriction.AllEnzymes:
    digestTuble = Restriction.RS.catalyze(this_seq)

else:
    print('Please type in enzyme name correctly')

This problem is that python doesn't equate:
RS = "EcoRI"
digestTuple = Restriction.RS.catalyze(this_seq)

with
digestTuple = Restriction.EcoRI.catalyze(this_seq)

As it is trying to use the string name associated with the enzyme and not actually invoking the proper method.
Is there a way to invoke this method using the single conditional that searches all possible enzymes?
Maybe something like this Invoking a method by its name but in python?
The technical wording regarding this question is a little confusing for me, so I probably did not explain the problem accurately. Ill happily answer any clarifying questions.
Thank you

A: As simple as:
getattr(your_object,"methodname")()

example:
class My_Class:
    def print_hi(self):
        print 'hi'

a = My_Class()

getattr(a,'print_hi')()

output:
hi

In your case:
RS = "EcoRI"
digestTuple = getattr(Restriction, RS).catalyze(this_seq)

A: Use getattr(), e.g.:
RS = "EcoRI"
digestTuple = getattr(Restriction, RS).catalyze(this_seq)


text:
Q: How to check or print which element handle specific event happy new year 2017!!
I want check which elememt is owner of event.
for example, basically mouse wheel event handler(owner) is body element.
if I had several vertical scrollbar, mouse wheel event handler will be changed.
please tell me how to print event owner(especially mouse wheel event).
Thanks!

A: The event Object has several properties. You are looking for currentTarget or target, depending on how you registered the event handler and which element actually called it.
You can play with them to see.


text:
Q: Have multiple arguments in CommandLine (Windows Terminal) I would like to setup my profile in Windows Terminal in a way that it automatically connects to server1 via ssh and using server1 it connects to server2.
Everything works fine when i connect to single server1 machine but not sure how to launch second command.

*

*What i have is:

in settings.json->"profiles"->"list" -
"commandline": "ssh -i "mykey.pem" ubuntu@server1"

*

*What i want to do is something like (Bellow is just for visualization, any way that gets the job done is fine)

"commandline": "ssh -i "mykey.pem" ubuntu@server1 && ssh -i "mykey.pem" ubuntu@server2"

A: Found Solution thanks to https://unix.stackexchange.com/questions/41493/how-to-ssh-to-a-server-using-another-server
ssh -t $SERVER_A ssh $SERVER_B

gets the job done


text:
Q: AngularJS: objects, arrays, JSON, API issues Create:
I am using $scope.services where I am storing my list of services. This is an array of objects:
$scope.services = [{
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined
}];

I can then push another object into array.
$scope.services.push({
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined
});

So far, so good. I am then using this object as a model within Angular, to show its content.
Update:
I am calling API and getting my JSON in format:
{
    someData: "some data",
    services: {
        0: {
            id: 101,
            offer_id: 101,
            title: "some title",
            ...
        },
        1: {
            ...
        }
    }
}

Appending received data by $scope.services = data.services and then when I am calling $scope.services.push I get the console error
TypeError: $scope.services.push is not a function.

What could be wrong? Is it the JSON/array issue? I never got to the bottom of this, so any theory knowledge would be appreciated as well. Thank you in advance.

A: Because services is not an array, (push is defined for arrays: Array.prototype.push()) you need to construct a proper array from the response.
var servicesArray = [];
Object.keys(data.services).forEach(function (key) {
   servicesArray.push(data.services[key]);
});
$scope.services = servicesArray;

A: I think the object you assign(data.services) $scope.services = data.services may not be an array. Cross check whether your object from data.services is array. Found a similar issue (link) which may be helpful for you.


text:
Q: replace CanvasRenderingContext rectangles, shapes with svg images in browser Pacman game I'm trying to replace the pills in this browser game with svg images
https://codepen.io/hellokatili/pen/xwKRmo
At the top of the JS file, I entered the following (my approach is based on this answer):
var image = new Image()
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

There is a function called drawPills which draws the pills using CanvasRenderingContext rectangles.  As I understand it, the image I want to replace these rectangles with needs to be loaded before I can use it, so I replace the call to drawPills() with the following:
    image.onload = function() {
      map.drawPills(ctx);

    }

Then in the drawPills() function, I replace the rectangles with the image:
      ctx.drawImage(image, i, j);

Here's what my completed version of drawPills looks like:
  function drawPills(ctx) {

    if (++pillSize > 30) {
        pillSize = 0;
    }

    for (i = 0; i < height; i += 1) {
        for (j = 0; j < width; j += 1) {
            if (map[i][j] === Pacman.PILL) {
              ctx.drawImage(image, i, j);
              /*                     ctx.beginPath();

                ctx.fillStyle = "#000";
                ctx.fillRect((j * blockSize), (i * blockSize),
                             blockSize, blockSize);

                ctx.fillStyle = "#FFF";
                ctx.arc((j * blockSize) + blockSize / 2,
                        (i * blockSize) + blockSize / 2,
                        Math.abs(5 - (pillSize/3)),
                        0,
                        Math.PI * 2, false);
                ctx.fill();
                ctx.closePath();*/

            }
        }
    }

No svgs are loaded, however.  Can anyone help me figure out what I'm doing wrong?

A: While the images do not seem to be in the correct places I got the image loaded. I added this to the top of your code:
function loadImage(url){
  let image = new Image()
  image.src = url
  return image;
}
var pill_img = loadImage("http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg")

And replaced the code in the for loop of drawPills with:
ctx.drawImage(pill_img, j * blockSize, i * blockSize, blockSize, blockSize)
//While you had the pills drawn to a different spot, this position got it closer than doing ctx.drawImage(pill_img, i * blockSize, j * blockSize, blockSize, blockSize)
//You can always shift it

This draws the image in the wrong places, but now we know it is loaded.

A: You define variable image then you set the src to a variable called img.
Also, if you try to load that image on an https page, your request will be blocked because you can not load unsecure content in https pages. Try changing http with https in your image request.


text:
Q: Xcode swift hanging and using 50Gb+ memory only when using iPad symbols Edit: The issue seems to be caused by swift type-checking the vars and going crazy as it doesn't know that the response is an array of arrays. See my comment to get a workaround.
So, I have a swift project, it compiles and runs just fine on the iPhone emulator, but if I switch to the iPad emulator on Xcode (7.3.1), or plug in my iPad 3 (it is up to date), the 'swift' process starts to consume a huge amount of Ram, eventually freezing my computer. If I terminate it, then the SourceKitService does the same... If I then switch back to the iPhone emulator, then everything runs ok, I don't even need to restart Xcode...
Now, I isolated the part of my code where this crash happens:
private func startConnection(){
    Alamofire.request(.GET, "https://some.api.com/")
        .responseJSON { response in
            let resposta : NSArray = response.result.value as! NSArray
            // ----- If I remove the comment from the for loop -----
            for i in 0..<resposta.count {
                let canalNovo = Canal()
                canalNovo.novo(resposta[i][0] as! String,
                    nome: resposta[i][4] as! String,
                    desc: resposta[i][5] as! String,
                    src: resposta[i][3] as! String,
                    sigla: resposta[i][1] as! String,
                    corA: resposta[i][2][0] as! String,
                    corB: resposta[i][2][1] as! String,
                    isEnabled: false,
                    updateTime: NSDate()
                )
                self.canais.append(canalNovo)
            }
            // ----- It breaks the compiler... -----

            self.canais = self.canais.shuffle()

            self.tableView.reloadData()
    }
}

As stated in the above comment, if I uncomment the for loop, I get a crash, but only if the iPad symbols are being used... I've tried removing the symbols, cleaning dirs on .../DerivedData, nothing seems to resolve the problem! Please help me by providing an alternative way of doing this loop, and/or by providing some insight on what may be going wrong it my little app...
Ps.: I tried the for as follows too:
            // try One
            let respostaSize = resposta.count - 1

            for i in 0...respostaSize {
                let canalNovo = Canal()
                canalNovo.novo(resposta[i][0] as! String,
                    nome: resposta[i][4] as! String,
                    desc: resposta[i][5] as! String,
                    src: resposta[i][3] as! String,
                    sigla: resposta[i][1] as! String,
                    corA: resposta[i][2][0] as! String,
                    corB: resposta[i][2][1] as! String,
                    isEnabled: false,
                    updateTime: NSDate()
                )
                self.canais.append(canalNovo)
            }

            // try Two
            for canal in resposta {
                let canalNovo = Canal()
                canalNovo.novo(canal[0] as! String,
                    nome: canal[4] as! String,
                    desc: canal[5] as! String,
                    src: canal[3] as! String,
                    sigla: canal[1] as! String,
                    corA: canal[2][0] as! String,
                    corB: canal[2][1] as! String,
                    isEnabled: false,
                    updateTime: NSDate()
                )
                self.canais.append(canalNovo)
            }

            // try Three
            while i < resposta.count {
                let canalNovo = Canal()
                canalNovo.novo(resposta[i][0] as! String,
                    nome: resposta[i][4] as! String,
                    desc: resposta[i][5] as! String,
                    src: resposta[i][3] as! String,
                    sigla: resposta[i][1] as! String,
                    corA: resposta[i][2][0] as! String,
                    corB: resposta[i][2][1] as! String,
                    isEnabled: false,
                    updateTime: NSDate()
                )
                self.canais.append(canalNovo)
                i += 1
            }

Still crashes...


text:
Q: Pass variables between different .js files; inside the same html file can anyone help me to pass variables from one .js file to another one, the two .js are instantiated in the same html as following:
<script src="file_1.js"></script>

<script src="file_2.js"></script>

the content of "file_1.js" is like this:
var paragraph = readFile('file_to_read.tcl');

so what i need, is to use the "paragraph " variable in side the "file_2.js script
Great thanks in advance

A: You can save them locally like this:
file_1.js:
window.paragraph = readFile('file_to_read.tcl');

file_2.js:
setTimeout(function(){ //a small timeout to let the variable be declared...
  alert(window.paragraph);
}, 100);

Codepen


text:
Q: How to get memory address of an embedded slice in a struct? How can I get the memory address of an embedded slice in a struct?
Example:
type t1 struct {
    data string
}

type t2 struct {
    listData []t1
}

Now I want to know the memory address of listData. I couldn't figure out how to get the memory address out of it using the following:
newData := t2{}
newData.listData = append(newData.listData, t1{data:"mydata"})
printf("%p", &newData.listData) // this doesn't work, in fact it returns address of newData

A: listData is the first field in the struct, its memory offset relative to the struct's address is zero, so they have the same address.
type t2 struct {
listData []string
moreData []int
}

func main() {
    var foo t2
    fmt.Printf("%p %p %p", &foo, &foo.listData, &foo.moreData)
}

0x43e260 0x43e260 0x43e26c

https://play.golang.org/p/FVMujcUHHYq


text:
Q: How do I setup IIS when debugging in Visual Studio 2010? In Visual Studio 2010 I have created a WebService (WCF) Application and a client to consume said service.
My 3 options as far as what servers to use for debugging are: Visual Studio Development Server, Local IIS Web Server, Custom Web Server.
I know I can't use the VS Development Server if I want my service to be accessible outside of localhost. So I installed IIS (Control Panel>Add/Remove Programs>Add/Remove Features). When I select this option in Visual Studio 2010 it doesn't seem to work. I'm not sure what options I have to setup so that other machines can run the client to consume this service.
By default VS set the Project URL to: http://localhost/MyService. Oh, and I'm working with .svc files (not .asmx) if that makes any difference.

A: Common problem when you intall IIS after the framework.
Go to your Windows\Ms.Net\Framework\<version> folder and execute aspnet_regiis.exe.  It's a commandline tool.

A: To save having to install IIS you can configure a proxy - such as Fiddler - to redirect certain incoming traffic to localhost.
Because these new requests are "appearing" (via the redirect) from inside your machine, Cassini will respond.
The process is covered in this answer: https://stackoverflow.com/a/4428747/1016183 under "Option #2: Write a FiddlerScript rule"

A: You can right click on Project and do publish. This will generate the required files for your deploy.
In order to debug your app, you can use the Visual Studio built-in host or IIS.
In your project properties, under Web, you can select "Use Local IIS Server".


text:
Q: How to force Puma start in single mode on Rails? I m working on a Ruby app. My versions always started locally with Puma in single mode. For one week, Puma has automatically launched in cluster mode, it generates bugs, broadcasts don't launch anymore ... How can I force Puma to start in single mode ? I can't see such control on my config/puma.rb

A: Find this line in config/puma.rb. It's usually commented.
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }

If it's uncommented then just comment it or make it like below
workers ENV.fetch("WEB_CONCURRENCY") { 0 }

Then puma will start in single mode.


text:
Q: Link the CSS file to the HTML one in CGI programm So, I recently started to code a web interface with CGI, after finding how to print hello world on my Apache web page with HTML, I wanted to add some CSS to it but apparently it doesn't work.
I'm on Linux, and I am working with Apache2.
So there is my source file hello.c (which is in /usr/lib/cgi-bin):
#include <stdio.h>

int main()
{
    printf(
        "Context-type:text/html\n\n"
        "\n"
        "\n"
        "<title> Hi world </title>\n"
        "<link type=\"text/css\" rel=\"stylesheet\" href=\"style/style.css\">\n"
        "\n"
        "\n"
        "
Hello world !
\n"
        "\n"
        "\n"
    );

    return 0;
}

and there is my CSS file (which is in /usr/lib/cgi-bin/style/):
body {
    background-color:rgb(255, 0, 170);
}

h2 {
    font-family: Times;
    font-size: 38pt;
}

I already tried to put my CSS file in my home directory but it doesn't work too.

A: If you check your network panel of your browser's debugger, you're probably encountering a 500 status, as the server refuses to serve /cgi-bin/style/style.css.
Generally, style sheets do not belong in the CGI directory. You should move them to somewhere in your DocumentRoot path.

Assuming your configuration is something like:
DocumentRoot "/var/www"
ScriptAlias /cgi-bin/ "/usr/lib/cgi-bin/"

Set your directory structure to:
/usr/lib/
└── cgi-bin
    └── hello.cgi
/var/www
└── style
    └── style.css

Then change the relative path
"<link type=\"text/css\" rel=\"stylesheet\" href=\"style/style.css\">\n"

to an absolute path (note the / prefix):
"<link type=\"text/css\" rel=\"stylesheet\" href=\"/style/style.css\">\n"


text:
Q: How can I remove slash from renderRow of type date? I want to remove the slash (/) between day/month/year in date format, in Symfony 1.4, when use
<?php echo $form['birthday']->renderRow(array('class' => 'date')) ?>

Which result in:

  Birthday

     <select class="date" name="profile[birthday][month]" id="profile_birthday_month">
        <option value="" selected="selected"></option>
        <option value="1">01</option>
        ...
        <option value="12">12</option>
     </select>
     /
     <select class="date" name="profile[birthday][day]" id="profile_birthday_day">
        <option value="" selected="selected"></option>
        <option value="1">01</option>
        ...
        <option value="31">31</option>
     </select>
     /
     <select class="date" name="profile[birthday][year]" id="profile_birthday_year">
        <option value="" selected="selected"></option>
        <option value="2006">2006</option>
        ...
        <option value="2016">2016</option>
     </select>

But I want:

  Birthday

     <select class="date" name="profile[birthday][month]" id="profile_birthday_month">
        <option value="" selected="selected"></option>
        <option value="1">01</option>
        ...
        <option value="12">12</option>
     </select>
     <select class="date" name="profile[birthday][day]" id="profile_birthday_day">
        <option value="" selected="selected"></option>
        <option value="1">01</option>
        ...
        <option value="31">31</option>
     </select>
     <select class="date" name="profile[birthday][year]" id="profile_birthday_year">
        <option value="" selected="selected"></option>
        <option value="2006">2006</option>
        ...
        <option value="2016">2016</option>
     </select>

A: You can change the date format for the widget in your form class. Add the following code to the configure() method in lib/form/doctrine/MyForm.class.php:
$this->setWidget('foo', new sfWidgetFormDate(
    array('format' => '%month% ... %day% ... %year%')
));

Replacing the widget name foo with the appropriate name in your case. Hope this helps :)
Edit:
You can find more information on sfWidgetFormDate and other widgets here


text:
Q: CSP 'self' is failing in various directives I've recently added CSP to my website and started testing it (Report-Only): it looks OK except for some reports I cannot make sense of.
Specifically I am seeing violations for resources that should be allowed by a 'self' directive.
The server is running Express and CSP is served through helmet-csp. I've validated the CSP policy headers with multiple services (e.g. https://csp-evaluator.withgoogle.com/) and it comes out error-free.
I am using report-uri.com to collect and analyze CSP reports.
This is the helmet-csp setup:
app.use(csp({
  directives: {
    'default-src': ["'none'"],
    'object-src': ["'none'"],
    'script-src': ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
    'connect-src': ["'self'", (req, _res) => (req.protocol === 'http' ? 'ws://' : 'wss://') + req.get('host')],
    'manifest-src': ["'self'"],
    'worker-src': ["'self'"],
    'style-src': ["'self'"],
    'font-src': ["'self'"],
    'img-src': ["'self'", 'data:'],
    'base-uri': ["'self'"],
    'form-action': ["'self'"],
    'report-uri': '[REMOVED]'
  },
  reportOnly: true
}));

This is the resulting CSP header:
Content-Security-Policy-Report-Only: default-src 'none'; object-src 'none'; script-src 'self' 'nonce-[REMOVED]'; connect-src 'self' wss://MYSUBDOMAIN.MYDOMAIN.it; manifest-src 'self'; worker-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; report-uri [REMOVED]

These are some example of the reports:
{
    "csp-report": {
        "document-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/",
        "effective-directive": "worker-src",
        "original-policy": "default-src 'none'; object-src 'none'; script-src 'self' 'nonce-[removed]'; connect-src 'self' wss://MYSUBDOMAIN.MYDOMAIN.it; manifest-src 'self'; worker-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; report-uri [REMOVED]",
        "blocked-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/notification-worker.js",
        "line-number": 1,
        "column-number": 1966,
        "source-file": "https://MYSUBDOMAIN.MYDOMAIN.it/js/index.min.js"
    }
}

{
    "csp-report": {
        "document-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/results",
        "effective-directive": "img-src",
        "original-policy": "default-src 'none'; object-src 'none'; script-src 'self' 'nonce-[removed]'; connect-src 'self' wss://MYSUBDOMAIN.MYDOMAIN.it; manifest-src 'self'; worker-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; report-uri [REMOVED]",
        "blocked-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/img/icon_twitter_black.png",
        "line-number": 82
    }
}

{
    "csp-report": {
        "document-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/results",
        "effective-directive": "style-src-elem",
        "original-policy": "default-src 'none'; object-src 'none'; script-src 'self' 'nonce-[removed]'; connect-src 'self' wss://MYSUBDOMAIN.MYDOMAIN.it; manifest-src 'self'; worker-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; report-uri [REMOVED]",
        "blocked-uri": "https://MYSUBDOMAIN.MYDOMAIN.it/css/results.min.css",
        "line-number": 8
    }
}

There are ten or so similar reports (different images and css files, but identical report structure) and they all came from Chrome on Android.
I don't understand why all these reports were sent: in every case the relevant policy included the 'self' keyword.
Am I missing something obvious?


text:
Q: How Can i pass the Basic Credentials while using REST API client Program Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("username", "password"));
        WebResource resource = client.resource("https://server.location.path");
        //WebResource.Builder builder=resource.getRequestBuilder().header("Authorization", "Basic Base64value");
        ClientResponse response = resource.accept("application/json")
                .get(ClientResponse.class);
        System.out.println(response);
        String output = response.getEntity(String.class);
        System.out.println("Output from Server .... \n");
        System.out.println(output);

Here i have been placed the code and please let me know is you have any suggestion please


text:
Q: Exporting my android app to iphone? Ive made an app on Android and I want to be able to sell the app for iphone and android. I dont want to have to learn objective C. Is there any possible way I can do this?

A: You have a lot of options but none of them are very nice. I know of no direct converter.
To reuse the majority of your code checkout RoboVM
http://www.robovm.com/
It is used by libgdx to allow for using Java to do cross platform development.
Pretty much all your other options as far as I have seen would involve using a proprietary language or recreating your app as HTML5.
In the end you will have to write some iOS code. At least now/soon you can use Swift instead of Objective-C =)


text:
Q: php soap wsdl error on request header $options = array('trace' => true);
$client = new SoapClient('http://topup.sparrowsms.com/wsdl/?wsdl' , $options);
$header = new SoapHeader('http://topup.sparrowsms.com/wsdl/?wsdl', 'RequestHeader', array("access_token"=>$token), true);
$params = new SoapHeader('http://topup.sparrowsms.com/wsdl/?wsdl', 'topup' , array('topup_request' => array('msisdn' => $number , 'amount' => $amount , 'requestRef' => 1)));
$client->__setSoapHeaders(array($header , $params));
echo "
";print_r($client->__getTypes());echo "
";
echo "
";print_r($client->__getFunctions());echo "
";
$response = $client->topup();

I have this error when calling  $response = $client->topup(); I want to use topup at this time.
PHP sends this error :

Fatal error: Uncaught SoapFault exception: [senv:1012] Invalid Access Token


text:
Q: Do escalated voting fraud cases ever go anywhere? A few months ago I reported an obvious case of serial voting, and a moderator said they escalated the incident to SE.

Since then, deafening silence.
Another user told me this would probably happen.

Unfortunately it looks like they were right.
So do voting fraud investigations ever go anywhere?

A: Yes, they do. They go into a queue for the community managers to look at. But they didn't always, and there's a reason it's taking so long right now.
Some history
Back in 2015, JNat and I joined the team as support specialists, taking over the ZenDesk support queue where all community tickets landed. Part of that responsibility eventually included a queue where all the CM escalations would land. It was sorted by a special priority system that tried to organize certain types of escalations that might be more urgent over the others. If JNat or I couldn't handle the ticket, we'd pass it along to someone else. But we mostly handled them all ourselves.
About a year and a half ago, that changed completely. Our support queue transitioned to Freshdesk and combined with support for Talent and the newly created Teams product. JNat stayed with the community team and followed a different role that wasn't directly related to support, while I was joined by Grace Note in following to a new "support team" - not being technically a part of the community team anymore. One of the biggest departures from tradition with this change was that only support staff had direct logins with Freshdesk, whereas the entire community team now shared a single login to access stuff they needed.
With regards to CM escalations
Since these escalations were already set up to be emailed to the community support queue, they initially fell onto the support team for handling. Since I was the only one on this team that was familiar with the majority of these tickets and how they were processed, they all got dumped into my personal queue in the support system for me to process whenever I had time.
One rainy day earlier this year, I was asked by my manager what it would take to train the rest of the team to handle these escalations, because no company likes having only one person trained to do specific tasks. I might go on vacation someday, he says. Pondering this thought for a while, "it's probably a lot of work." Most of the support team isn't as familiar with the community or how the site works - at least not enough that they'd fully understand how to process these escalations without basically going through community manager training first.
This sparked an analysis - why is the support team responsible for these? Simple answer: because they were going into our queue and nobody questioned it. But it doesn't make sense for the support team to continue handling these.
The current backlog
So on September 18, I went back to the community team and asked them to come up with some process for their own team to surface and handle these escalations on their own. After all, they are called "community manager" escalations, and the support team are not community managers. I had planned on continuing handling these while that process was created. Unfortunately, around that same time, I got very busy with two other projects that ate up most of the free time I would normally devote to handling those escalations, and handled maybe a dozen over those two months.
Ironically, the exact situation we were trying to avoid by transitioning these back to the community team is what caused the current dilemma, and we ended up with a huge backlog which is still over 250 tickets long.
But they are there, and they are slowly being processed again. That system is in place for bugging community managers to handle them, and the backlog has shrunk over the past month. How fast it continues to shrink depends entirely on what else the CMs have to deal with over time. But we also have to remember that some inappropriate voting is an extremely low priority, and just about anything else that can possibly come up will likely be higher on the list than plundering through a bunch of voting invalidation tickets. But at some point, someone will look at it.


text:
Q: How to "append" Op at the beginning of a TensorFlow graph? I have a GraphDef proto file which I am importing using tf.import_graph_def. Ops can be added at the end of the graph like this:
final_tensor = tf.import_graph_def(graph_def, name='', return_elements=['final_tensor'])
new_tensor = some_op(final_tensor)

But I want to add Ops at the beginning of the graph, so essentially the first Op in the graph_def needs to take the output of my Op as input, how do I do it?

A: Finally found a way to do this. I am sure the function Yarolsav mentioned in the comments does something similar internally.
new_input = graph_def.node.add()
new_input.op = 'new_op_name'  # eg: 'Const', 'Placeholder', 'Add' etc
new_input.name = 'some_new_name'
# set any attributes you want for new_input here
old_input.input[0] = 'some_new_name'  #  must match with the name above

For details about how to set the attributes, see this file.

A: The script @Priyatham gives in the link is a good example how to add node in tf graph_def. name, op, input, attr are 4 required elements. name and op could be assigned, whereas input should use extend and attr should use CopyFrom method for assignment, like:
new_node = graph_def.node.add()
new_node.op = "Cast"
new_node.name = "To_Float"
new_node.input.extend(["To_Float"])
new_node.attr["DstT"].CopyFrom(attr_value_pb2.AttrValue(type=types_pb2.DT_FLOAT))
new_node.attr["SrcT"].CopyFrom(attr_value_pb2.AttrValue(type=types_pb2.DT_FLOAT))
new_node.attr["Truncate"].CopyFrom(attr_value_pb2.AttrValue(b=True))


text:
Q: UMDH/Windbg not compatible DMP file? I'm using UMDH 6.1.7659 out of the latest Windows Debugging Kit.  I'm wanting to try and generate a dmp file that I can look at in WINDBG to investigate a memory leak in an unmanaged 64-bit C++ EXE:
set _NT_SYMBOL_PATH=<.PDB_file_directory>
umdh -p:<valid PID> -f:c:\temp\dump1.dmp

When I try and open up the DMP file in WinDbg (Version 1607), I see this:
Loading Dump File [c:\temp\dump1.dmp]
Could not match Dump File signature - invalid file format
Could not open dump file [c:\temp\dump1.dmp], Win32 error 0n87
"The parameter is incorrect."
**** DebugClient cannot open DumpFile - error 80070057

DUMPCHK on the same DMP file gave me the same result.
Is UMDH not compatible with WINDBG anymore?

A: I believe you got some misunderstanding,
https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-umdh-to-find-a-user-mode-memory-leak
UMDH generates its own data format (a text based data structure), which is clearly not process dump files for WinDbg to analyze.


text:
Q: Fetch a saved game snapshot using a conflict resolution policy I don't understand the documentation here:
https://developers.google.com/android/reference/com/google/android/gms/games/SnapshotsClient#public-abstract-taskdataorconflictsnapshot-open-snapshotmetadata-metadata,-int-conflictpolicy
Calling
getSnapshotsClient().open("slot_name", RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED)
should, logically, force Google Play Games to solve any conflict on its own, and always return the most recent snapshot.
Yet the documentation states that:

If a conflict occurred, the result's isConflict() will return true, and the conflict will need to be resolved using resolveConflict(String, Snapshot) to continue with opening the snapshot.

...which sounds like I'll have to handle the conflict resolution myself. What's the point of specifying a conflict resolution policy then??
What is the exact behavior of this method?
Is the documentation wrong, or am I missing somethig here?


text:
Q: Where does the money given to the icon of the Ferengi Blessed Exchequer go? Ferengi use a sort of piggy bank in the image of the Blessed Exchequer to pray and make offerings of latinum.
Where does that money go?
Do the Ferengi send it to some church somewhere or maybe they keep it (making the offering symbolic only)? I have a hard time thinking of Ferengi as charitable in any sense - though a powerful church-estate does seem 'on brand' for them.

A: According to the EU novel Star Trek: SCE - Caveat Emptor, diligent Ferengi pay donations to something called "the Prophets of the Divine Treasury", a priestly class who function something like a chantry order, speaking the praises of the donor to their god (for a very reasonable fee). It seems likely that bribes placed in the icon of the Blessed Exchequer would be reserved for this use.

A matching pair of latinum lobe buffers and fang sharpeners. A
complete lifetime's wardrobe of the finest Tholian silk (including
underwear). An estate in the Colloid marshes. A brand-new, not
reconditioned, trading schooner with its own captain's yacht. A moon—
maybe two.
Plus, of course, a substantial donation to the Prophets of the Divine
Treasury— ensuring his name was recited in the Annual Tally so that he
might be looked upon favorably by the Blessed Exchequer and the
Celestial Auctioneers. Forg wasn't usually so diligent in his
spiritual devotions, but it never hurt to hedge your bets.


text:
Q: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to iland.hbm.BillDetails` Following are my code where I am fetching data from multiple table and want to print that data.
For fetching data I am using following method
 public List<BillDetails> fetch(long id, long cid) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        List<BillDetails> obj = null;
        try {
            String hql = "select distinct bd,sum(bpds.amount) from BillDetails as bd "
                    + "left join fetch bd.customerDetails as cd "
                    + "left join fetch bd.billProductSet as bpd "
                    + "left join fetch bpd.product as pd "
                    + "left join fetch bd.billPaidDetails as bpds "
                    + "where bd.billNo=:id "
                    + "and bd.client.id=:cid ";

            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("cid", cid);
            obj = query.list();
            tx.commit();

        } catch (HibernateException e) {
            if (tx != null) {
                e.printStackTrace();
                tx.rollback();
            }
        } finally {
            session.close();
        }
        System.out.println("Size is " + obj.size());
        System.out.println("  " + obj.get(0).getBillNo());
        return obj;
    }

BillDetails pojo
public class BillDetails implements java.io.Serializable {
 private Long billNo;
    private CustomerDetails customerDetails;
    private Client client;
    private BigDecimal subTotal;
    private BigDecimal vat;
    private BigDecimal total;
    private String invoiceNo;
    private Date invoiceDate;
    private String status;
    private Timestamp addDate;
    private Set<BillPaidDetails> billPaidDetails = new HashSet(0);
     private Set<BillProduct> billProductSet = new HashSet(0);
    //getter and setter
   }

BillPaidDetails
public class BillPaidDetails implements java.io.Serializable {

    private Long id;
    private Client client;
    private BillDetails billDetails;
    private BigDecimal amount;
    private String paymentMode;
    private Date dt;
    private Timestamp adddate;
}

While printing value at fetch() at System.out.println("  " + obj.get(0).getBillNo());
It is showing
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to iland.hbm.BillDetails.
How to resolve above exception and where the sum(bpds.amount) will store.
Is it possible that sum(bpds.amount) should be store in any desired fields of BillPaidDetails like added a field private BigDecimal totalAmount; where sum will stored.

A: First of all this query can't work as it is. I already responded about the need for including all fetched entities' properties in the group by clause.
You try to select both an entity and a sum, while expecting to fit into a List<BillDetails>.
If you were only selecting BillDetails you'd be fine. But when you want to select more than one entity you need to assign the select to a List<Object[]>:
List<Object[]> obj = null;
...
Object[] bdAndSum = obj.get(0);
BillDetails bd = (BillDetails) bdAndSum.get(0);
Number sum = (Number) bdAndSum.get(1);


text:
Q: Build a balanced panel keeping observations that are repeated every year I would like to keep only the complete observations for all the years, how can I proceed?
I have the following example:
structure(list(variable = c(1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5,
5, 5), Year = c(2010, 2011, 2012, 2010, 2012, 2010, 2011, 2012,
2011, 2012, 2010, 2011, 2012)), class = "data.frame", row.names = c(NA,
-13L))

I would like to get:
structure(list(variable = c(1, 1, 1, 3, 3, 3, 5, 5, 5), Year = c(2010,
2011, 2012, 2010, 2011, 2012, 2010, 2011, 2012)), row.names = c(1L,
2L, 3L, 6L, 7L, 8L, 11L, 12L, 13L), class = "data.frame")

The example is simple, but I need to do this for a vast dataset with the idea of building a balanced dashboard. I appreciate any help.

A: In base R, we can use subset with table
yr <- unique(df$Year)
subset(df, variable %in% names(which(table(variable[Year %in% yr]) ==
       length(yr))))

Or with dplyr, grouped by 'variable', filter those variables having number of distinct 'Year' (n_distinct) same as those in the entire data
library(dplyr)
df %>%
    group_by(variable) %>%
    filter(n_distinct(Year) == n_distinct(.$Year)) %>%
    ungroup
# A tibble: 9 x 2
  variable  Year
     <dbl> <dbl>
1        1  2010
2        1  2011
3        1  2012
4        3  2010
5        3  2011
6        3  2012
7        5  2010
8        5  2011
9        5  2012


text:
Q: how to automatically change the color of selected item in QListWidget I want to change the color of selected item in QListItem, and I find qss may be a solution. And the code is:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class Window(QWidget):

    def __init__(self):
        super().__init__()
        with open('mainStyle.qss', 'r', encoding='utf-8') as file:
            self.setStyleSheet(file.read())
        # self.setStyleSheet('*{font-size: 15px;background-color: rgb(150, 150, 150);}'
        #                    'QListWidget::item:selected{background: rgb(128,128,255);}')
        self.setStyleSheet('QListWidget::item:selected{background: rgb(128,128,255);}')

        layout = QVBoxLayout()
        self.setLayout(layout)

        listWidget = QListWidget()
        layout.addWidget(listWidget)

        w1 = QWidget()
        w1Item = QListWidgetItem()
        w1Item.setSizeHint(QSize(150, 150))

        listWidget.insertItem(0, w1Item)
        listWidget.setItemWidget(w1Item, w1)

        w2 = QWidget()
        w2Item = QListWidgetItem()
        w2Item.setSizeHint(QSize(150, 150))

        listWidget.insertItem(1, w2Item)
        listWidget.setItemWidget(w2Item, w2)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = Window()
    win.show()
    app.exec_()

We can see that the color is changed to be blue when the item is selected.
However, I need to provide a general background color for other widgets. So I change the style from
self.setStyleSheet('QListWidget::item:selected{background: rgb(0,0,255);}')

to
self.setStyleSheet('*{font-size: 15px;background-color: rgb(150, 150, 150);}'
                   'QListWidget::item:selected{background: rgb(0,0,0);}')

Then, I find QListWidget::item:selected do not work. The color do not change when I select a item.
What's the wrong with my code?

A: The problem is that you're setting a QWidget for the item, and since you're using a universal selector (with the wildcard), the result is that all QWidget will have that background color, including those added as item widgets for the list view.
The color you used for the :selected pseudo is only valid for the item painted by the view, since the item widget has its own background set from the universal selector, that background won't be visible.
The solution is to use a proper selector combination ensuring that the rule only matches children of the list view that have a usable selector, and set a transparent color for those widgets.
A possibility is to set a custom property for the widgets that must be set before adding the widgets to the list (otherwise, you need to set the stylesheet after adding them, or request a style.unpolish()).
        self.setStyleSheet('''
            QWidget {
                font-size: 15px;
                background: rgb(150, 150, 150);
            }
            QListWidget::item:selected {
                background: rgb(128,128,255);
            }
            QListWidget QWidget[widgetItem=true] {
                background: transparent;
            }
        ''')

        # ...
        w1 = QWidget()
        w1.setProperty('widgetItem', True)
        # ...
        w2 = QWidget()
        w2.setProperty('widgetItem', True)
        # ...

Another way to do so is to use an "empty" subclass for widgets that are going to be added to the item view:
class CustomItemWidget(QWidget): pass

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setStyleSheet('''
            QWidget {
                font-size: 15px;
                background: rgb(150, 150, 150);
            }
            QListWidget::item:selected {
                background: rgb(128,128,255);
            }
            CustomItemWidget {
                background: transparent;
            }
        ''')

        # ...
        w1 = CustomItemWidget()
        # ...
        w2 = CustomItemWidget()
        # ...

Consider that using universal selectors for colors is usually not a good idea, as it can result in inconsistent behavior, especially for complex widgets: for instance, the scroll bars of scroll areas (like QListWidget) might not be correctly styled and can even become unusable.
If you plan to have a common background color for all widgets, it's better to set the Window role of the application palette:
    app = QApplication(sys.argv)
    palette = app.palette()
    palette.setColor(palette.Window, QColor(150, 150, 150))
    app.setPalette(palette)
    # ...

In this way the current style will know exactly when to use that color as background, or as a component for other UI elements.


text:
Q: Postgresql 12 - ddluser and dmluser for same schema dml permission denied on tables I have created a postgres 12  instance and executed the below command sequence:
psql --host localhost -U postgres -c "CREATE DATABASE mydb"
psql --host localhost -U postgres -d mydb -f /tmp/createdb.sql

The need is to create tables with ddluser and the dmluser can manipulate(insert/select/delete) the contents of the tables that ddluser will create.
The contents of /tmp/createdb.sql are the following:
DROP USER IF EXISTS ddluser;
DROP USER IF EXISTS dmluser;
DROP ROLE IF EXISTS ddlrole;
DROP ROLE IF EXISTS dmlrole;
CREATE USER ddluser WITH PASSWORD '1234';
CREATE USER dmluser WITH PASSWORD '1234';
CREATE SCHEMA myschema;
REVOKE CREATE ON SCHEMA myschema FROM PUBLIC;
REVOKE ALL ON DATABASE mydb FROM PUBLIC;
CREATE ROLE ddlrole;
GRANT CONNECT ON DATABASE mydb TO ddlrole;
GRANT USAGE, CREATE ON SCHEMA myschema TO ddlrole;
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschema FROM ddlrole;
GRANT ddlrole TO ddluser;
CREATE ROLE dmlrole;
GRANT CONNECT ON DATABASE mydb TO dmlrole;
GRANT USAGE ON SCHEMA myschema TO dmlrole;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA myschema TO dmlrole;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO dmlrole;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA myschema TO dmlrole;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT USAGE ON SEQUENCES TO dmlrole;
GRANT dmlrole TO dmluser;

The table I create for example is the below:
CREATE TABLE myschema.accounts (
user_id serial PRIMARY KEY,
username VARCHAR ( 50 ) UNIQUE NOT NULL,
password VARCHAR ( 50 ) NOT NULL,
email VARCHAR ( 255 ) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
    last_login TIMESTAMP );

Output is:
mydb=> select * from myschema.accounts;
ERROR:  permission denied for table accounts
mydb=> exit

A: Assuming that:

*

*the database user running the commands in /tmp/createdb.sql is a superuser (let's say it's postgres)

*the database user running the CREATE TABLE later is ddluser
Your expectation is probably that this command run by the superuser:
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO dmlrole;
will make every object created in myschema have these permissions.
But in fact only objects created by postgres would be affected, because, according to the documentation for ALTER DEFAULT PRIVILEGES:

You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.

(yourself in this context means of course the current db user)
The simplest solution is to switch temporarily to ddlrole in the creation script.
[... statements run by the superuser...]

SET ROLE ddlrole;

ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO dmlrole;

RESET ROLE;

[... rest of statements run by the superuser...]

Then the tables created in the future in myschema will have these permissions when they're created by a member of ddlrole.


text:
Q: Cardinality of the set of truth values in a Heyting-valued model of IZF I've very recently become interested in intuitionistic set theory. I'm now trying to get acquainted with the very basics, and I have a number of small silly questions, that might not make sense due to my current lack of knowledge (apologies if that's the case).

Can the cardinality of the set $\Omega$ of truth values/subobject
  classifier in a Heyting-valued model of intuitionistic ZF be defined
  (internally to the model)?
If so, can it be different from 2? And does it coincide with the
  cardinality of $\Omega$ as an ordinary set?

For example, taking $\Omega$ as the Heyting algebra from the third example here, would its internal cardinality be 2, 3 or undefined?
I've found this article that claims that the cardinality cannot generally be defined in constructive mathematics except for a special type of decidable sets, but the article doesn't go into much detail as to why; it only rules out the existence of a map assigning the cardinality 1 to singletons.

A: Welcome to the wondrous world of intuitionistic set theory!
I don't know your definition of cardinality; mine is: Sets $X$ and $Y$ are of the same cardinality if and only if there exists a bijection $f : X \to Y$. This defines an equivalence relation on the universe; the equivalence classes are called cardinal numbers.
With this definition, every set $X$ has a cardinality, namely the cardinal number represented by $X$ itself. However, in the absence of the law of excluded middle, and to a lesser extent in the absence of the axiom of choice, the thusly-defined cardinal numbers might not enjoy the properties you might expect from them. In particular:

*

*The relation defined by setting $[X] \leq [Y]$ if and only if there exists an injection $f : X \to Y$ might not be a linear order.

*The relation defined by setting $[X] \geq [Y]$ if and only if there exists a surjection $f : X \to Y$ might not be the opposite of the relation $({\leq})$.

*Subsets of sets of the form $\mathbf{n} = \{0,1,\ldots,n-1\}$ might not be of the same cardinality as any $\mathbf{k}$.

Yes, it can happen that $\Omega$, the powerset of the singleton set, is not of the same cardinality as $\mathbf{2} = \{ 0,1 \}$ (whose cardinality is traditionally called "$2$"). The set $\Omega$ is of the same cardinality as $\mathbf{2}$ if and only if the law of excluded middle holds.
Regarding the third Wikipedia example you linked to: Let $H$ be the Heyting algebra of that example. Let $X$ be the locale which has $H$ as frame of opens. We can then build the topos $\mathrm{Sh}(X)$ of sheaves on $X$. This topos will contain a subobject classifier (a certain sheaf), traditionally written "$\Omega$". As with any topos, this topos has an internal language which we can use to reason about the objects and morphisms of the topos in a naive element-based way. From the internal point of view, $\Omega$ is just a set (not a sheaf), and in fact it is the powerset of the singleton set. Like any set, it has some well-defined cardinality. A formalization of your question is: What is this cardinality? Well, $\Omega$ is neither of the same cardinality as $\mathbf{2}$ nor of the same cardinality as $\mathbf{3}$. It still has some cardinality though, trivially so.
Please feel free to ask for clarifications!


text:
Q: Installing MySQL in CentOS without permissions I need to install a MySQL that doesn't need root. The reason for this is that I'm a user in a cluster, so I don't want to mess other people work. Said that, is there a way to have a "portable" MySQL with C++ connections? I don't need workbench, our team will be using shell and VI the whole time.
Already tried this two:  "portable"  and  MySQL RPM installation .
Thanks!


text:
Q: How to install msi one after another .net? I've made an vb.net application that requires crystal reports 10 and I need to redistribute my application.
So...
I need to install XP SP3 THEN -> .net framework 4 THEN -> crystal reports redistuble package and my application  and that packages are installed in series one after another (means that you have to wait for the first package to finish its installation and then run the next installation package) not simultaneously at one time.
Some users are not professional at computer and get nervous about installing those files in series SO I want a small application or an installer that takes over that operation and runs the files one after another any advice?

A: I use a great free installer script called Inno Setup. It has many examples on how to install .NET Framwork and Crystal Reports. The installer will allow you to chain multiple packages together and create a simple installer UI for your users. Here is a great pre-made script that will check and install the .NET Framework. There are many more examples on google.

A: You need a bootstrapper. You can make one using a tool like ClickOnce or WIX (with the Burn bootstrapper introduced in 3.6).

A: I have used dotNetInstaller on several occasions with success. Try it first. It is available on codeplex.

A: You are missing two important points:
1) You are taking a huge risk assuming you can install an entire Windows Service pack without error.
2) XP SP3 is NOT redistributable.

The Microsoft Download Center site is your only authorized web source
  for downloading a licensed copy of Windows XP Service Pack 3. To
  report a website offering unlicensed copies of Windows XP SP3 for
  download, please send e-mail to: piracy@microsoft.com or visit
  http://www.microsoft.com/piracy/ReportingUs.mspx.

Tell your users to turn on Windows Update and they will get XP SP3 and .NET 4.0 automatically.  All your installer should do is check that those requirements are met and abort if they are not there. (AppSearch and LaunchConditions tables)