Q:

play/pause button image in notification ,Android

I have implemented music player which fires a custom notification when stream audio is playing.
Everything is working and I can play/pause the audio using the button in the notification. The only problem is the image button: it can't change the image on a click of a button to indicate play/pause.
Using remoteViews.setImageViewResource() in RemoteReceiver is not working. The control is done using BroadcastReceiver and this is the code of firing the notification from the player activity:
  public void setNotification(String songName){
      String ns = Context.NOTIFICATION_SERVICE;
      NotificationManager notificationManager = (NotificationManager) getSystemService(ns);

      @SuppressWarnings("deprecation")
      Notification notification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis());

      RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_view);
      notificationView.setImageViewResource(R.id.button1, R.drawable.pause);
      notificationView.setTextViewText(R.id.textView1, songName);

      //the intent that is started when the notification is clicked (works)
      Intent notificationIntent = new Intent(this, PlayerActivity.class);
      PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

      notification.contentView = notificationView;
      notification.contentIntent = pendingNotificationIntent;

      Intent switchIntent = new Intent("com.example.test.ACTION_PLAY");
      PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

      notificationView.setOnClickPendingIntent(R.id.play_pause, pendingSwitchIntent);
      notificationManager.notify(1, notification);
  }

The notification.xml content is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ImageView
        android:layout_alignParentLeft="true"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@drawable/ic_launcher"
        android:id="@+id/imgAppIc" />

    <TextView
        android:layout_toRightOf="@id/imgAppIc"
        android:singleLine="true"
        android:id="@+id/textView1"
        android:ellipsize="marquee"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="10dp"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:scrollHorizontally="true"
        android:layout_width="170dp"
        android:layout_height="wrap_content"/>

    <ImageButton
        android:id="@+id/play_pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/play"

         />

</RelativeLayout>

this is the RemoteRecivier class
public class RemoteControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.notification_view);

        if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){
            if(mediaplayer.isPlaying()){
                mediaplayer.pause();

                remoteViews.setImageViewResource(R.id.button1, R.drawable.play);
            }
            else {
                mediaplayer.start();
                remoteViews.setImageViewResource(R.id.button1, R.drawable.pause);
            }
        }
    }
}

and finally, the manifest is
 <receiver android:name=".RemoteControlReceiver">
            <intent-filter>
                <action android:name="com.Music.app.ACTION_PLAY" />
            </intent-filter>

        </receiver>

<activity android:name="PlayerActivity" />

A:

You have to set your notification.contentView to the new remoteView after it was changed so it can update the notification view itself.
Meaning, after you receive the action in your BroadcastReceiver, re-build your notification with the desired button display ( pause or play )
Hope this helps

A:

This should work. Just make your notification and notificationManager a static global variable.
public class RemoteControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){
            if(mediaplayer.isPlaying()){
                mediaplayer.pause();
                notificationView.setImageViewResource(R.id.button1, R.drawable.play);
                notification.contentView = notificationView;
                notificationManager.notify(1, notification);
            }
            else {
                mediaplayer.start();
                notificationView.setImageViewResource(R.id.button1, R.drawable.pause);
                notification.contentView = notificationView;
                notificationManager.notify(1, notification);
            }
        }
    }
}


Q:

How to prove that $P (X ≥ k) = (1 - p)^k$? Can I start with $P(X≥k)=1−P(X<k)$?

The exercise says:

Let $X$ ~ $G (p)$. Prove that $P (X ≥ k) = (1 - p)^k$, with $k ∈ N$.

My try to demonstrate it:

$P (X ≥ k) = 1-P(X<k)$
$P (X+1 ≥ k+1) = 1-P(X+1<k+1) = 1-P(X⩽k)$
$P (X+1 ≥ k+1) = 1-((1-p)^kp)$
$P (X+1-1 ≥ k+1-1) = 1-(((1-p)^kp)-1)$
$P (X ≥ k) = 1-(((1-p)^kp)-1)$

A:

$\bbox[0.5ex]{X\sim\mathcal{Geo}_0(p)}$ means $X$ is a count of failures before a success in an indefinite sequence of independent Bernoulli trials with identical success rate $p$.
$\bbox[0.5ex]{\mathsf P(X\geq k)\quad [k\in\Bbb N]}$ is then the probability for the first success occurring after at least $k$ consecutive failures.   Which is simply the probability for obtaining $k$ consecutive failures.
$$\mathsf P(X\geq k)=(1-p)^k$$
Of course you can show this by using $\bbox[0.5ex]{\mathsf P(X=k)~=~(1-p)^kp}$ (but why is that so)?
$$\begin{align}\mathsf P(X\geq k) &= \sum_{j=k}^\infty (1-p)^j p
\\ & = (1-p)^kp\sum_{j=k}^\infty (1-p)^{j-k}
\\ &  \vdots
\end{align}$$


Q:

REST API design with async (polling) operations and errors that are found "later"

Given this resource representation:
Request/id/Resource

which is made to support async Resource creation (you submit a Request first, then use the id to poll for Resource until you get 200 OK), what would be a good status code to return when errors of original Request are detected during the polling phase?
Longer explanation:
So the main problem is that submitting the original Request can have some invalid parameters, and for those returning 400 Bad Request is fine. Trouble is, some of these parameters can be validated only later, during the polling phase (while the actual Resource is being created), so we need to propagate this information to the user. What we currently return for errors during the process is 500 InternalServerError, but if we find that something was wrong with the initial Request this is hardly an internal server error. Returning 400 Bad Request comes to mind, but in reality nothing is wrong with the polling call itself (Bad Request for me says that the call you are right now is bad).

A:

I would say don't do it that way. Instead, do something like:
POST /requests
{
    "id": 12,
    "status": "Pending"
}

GET /requests/{id}=12
{
    "id": 12,
    "status": "Error",
    "cause": "Invalid parameter: 'bob' is not a number"
}

GET /requests/{id}=15
{
    "id": 15,
    "status": "Complete",
    "resource": "/resources/5"
}

GET /resources/5
{
    "id": 5,
    ...
}

GET /requests will return 200 OK and indicate whether there's a problem or not. Clients can poll their request looking for "error" or "resource" (or however you want to structure it - I didn't think much about entities, only URIs).


Q:

How to manage rewards for small delegators?

What would be the best way to transfer rewards for smaller delegators? For instance for those who have delegated less than 1XTZ.
Usually their staking capital generates not so much in terms of rewards. In order to transfer them their rewards, the baker would have to spend on transaction about half of the rewards generated by them.
So what is a solution here?

A:

The best solution is to apply the minimum payout rule. So, you will pay the delegator only when this value is reached.
For example, let MinPayout = 0.01, then:
Cycle    Reward    Debt    Payout
#n       0.004     0.004   ---
#n+1     0.004     0.008   ---
#n+2     0.004     0.012   0.012

That's it =)


Q:

Ubuntu 12.04 /usr/bin/ld: error: cannot find -lGL

I istalled the fglrx ATI/AMD proprietary driver and now when i try to launch my OpenGL/SDL project i receive this message: /usr/bin/ld: error: cannot find -lGL
I run Ubuntu 12.04 desktop, 64-bit. HD6870 [ATI Radeon HD 6800 Series]

A:

Installing fglrx-glx should help you, those are libGL's for proprietary AMD/ATI drivers.


Q:

Creating a method to modify elements in an array in Ruby with 2 arguments, one of them being the original array

I would like to create a method, mod_method(array, n) , where array is an array and n is a number. mod_method should take number n and add it to all internal numbers in array and return that new array.
For example, using array = ["I", "have", 3, "to", 4, "hours"], how would I find mod_method(array, 1) such that
mod_method(array,1)
 => ["I", "have", 4, "to", 5, "hours"]

I'm a noob and was only able to do this using the already defined array and number (let's use 1), as such:
array = ["I", "have", 3, "to", 4, "hours"]
=>[[0] "I",
  [1] "have",
  [2] 3,
  [3] "to",
  [4] 4,
  [5] "hours"]

numbers = array.values_at(2, 4)
=> [
  [0] 3,
  [1] 4

mod = numbers.map{|x| x + 1}
=> [
  [0] 4,
  [1] 5]
new_array = ["I", "have", mod[0], "to", mod[1], "hours"]
=> ["I", "have", 4, "to", 5, "hours"]

I have no idea how to do it with undefined arguments for the mod_method.

A:

Write the method as
def mod_method(array, n)
  array.map { |i| i.is_a?(Fixnum) ? (i + n) : i }
end

array = ["I", "have", 3, "to", 4, "hours"]
mod_method(array, 1) # => ["I", "have", 4, "to", 5, "hours"]

If your array contains both Fixnum and Float instances, and you want to add 1 with either of those instances. Then use the below method :-
def mod_method(array, n)
  array.map { |i| i.kind_of?(Numeric) ? (i + n) : i }
end

array = ["I", "have", 3.2, "to", 4, "hours"]
mod_method(array, 1) # => ["I", "have", 4.2, "to", 5, "hours"]

A:

Here is what I would do.
def mod_method(array,n)
  array.map do |e|
    e.is_a?(Integer) ? e + n : e
  end
end


Q:

Minimal Least Common Multiplier for $n$ distinct integers

Let $n\in\mathbb N^+$ be a positive integer.
I am trying to find a set of $n$ distinct positive integers with minimal LCM.

What is the set of $n$ distinct integers with minimal LCM?
What is the asymptotics of this LCM as a function of $n$?

Observe that we can choose the set to be $\{1,...,n\}$, which would give a bound of $2^{O(n)}$. However, I'm not sure that this is tight.
For example, if $n=9$ then LCM$(\{1,2,3,4,5,6,7,8,9\})=2520$, but we have
LCM$(\{1,2,3,4,6,8,12,16,24\})=48$.

A:

ADDED: see Nicolas on highly composite
Nicolas  Full List
you can get a predictably small LCM by taking the first Superior Highly Composite Number with number of divisors at least your target number, you are calling that $n$
https://en.wikipedia.org/wiki/Superior_highly_composite_number
For your $7 \leq n \leq 12,$ you can get a small LCM by taking $n$ divisors of $60$
For your $13 \leq n \leq 16,$ you can get a small LCM by taking $n$ divisors of $120$
For your $17 \leq n \leq 24,$ you can get a small LCM by taking $n$ divisors of $360$
For your $25 \leq n \leq 48,$ you can get a small LCM by taking $n$ divisors of $2520$


Q:

How to switch between text/headings with textarea with jQuery?

I have some HTML code that I want to add inline-editable box to. I want to be able to edit the content clicked. Right now the text are replaced with textarea containing the text value. But I'm not able to type in new values in the textarea.
Any ideas on why I cant edit the contents of the textarea?

$("h1,h2,h3,h4,h5,h6,p").click(function() {
  var element = $(this);

  $(element).after().html("<textarea class='form-control'>" + $.trim($(element).text()) + "</textarea>");

  $("textarea").mouseout(function() {
    element.html($(this).val());
  });
});

This is a h2

Some text here

A:

Set custom data-* property to check the element is in editing state or not otherwise on each click event it would generate textarea repeatedly.

$("h1,h2,h3,h4,h5,h6,p").click(function() {
  var element = $(this);
  if (!element.data('editing')) {
    element.data('editing', true);
    $(element).html("<textarea class='form-control'>" + $.trim($(element).text()) + "</textarea>");

    $("textarea").mouseout(function() {
      element.html($(this).val());
      element.data('editing', false);
    });
  }
});

This is a h2

Some text here

FYI : In your code after() method doesn't have anything do which is useless actually.

Also which is not a good practice to put textarea inside the h1 tag so completely replace it with the textarea which also avoid the problem in your code.

$(document).on('click', "h1,h2,h3,h4,h5,h6,p", function() {
  var $element = $(this);
  var $text = $("<textarea class='form-control'>" + $.trim($element.text()) + "</textarea>");
  $element.replaceWith($text);
  $text.mouseout(function() {
    $element.text(this.value);
    $(this).replaceWith($element);
  });
});

This is a h2

Some text here

I think it's better to use HTML5 contenteditable attribute.

This is a h2

Some text here


Q:

Rails 3 - Speed up Console Loading Time

I am wondering if there is any relatively easy way to speed up my console load time, which is starting to approach 30 seconds.  I have a lot of subclasses whose methods don't seem to be affected by reload! so I end up opening and closing the console a lot.  IRB loads lightning quick.
Do I have too many gems?  How do I go about timing the load tasks so I can see what is taking up the most time?  As you can see, I've already tried the dev-boost gem to no avail.  The app is fine in Passenger, it's just the console loading that bugs the crap out of me.  Running on MBP OSX 10.6.6 with 2.4GHz and 4GB RAM.  Not using RVM.
Versions:
Ovid$ rails -v
Rails 3.0.3
Ovid$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10]

Memory:
Ovid$ vm_stat
Mach Virtual Memory Statistics: (page size of 4096 bytes)
Pages free:                         118818.
Pages active:                       341320.
Pages inactive:                      99490.
Pages speculative:                  310576.
Pages wired down:                   112527.
"Translation faults":             23097323.
Pages copy-on-write:               1270961.
Pages zero filled:                13836659.
Pages reactivated:                      36.
Pageins:                            165761.
Pageouts:                                0.
Object cache: 28 hits of 760846 lookups (0% hit rate)

Gemfile:
source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'mysql2'
gem 'foreigner'
gem 'haml'
gem 'capistrano'
gem 'nokogiri'

#web services
gem 'yammer4r'
gem 'ruby-freshbooks'

#authentication gems from nifty generator
gem "bcrypt-ruby", :require => "bcrypt"
gem "mocha", :group => :test
gem 'authlogic'

#dev
group :development do
  gem 'rails-dev-boost', :git => 'git://github.com/thedarkone/rails-dev-boost.git', :require => 'rails_development_boost'
end

#testing
group :test do
  gem 'database_cleaner'
  gem 'cucumber-rails'
  gem 'cucumber'
  gem 'rspec-rails'
  gem 'spork'
  gem 'launchy'
  gem 'machinist'
  gem 'faker'
  gem 'capybara'
end

Thank you very much!

A:

I finally found my startup bottlenecks using Benchmark. In particular, navigate to the bundler gem and in lib/bundler/runtime.rb, find the line that does Kernel.require and wrap it like this:
puts Benchmark.measure("require #{file}") {
  Kernel.require file
}.format("%n: %t %r")

You may have to add require 'benchmark' somewhere in your app, like in config/boot.rb. That will show you how long it takes to require each gem. I can't guarantee your results will match mine, but I had a few gems that were taking over a second to load compared with sub-millisecond for most. A few were gems that I didn't need for developing but I did need for some tasks in the development environment, e.g. capistrano, shoulda. I benchmarked other areas of startup (initializers, etc), but couldn't find any significant bottlenecks.
I haven't yet figured out a clean way to configure the app to only load those for tasks where they are really needed. Possibly, I could create an environment called :speedy and use RAILS_ENV=speedy rails s/c for startup when I know I don't need those gems. Then in Gemfile, I could use group :speedy to exclude those gems in certain cases.
All that said, the biggest startup annoyance for me is having to load the entire environment to run a rake task. I could probably exclude most gems for that, but Gemfile would start to get messy so I don't know if it's worth it.

A:

Slightly adapted form that is copy-pastable, wraps all requires, and provides sortable output:
# Add this to the top of boot.rb
require 'benchmark'
def require(file)
  puts Benchmark.measure("") {
    super
  }.format("%t require #{file}")
end

Then you can execute no-op to see them:
rails runner 1

Or sort them and show the top 50:
rails runner 1 | sort -nr | head -n 50

A:

You can speed it up by adding :require => nil to the slow Gemfile entries and require them manually.
e.g.
gem 'jammit', :require => nil

I also addressed this issue in a meetup i've had.
This seems to be a bug in ruby 1.9.2 (see comments of this patch: https://gist.github.com/1008945)
You can fix it by patching your 1.9.2 by the gist i just linked or upgrading to 1.9.2-head or 1.9.3-head.


Q:

how to set default charset while create new field

Is there any command in mysql that makes the following:
if I create a new field and I set the type to TEXT than it automatically knows that by this I mean not latin1_swedish_ci but utf8_hungarian_ci charset.
I would like to apply this changes to the whole database without create a new table.

A:

You can specify this option in a field definition - CREATE TABLE Syntax, ALTER TABLE Syntax.
Try this ALTER statement -
ALTER TABLE table1
  ADD COLUMN column2 VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_hungarian_ci DEFAULT NULL AFTER column1;


Q:

Javascript Object Prototype Reference

As per my knowledge, the second case below should be true, but in fact it is false.  So why is it not true?
Case 1
     var P = function(){};
         P.prototype.get = function(){};

    var p = new P,q = new P;
    console.log(q.__proto__ === p.__proto__) //true

Case 2
var PP = function(){
    var P = function(){};
    P.prototype.get = function(){};
    return new P;
};

var p = PP(), q = PP();
console.log(q.__proto__ === p.__proto__) //false

A:

In the first case, P and get() are predefined globals.  In the second, they're local to the function that defines PP, hence, a different reference for each instance.


Q:

Django EmailValidator validating trailing dots

I'm using Django 1.9, and EmailValidator seems to be validating trailing dots in email ids.
faulty_email = 'sid@h.in.'

user.email = faulty_email
user.save()

The above piece of code runs smoothly even though email is an EmailField, which has EmailValidator. The weird thing is, when I run the validation manually, it throws a ValidationError.
In [1]: from django.core.validators import validate_email

In [2]: faulty_email = 'sid@h.in.'

In [3]: validate_email(faulty_email)
---------------------------------------------------------------------------
ValidationError        Traceback (most recent call last)
<ipython-input-3-bdbbd57d5fe1> in <module>()
----> 1 validate_email(faulty_email)

/usr/local/lib/python2.7/dist-packages/django/core/validators.pyc in __call__(self, value)
    201             except UnicodeError:
    202                 pass
--> 203             raise ValidationError(self.message, code=self.code)
    204
    205     def validate_domain_part(self, domain_part):

ValidationError: [u'Enter a valid email address.']

Does anyone know what the issue is?

A:

When you save() a model you’re only telling Django to commit the object to the database. It doesn’t validate during save. It will throw database exceptions if the fields don’t have the format expected by the database but an EmailField is just a charfield in your db. You should always validate your models before saving them:
user.email = faulty_email
try:
    user.full_clean()
except ValidationError as e:
    print(e)
else:
    user.save()

When using a ModelForm you first validate the form (check form.is_valid()) then save it.


Q:

How to set SharePoint list view 'Item Limit' with the option "Display items in batches of the specified size." programmatically

How to set SharePoint List View 'Item Limit' programmatically with the option 'Display items in batches of the specified size.' selected.
By default, 'Limit the total number of items returned to the specified amount.' option is selected. I want to change it to 'Display items in batches of the specified size.'

A:

Please try below mentioned code
    using System.Net;
    using Microsoft.SharePoint.Client;

    namespace ClientObjectModelConsoleApplication
    {
      class Program
      {
        static void Main(string[] args)
        {
          ClientContext clientContext = new ClientContext("http://hercules");
          clientContext.Credentials = new NetworkCredential("Administrator", "12345");
          string listName = "My Custom List", viewName = "All Items";

          // true is "Display items in batches of the specified size"
          // false is "Limit the total number of items returned to the specified amount"
          bool paged = true;

          List list = clientContext.Web.Lists.GetByTitle(listName);
          View view = list.Views.GetByTitle(viewName);
          view.Paged = paged;
          view.Update();
          clientContext.ExecuteQuery();
        }
      }
    }


Q:

store password with Windows Hello

I want to store and retrieve a password with Windows Hello. The user can choose at login time if he wants to input his password manually, or if he wants to use Windows Hello to unlock (which then retrieves the last used password, and fills it in for the user).
If Windows Hello is setup correctly there are two use cases in the doc.
One to just unlock:
UserConsentVerificationResult consentResult = await UserConsentVerifier.RequestVerificationAsync("userMessage");
if (consentResult.Equals(UserConsentVerificationResult.Verified))
{
   // continue
}

and one to sign a message from the server:
var openKeyResult = await KeyCredentialManager.OpenAsync(AccountId);
if (openKeyResult.Status == KeyCredentialStatus.Success)
{
    var userKey = openKeyResult.Credential;
    var publicKey = userKey.RetrievePublicKey();
    //the message is the challenge from the server
    var signResult = await userKey.RequestSignAsync(message);

    if (signResult.Status == KeyCredentialStatus.Success)
    {
        //the with the private key of the user signed message
        return signResult.Result;
    }
}

Both is not very useful for my use-case: I want a symmetric way to store and retrieve the password.
My question in short:
Is there a way to symmetrically store data with Windows Hello?
relevant docs:
https://docs.microsoft.com/en-us/windows/uwp/security/microsoft-passport

A:

I have solved this problem by encrypting / decrypting the secret I wanted to store using a password generated with Windows Hello. The password was a signature over a fixed message.
A complete code example (untested) to illustrate my point:
const accountId = "A ID for this key";
const challenge = "sign this challenge using Windows Hello to get a secure string";

public async Task<byte[]> GetSecureEncryptionKey() {
    // if first time; we first need to create a key
    if (firstTime) {
        if (!await this.CreateKeyAsync()) {
            return null;
        }
    }

    // get the key using Windows Hellp
    return await this.GetKeyAsync();
}

private async Task<bool> CreateKeyAsync() {
    if (!await KeyCredentialManager.IsSupportedAsync()) {
        return false;
    }

    // if app opened for the first time, we need to create an account first
    var keyCreationResult = await KeyCredentialManager.RequestCreateAsync(AccountId, KeyCredentialCreationOption.ReplaceExisting);
    return keyCreationResult.Status == KeyCredentialStatus.Success);
}

private async Task<byte[]> GetKeyAsync() {
    var openKeyResult = await KeyCredentialManager.OpenAsync(AccountId);

    if (openKeyResult.Status == KeyCredentialStatus.Success)
    {
        // convert our string challenge to be able to sign it
        var buffer = CryptographicBuffer.ConvertStringToBinary(
            challenge, BinaryStringEncoding.Utf8
        );

        // request a sign from the user
        var signResult = await openKeyResult.Credential.RequestSignAsync(buffer);

        // if successful, we can use that signature as a key
        if (signResult.Status == KeyCredentialStatus.Success)
        {
            return signResult.Result.ToArray();
        }
    }

    return null;
}

The full source is on github, and shows how I have integrated these concepts into the application.


Q:

Workaround for NHibernate DB2 inexact query bug?

Does anyone know a workaround for NH-2436?
Basically, when you concatenate a parameter in the case of (% || ? || %) DB2 requires it to be cast as in CAST((% || ? || %) AS VARCHAR(255)) which NHibernate does not do, otherwise an exception is thrown.
Is there some way to work around this and do a parameter based LIKE query using NHibernate against DB2?

A:

Well, if you throw fluentNhibernate, Linq, and automapping out the window I was able to work around this with a named query.


Q:

Accesssing cookies of another domain using Iframes and Javascript

Using Iframe we can embed webpages of another domain provided the X-Frame-Options isn't set to SAMEORIGIN. This also loads the cookie inside the iframe.
Now, one can access this cookie if it's in the iframe box using document.cookie. I wanted to ask if it's possible to send this cookie by mailing this to oneself (by writing a script inside the iframe tag).
My Opinion:
This is possible if we can write the script tag inside the iframe tag in the web-page. But it doesn't seem to work in my case.
We can also insert a script dynamically inside the iframe. I wanted to know if it's possible or not.
I think it might not work since the iframe loaded might overwrite all the content inside the iframe tag and the script tag might not work.
If this is the case then why there is a iframe closing tag at all. Can't it be only: iframe src="https://abc.def.com" tag to define iframes?

A:

Same Origin Policy ensures that you cannot read or modify the content of a page with different origin. In case of the iframe this means that the parent frame can fully replace the iframe (and thus changing the origin) but it cannot read or modify the contents of the iframe has a different origin.
Thus reading a cookie cross-origin from an iframe will only work if the content of the iframe explicitly communicates with the parent frame (like with postMessage) to share the cookie value. Usually this is not the case with unrelated origins but if you find a XSS attack at the iframes origin then you might be able to trick the iframe into sending this cookie to the parent frame.
Note that X-Frame-Options is unrelated to the same origin policy. It is only used to define if a site can be put into an iframe or not. This is important to defend against Clickjacking or other UI-Redressing attacks.


Q:

Exec SQL error because of single quotes inside

I have the following exec query:
EXEC (
        'SELECT (SELECT Count(*) AS Count_Id FROM ns_customer WHERE external_id IN (
        ' RW00363075 ',' RW00336566 ',' RW00365438 ',' RW00343570 ')  ) AS Count_Id,
        ACH_allowed, CC_allowed, DD_allowed FROM ns_customer
        WHERE external_id IN (' RW00363075 ',' RW00336566 ',' RW00365438 ',
        ' RW00343570 ')'
        );

After execution I get an error:

SQL statement: Incorrect syntax near 'RW00363075'.; Caused by:
  Incorrect syntax near 'RW00363075'.

How can I solve this?
Thanks

A:

Escape single quotes with two single quotes
EXEC('SELECT (SELECT Count(*) AS Count_Id FROM ns_customer WHERE external_id IN (''RW00363075'',''RW00336566'',''RW00365438'',''RW00343570'')  ) AS Count_Id, ACH_allowed, CC_allowed, DD_allowed FROM ns_customer
    WHERE external_id IN (''RW00363075'',''RW00336566'',''RW00365438'',''RW00343570'')');

A:

The answer to your specific question is to double up the single quotes.  However, (assuming that you are using SQL Server), your query would be more simply written as:
SELECT COUNT(*) OVER () as Count_Id, ACH_allowed, CC_allowed, DD_allowed
FROM ns_customer
WHERE external_id IN ('RW00363075', 'RW00336566', 'RW00365438', 'RW00343570')

Or, as I prefer, use sp_executesql:
declare @sql nvarchar(max);
set @sql = '
SELECT COUNT(*) OVER () as Count_Id, ACH_allowed, CC_allowed, DD_allowed
FROM ns_customer
WHERE external_id IN (''RW00363075'', ''RW00336566'', ''RW00365438'', ''RW00343570'')';

exec sp_executesql @sql;

If you are going to learn how to do this, you might as well learn the right way.  sp_executesql is superior to exec() because it allows you to pass parameters in and out of the query.  Learning to use it first is simpler than learning it later.


Q:

Django multiple User profiles/subprofiles

I am trying to create an intranet/extranet with internal/external user-specific profiles, with a common generic profile.  I've looked at several answers on this site, but none specifically address what I'm looking to do.  Below are the (stripped down) files I have so far.
What's the best way to create a profile model, with subprofiles for each user type?  I'm trying not to require a custom authentication backend if at all possible.
https://gist.github.com/1196077

A:

I have a solution I dont Know if its the best but see it:
models.py
from django.db import models
from django.contrib.auth.models import User

class Pollster(models.Model):
    """docstring for Polister"""
    user   = models.OneToOneField(User, related_name = 'polister', unique=True)
    cedule = models.CharField( max_length = 100 )

class Respondent(models.Model):
    """ """
    born_date   = models.DateField( verbose_name=u'fecha de nacimiento' )
    cedule      = models.CharField( max_length = 100, verbose_name=u'cedula' )
    comunity    = models.CharField( max_length = 100, verbose_name=u'comunidad')
    phone       = models.CharField( max_length = 50, verbose_name=u'telefono')
    sanrelation = models.TextField( verbose_name =u'Relacion con SAN')
    user        = models.OneToOneField( User, related_name = 'respondent')

I create a MiddleWare: so
i create middleware.py
from django.contrib.auth.models import User
from encuestas.models import Pollster, Respondent

class RequestMiddleWare(object):
    """docstring for """
    def process_request(self,request):
        if isPollster(request.user):
            request.user.userprofile = Pollster.objects.get( user = request.user.id)
        elif isRespondent(request.user):
            request.user.userprofile = Respondent.objects.get(user = request.user.id)
        return None

def isPollster(user):
    return Pollster.objects.filter(user=user.id).exists()

def isRespondent(user):
    return Respondent.objects.filter(user=user.id).exists()

and you need to configure settings.py for the middleware:
add to MIDDLEWARE_CLASSES atribute:
'encuestas.middleware.RequestMiddleWare'

encuestas is my_app name
middleware is the Middleware file
RequestMiddleWare is the middleware class

A:

You need a combination of storing additional information about users and model inheritance.
Basically, you'll need the generic User models we all know and either love or hate, and then you need a generic profile model that is your AUTH_PROFILE_MODULE setting.
That profile model will be a top-level model, with model subclasses for internal and extrernal users. You probably don't want an abstract model in this case since you'll need a common profile table to load user profiles from with User.get_profile().
So...I think the major thing you want to change is to make your Associate, External, etc. models inherit from your Profile model.


Q:

C# linq lambda expression for OR in a list

I have this scenario in which i query with FindByMany (which takes the lambda and returns post if user country and category matches, (as seen in the "else")
But now i need to customize the return with prefered subcategories from users, so what im doing is query n times foreach subcategory and just addRange. I dont want to query 5 times the db if the user has 5 subcategories as favorite, but i dont know how to apply a dinamic OR.
So my question is, how can this code be improved for performance.
var posts = new List<Content>();
if (request.UserId != 0)
{
   var user = _userRepository.FindBy(u => u.Id == request.UserId);
   if (user != null && user.SubCategories.Any())
   {
      foreach (var temp in user.SubCategories.Select(subCategory => _contentRepository.FindManyBy(
         c =>
           c.Country.Id == country.Id && c.Category.Id == theCategory.Id &&
           c.SubCategory.Id == subCategory.Id).ToList()))
      {
         posts.AddRange(temp);
      }
   }
}
else
{
   posts = _contentRepository.FindManyBy(
           c => c.Country.Id == country.Id && c.Category.Id == theCategory.Id
      ).ToList();
}

A:

Could you not just materalise the sub-categories into a list, and then in your FindBy use a thatlist.Contains()?


Q:

Radio-button can't focus in Rails with form-for

I want to implement that the radio button can focus when it been clicked.
Here is the GIF:

Code
<%= form_for [:admin, @question] do |f| %>

    <%= f.label :title %>
    <%= f.text_field :title, :class => "form-control" %>

    <%= f.label :category_id %>

      <% Category.all.each do |category| %>
        <label class="btn btn-default <%= (category.id == f.object.category_id)? 'active' : '' %>">
          <%= f.radio_button :category_id, category.id %>
          <%= category.title %>

      <% end %>

  <%= f.submit "Submit", data: { disable_with: "Submitting..." }, class: "btn btn-primary" %>

<% end %>

Any idea, please.

A:

I assume you are using bootstrap 4, try to check that you properly including js files
https://github.com/twbs/bootstrap-rubygem/blob/master/README.md
//= require jquery3
//= require popper
//= require bootstrap


Q:

Intercept All Relative Paths

Is it possible to intercept all and any relative paths used in an application and remove/edit a portion of it before the absolute path is evaluated?
Example:
In mvc view page-
<%= Html.Image("~/{somefolder}/logo.png") %>

I want to intercept the relative path "~/{somefolder}/logo.png" and replace "{somefolder}" with a folder location retrieved through some logic (database, if/else etc.)

A:

You could create a helper that does that.
For example...
public static string LinkedImage(this HtmlHelper html, string url)
{
  Regex regex = new Regex("({(.*?)})");//This is off the top of my head regex which will get strings between the curly brackets/chicken lips/whatever! :).
  var matches = regex.Matches(url);

  foreach (var match in matches)
  {
    //Go get your value from the db or elsewhere
    string newValueFromElsewhere = GetMyValue(match);
    url = url.Replace(string.Format("{{0}}", match), newValueFromElsewhere);
  }

  return html.Image(url);
}

In terms of looking to resolve the url itself, you might want to look here at Stephen Walther's blog.


Q:

$gh = hg, \ \gcd(|g|, |h|) = 1\Rightarrow|gh| = |g||h|\ \ (|a|$ = order of element $a)$

Let $G$ be a group and $g,h \in G$. I need to prove that if $g$ and $h$ commute and their orders are coprime, then $|gh| = |g||h|$, that is, the order of their product is the multiple of their orders.
Since $gh = hg$, then $(gh)^{ lcm(|g|, |h|)} = e$, so, $|gh|$ divides $lcm(|g|, |h|)$. Since $\gcd(|g|, |h|) = 1$, then $lcm(|g|, |h|) = |g||h|$.
So, $|gh|$ divides $|g||h|$.

A:

You can find $|gh|$ divides $|g||h|$ already from $$(gh)^{|g||h|}=g^{|g||h|}h^{|h||g|}=e^{|h|}e^{|g|}=e.$$
On the other hand,
$$ e=(gh)^{|gh||h|}=g^{|gh||h|}h^{|gh||h|}=g^{|gh||h|}$$
implies $|g|$ divides $|gh||h|$. As $\gcd(|g|,|h|)=1$, we conclude $|g|$ divides $|gh|$. Similarly, $|h|$ divides $|gh|$. Again using $\gcd(|g|,|h|)=1$, we finally have $|g||h|$ divides $|gh|$.

A:

$1 = (gh)^k\! = g^k h^k\Rightarrow\, g^k\! = h^{-k} =: \color{#c00}f\in \langle g\rangle\cap\langle h\rangle\Rightarrow\,  |f|\ {\Large\vert}\ \overbrace{|g|,|h|}^{\rm coprime}\,\Rightarrow |f|=1\Rightarrow \color{#c00}{f = 1}$
So $\,\ (gh)^k = 1\iff g^k =\color{#c00} 1 = h^k\!\iff |g|,|h|\mid k\iff\! |g|\,|h|\mid k,\,$ thus $\,|gh| = |g||h|$


Q:

Should a Weakref object be called every time it's accessed?

I have a class structure where the instance of one class needs to hold a reference to an instance of the other. Reading through some other posts, the best (safest) way to do this, is using weakref. It would look like this:
class ClassA:
    def __init__(self):
        self.my_b = ClassB(self)
        self.some_prop = 1

class ClassB:
    def __init__(self, some_a):
        self.some_a = weakref.ref(some_a)

The question that I have, is that to access some_prop through an instance of ClassB, you'd have call the reference which will make the object available, as per documentation:
self.some_a().some_prop

However, my question is whether calling the reference should be done every time. Can't we just call the weakref in init? I.e.
self.some_a = weakref.ref(some_a)()

and then access it (more naturally) like
self.some_a.some_prop

I have a feeling the first option is preferred, but I am trying to understand why. In my case there is no way that the referenced object gets deleted before the other.

A:

For completeness' sake I will write this answer, which is a copy of @sanyash 's comment.

Python garbage collector is clever enough to detect cyclic references and delete both objects that reference each other if there is no reference to them in the outer scope. You really don't need to use weakref.


Q:

Ethernet connection drops after several seconds

I recently got a Raspberry Pi, but I've been having trouble getting a working internet connection.
At the moment, the pi will connect, and I'll be able to access the internet for about 15 seconds until it suddenly disconnects (it disappears from the list of DHCP devices on my router). I then have to use sudo /etc/init.d/networking restart to reconnect, which either causes the graphics to freeze or lets the Pi access the internet for another 15 seconds or so. When the GUI (startx) isn't running, and I'm just using ping 8.8.8.8 the connection doesn't seem to drop.
It's running Raspbian, the power cable is 5V and 0.7A and the eth0 interface is using DHCP. I can provide any other information which might help to diagnose this problem.

A:

Are you using USB peripherals?
I don't know if you have a good quality power supply. Consider that 700mA is the minimum required... You can try with a ~1A supply.


Q:

python checking presence of a list element

I am trying to solve a more generic problem similar to the following. In the following, I get vow_array, which indicates the presence of a subset of vowels in some text, say, sent to my program. I need to print each vowel's presence as 0 or 1.
ch_a = 0
ch_e = 0
ch_i = 0
ch_o = 0
ch_u = 0

# vow_array is generated at runtime; here is an example
vow_array = ['a', 'o', 'u']

if 'a' in vow_array:
    ch_a = ch_a + 1
if 'e' in vow_array:
    ch_e = ch_e + 1
if 'i' in vow_array:
    ch_i = ch_i + 1
if 'o' in vow_array:
    ch_o = ch_o + 1
if 'u' in vow_array:
    ch_u = ch_u + 1

print ch_a, ch_e, ch_i, ch_o, ch_u

I think this code is too long and prone to errors. Is there a more compact way of writing this? Also, say if I had to do this for all 'letters' in the alphabet I don't want to have to repeat the code.

A:

Definitely.
If you ever have variables with the same prefix (ch_a, ch_e, ...), you need to use a dictionary or a list to group them:
vowels = {
    'a': 0,
    'e': 0,
    'i': 0,
    'o': 0,
    'u': 0
}

vowel_array = ['a', 'o', 'u']

for vowel in vowels.keys():
    if vowel in vowel_array:
        vowels[vowel] += 1

print vowels

A more Pythonic solution would be something like this:
>>> from collections import Counter
>>>
>>> letters = 'i am a sentence'
>>> Counter(letters)
Counter({' ': 3, 'e': 3, 'a': 2, 'n': 2, 'c': 1, 'i': 1, 'm': 1, 's': 1, 't': 1})


Q:

Go using mux Router - How to pass my DB to my handlers

At the moment, I try to create a small Web-Project using Go for data handling on the server.
I try to pass my database-connection to my HandlerFunc(tions) but it does not work as expected. I am pretty new to golang, so maybe I did not understand some basic principles of this lang.
My main func looks like this:
func main() {

    db, err := config.NewDB("username:password@/databasename?charset=utf8&parseTime=True")
    if err != nil {
        log.Panic(err)
    }
    env := &config.Env{DB: db}

    router := NewRouter(env)
    log.Fatal(http.ListenAndServe(":8080", router))
}

My Router:
func NewRouter(env *config.Env) *mux.Router {
    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        var handler http.Handler

        handler = route.HandlerFunc
        handler = Logger(handler, route.Name)

        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(handler)
    }
    return router
}

and my routes:
type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
    Route{
        "Index",
        "GET",
        "/",
        controller.Index,
    },
    Route{
        "Show",
        "GET",
        "/todos/{todoId}",
        controller.TodoShow,
    },
    Route{
        "Create",
        "POST",
        "/todos",
        controller.TodoCreate,
    },
}

So - how can I pass my "env" (or env.DB) to my FuncHandlers? I tried many things, but none of them worked.

A:

You have three options:

Make your database connection pool a global, so that you don't have to pass it. sql.DB is safe for concurrent access, and this is the easiest approach. The downside is that it makes testing harder and obfuscates "where" the pool is coming from - e.g.
var db *sql.DB

func main() {
    var err error
    db, err = sql.Open(...)
    // Now accessible globally, no need to pass it around
    // ...
 }

Wrap your handlers in a closure, which makes it accessible to the inner handler.  You'll need to adapt this to your range-over-routes approach—which is a little obtuse IMO, and makes it harder to see what routes exist, but I digress—for example:
func SomeHandler(db *sql.DB) http.HandlerFunc {
    fn := func(w http.ResponseWriter, r *http.Request) {
        res, err := db.GetThings()
        // etc.
    }

    return http.HandlerFunc(fn)
}

func main() {
    db, err := sql.Open(...)
    http.HandleFunc("/some-route", SomeHandler(db))
    // etc.
}

Create a custom handler type that accepts a handler - e.g.
type AppHandler struct {
    Handler func(env *config.Env, w http.ResponseWriter, r *http.Request)
    Env *config.Env
}

// ServeHTTP allows your type to satisfy the http.Handler interface.
func (ah *AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    ah.Handler(ah.Env, w, r)
}

func SomeHandler(env *config.Env, w http.ResponseWriter, r *http.Request) {
    res, err := env.DB.GetThings()
    // etc.
}

Note that (shameless plug!) I've written about the last approach in detail, and Alex Edwards has an excellent blog post on approaches to accessing DB pools in Go programs as well.
The only strict advice I can give is that you should shy away from passing your DB pool around in a request context, which is inefficient and not good practice (request contexts are for temporary, per-request objects).


Q:

How to debug gulpfile.js

What is the proper way to execute node-inspector in order to be able to debug gulpfile.js?
I've tried following (code in my gulpfile requires harmony and harmony-arrow-functions switches):
node-debug --nodejs --harmony --nodejs --harmony-arrow-functions /home/user/.npm-packages/bin/gulp default

Node inspector was properly loaded however it was not possible to set breakpoint in gulpfile neither before nor after the file was loaded. It was also not possible to set breakpoints in gulp/index.js and orchestrator/index.js files. And it was not possible to "step into" following statement (whole source):
gulpInst.start.apply(gulpInst, toRun);

Environment:

Fedora 21 x64
Node Inspector v0.9.2
node v0.12.0
gulp

CLI version 3.8.11
Local version 3.8.11

A:

It looks like you're missing pointing to your actual gulpfile.js. Try something like this:
node-debug /path/to/your/gulp/install/gulp.js --harmony --harmony-arrow-functions --gulpfile /path/to/your/gulpfile/gulpfile.js default

I use this and it works.


Q:

"Sparql filter by number of objects return for a given predicate

In the following query I'm trying to get a list of all entries ?s that include more than 3 objects for the predicate sctap:mentionedBy. However, I keep getting a malformed query error for this search. Does anyone see anything wrong with my query?
Thanks
SELECT ?s
WHERE {
    ?s sctap:mentionedBy ?o
    FILTER (count(?o) > 3)
}

The sparql error says: "Aggregate expression not legal". I'm not sure what that means.

A:

Does anyone see anything wrong with my query?

Sure.  Just like the error message says, you're using an aggregate expression (count(?o)) where one isn't legal.  You can see in the table of contents of SPARQL 1.1 Query Language what things are filter functions that you can use in a filter, and what things are aggregates, and where you can use each.  You can also try parsing queries at sparql.org's query validator.  For your query, it will give you the line and column numbers where something went wrong.  It's at count(?o).
In this case, you're trying to count the number of ?o values for each s, which means that you need to group by ?s, and that your filter will need to be father out.  E.g.,
select ?s where {
  ?s sctap:mentionedBy ?o
}
group by ?s
having (count(?o) > 3)

It's unlikely to  make a difference in this case, but you probably only want to count distinct values of ?o, so you could also consider:
select ?s where {
  ?s sctap:mentionedBy ?o
}
group by ?s
having (count(distinct ?o) > 3)


Q:

Пользование Sublime Text 2 без регистрации

Можно ли пользоваться Sublime Text 2 без регистрации серийного номера? Просто у них на сайте скачивание в свободном доступе.

A:

Да, можно, но он будет иногда предлагать купить себя. Что не есть обязательным.


Q:

Crystal Reports Web Viewer - formatting issues in crosstab

I'm using a Crystal Reports Web Viewer to display a CR report. It works perfectly fine in a CR Designer preview, however when I view it in a browser (any) the crosstab does not look as expected:

Specifically, column and row names have an additional margin added (values are displayed correctly) which cases the problem. I tried to change paragraph margin settings in my site's css file, but it doesn't make any difference. What could be causing this problem and how could this be solved?
When I change the specific p element margin property using Firebug, it displays correctly:

A:

This is actually a Crystal Reports bug which affects 13.0.4 Version, it works fine when you run the same report using the 13.0.3 (and probably earlier) version. This bug is known to the CR team but won't be fixed till October (3 months to fix something that worked fine previously...): http://scn.sap.com/thread/3207181
Just love Crystal...


Q:

Recurring event based on day of the year

Today is the Day of the Programmer. It's set to be on the 256th day of the year.
Is there a way of creating recurring events in Outlook based on the day of the year? I haven't found a way to do so. Keep in mind that there are leap years, making dates jump (the 256th day being September 12th during leap years, September 13th otherwise).

A:

Unfortunately, Outlooks's recurrence feature doesn't work like that. You can do recurrence based on the nth day of the month (to an extent) but not the nth day of the year.
The closest you could come would be to set up a recurring event on 9/13 every 4 years, starting on the next leap year, then also set up a new event (the same content; just a new event item) to recur on 9/12 annually. Then, on leap years, set yourself a reminder to cancel that year's annual 9/12 occurrence.
In effect, that would give you the Sept. 13th event every four years, and the Sept. 12th event all other years, with a tiny bit of interaction required.


Q:

What is the best practice for handling touch events on different GameObjects in Unity2D?

First of all I want to describe what I have in my scene.
1. Joystick.
2. Main character that has link to joystick and handles touch events from joystick.
2. Buttons.
3. Other GameObjects that must handle touch events.
But that's not all. When player is touching any part of screen (except of the above objects) main character must start fighting. The problem is in that I cant correctly handle all touch events on these game objects. When the player is touching to the joystick the main character starts moving but before this he is performing a single fight action. Can anyone give me some ideas how to correctly handle touch events on different gameobjects? Perhaps my question is confusing, I am sorry for this.

A:

You have to route the input by priority or z-order. First check HUD or GUI elements (on top) and the actual world ground at last (beneath). If a valid touch target is found/hit then you have to consume the input ond not routing it any further.
Think of it as layers, for example
[Touch] -> [Button] -> [Character] -> [Ground]

Every touch will at least hit the ground. When a touch event occurs you start start with all GUI elements like buttons. If no button was hit then you check all characters and then where on the ground the touch hit the level.
If a button was hit you trigger its action and do not check the others (characters and ground). The input is consumed by the first object being hit.


Q:

obtain largest vector from n input files MATLAB

I'm developing a program that reads data from an excel file, it saves the data regarding to numbers in the variable num then it determines which vector from the data read is the largest one.
I want to expand this code for n number of input files in an efficient way (not read and compare file by file).
any recommendations on how to achieve this?
Suppose I want this code to work for file names finger1.xlsx to finger100.xlsx
filename='finger1.xlsx';
[num1,txt1] = xlsread(filename);
filename='finger2.xlsx';
[num2,txt2] = xlsread(filename);
filename='finger3.xlsx';
[num3,txt3] = xlsread(filename);
filename='finger4.xlsx';
[num4,txt4] = xlsread(filename);
filename='finger5.xlsx';
[num5,txt5] = xlsread(filename);

if(length(num1)>length(num2))
    parent=num1;
    rank=1;
else
    parent=num2;
    rank=2;
end
if(length(num3)>length(parent))
    parent=num3;
    rank=3;
end
if(length(num4)>length(parent))
    parent=num4;
    rank=4;
end

if(length(num5)>length(parent))
    parent=num5;
end

A:

You could write a loop and change the name of the file based on the loop variable i.
    filename = sprintf('finger%d.xlsx', i);

If you do not want to compare file by file, you might store all the data from all the files and then use max to find the largest one.


Q:

Exibir imagem de outro site

Boa tarde!, Pessoal estou utilizando um código php para exibir noticia de um site, acontece que estou tentando também exibir a imagem que nele tem, porém, não estou conseguindo, o titulo e data de postagem estou conseguindo exibir normal, todavia, esse eu não consigo
<?php
// Mostrar Data na Tela.
$titulo = array();
$data = array();
$link = array();
$quantos = 0;
$exibir = 1;
$limite_title = 100;

foreach(simplexml_load_file("http://cidades.gov.br/ultimas-noticias?format=feed&type=rss")->channel->item as $item)
{
$imagem[] = $item->src;
$titulo[] = utf8_decode(substr($item->title, 0, $limite_title)."...");
$link[] = $item->link;
$data[] = utf8_decode($item->pubDate);
$quantos++;
}

for($i = $quantos-($exibir+1); $i < $quantos-1; $i++)
{
if($titulo[$i]!="")
{
echo
'

'.utf8_encode($titulo[$i]).'

'.str_replace(" ", " as ", date('d/m/Y H:m:s', strtotime($data[$i]))).'

';
}
}
?>

O que eu fiz de errado ?

A:

O problema é que o feed esta usando HTML junto ao <![CDATA[...]]>:
<description><![CDATA[
O ministro das Cidades...
]]></description>

O CDATA não é considerado "parte do XML", ou melhor é como um texto apenas e não será processado a não ser que você solicite, a maneira de fazer seria fazendo o parse do conteudo de description também, assim:
<?php
// Mostrar Data na Tela.
$titulo = array();
$data = array();
$link = array();
$quantos = 0;
$exibir = 1;
$limite_title = 100;

$items = simplexml_load_file("http://cidades.gov.br/ultimas-noticias?format=feed&type=rss")->channel->item;

$doc = new DOMDocument;

foreach($items as $item) {
    $titulo[] = utf8_decode(substr($item->title, 0, $limite_title)."...");
    $link[] = $item->link;
    $data[] = utf8_decode($item->pubDate);
    $quantos++;

    //Converte o objeto para string
    $desc = (string) $item->description;

    //Faz o parse da string html para DOMElement
    if ($doc->loadHTML($desc)) {

        //Pega todas tags img
        $imgs = $doc->getElementsByTagName('img');

        //Verifica se existe ao menos uma imagem
        if ($imgs->length) {

            //Salva a imagem no array
            $imagem[] = $imgs->item(0)->getAttribute('src');

            //para o loop atual evitando que chegue até o "$imagem[] = null;"
            continue;
        }
    }

    //Se não houver description ou img então envia o valor como null
    $imagem[] = null;
}

//E no teu for pode fazer assim:

for ($i = $quantos-($exibir+1); $i < $quantos-1; $i++) {
    if($titulo[$i]!="") {
       echo '
';

       //Se a imagem existir a exibe, caso contrário não
       if ($imagem[$i] !== null) {
           echo '

';
       }

        echo ''.utf8_encode($titulo[$i]).'

'.str_replace(" ", " as ", date('d/m/Y H:m:s', strtotime($data[$i]))).'

        ';
    }
}


Q:

How to select community wiki questions?

I want to write a query which selects the highest scored community-wiki questions (like this one) but I don't have an idea how to do it. This is what I have so far:
https://data.stackexchange.com/stackoverflow/query/1166501/find-top-wiki-questions

How to do it?
It is also possible to select question which are NOT community-wiki? If yes: how to do it?

UPDATE - info:
Community-wiki posts are slightly different than community-wiki-locked posts - how to deal with it here

A:

You seem to have adjusted your query already (perhaps after @rene's comment which I failed to spot at first); it is working fine.
There's no IsCommunityWiki boolean/bit column in the Posts table; instead, you have to check the CommunityOwnedDate which is NULL if and only if it's not a community wiki post. So
AND p.CommunityOwnedDate is not null

selects community wiki posts only, and
AND p.CommunityOwnedDate is null

would only select posts which are not community wiki.


Q:

UITableView tap not working first time after constraints change

IMPORTANT: My problem is not that I'm implementing didDeelectRowAt instead of didSelectRowAt. Already checked that :)
I have a UITableView that is shown on part of the screen in a modally presented view controller. When the user is dragging it resizes to full screen and back to some defined min height. I'm doing this by implementing the following methods from the UIScrollViewDelegate:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    guard !scrollView.isDecelerating else { return }

    let contentOffset = scrollView.contentOffset.y
    if tableViewHeightConstraint.constant < view.frame.height && contentOffset > 0.0 {
        tableViewHeightConstraint.constant = min(contentOffset + tableViewHeightConstraint.constant, view.frame.height)
        scrollView.contentOffset.y = 0.0
        return
    }

    if tableViewHeightConstraint.constant > minViewHeight && contentOffset < 0.0 {
        tableViewHeightConstraint.constant = max(tableViewHeightConstraint.constant + contentOffset, minViewHeight)
        scrollView.contentOffset.y = 0.0
    }
}

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    // Here I have some calculations if depending the dragging end position and the velocity the end size should be full screen or `minViewHeight`
    // After calculating what the end size should be I'm animating the size change
    heightConstraint.constant = newConstraintHeight
    UIView.animate(withDuration: TimeInterval(calculatedAnimationDuration), delay: 0.0, options: .curveEaseOut, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)
}

Everything about the resizing and the scrolling works fine, but there is a problem that I cannot figure out why it's happening. It's the following:

When the view controller with the table view is shown for the first time with the min height and I tap on a cell it works fine.
If I drag to expand the table view to full screen height and tap on a cell, again it works fine.
If I drag to expand the table view to full screen height and then drag again to return it to the min height and then tap on a cell, nothing is happening, no UIScrollViewDelegate or UITableViewDelegate method is called at all. If I tap once more on a cell everything works fine.

One thing that I noticed is that after dragging the table view back to the min height the scroll indicator does not hide. On the first tap it hides, and on the second tap the didSelectRowAt is called.
UPDATE:
Here is a test repo for the problem: https://github.com/nikmin/DragTest
Please don't mind if the dragging doesn't work perfectly, I just put something so anyone can try it out, but I think the problem is easily reproducible.
Also one more thing... If you drag from full size all the way to the bottom so the table view reaches min height and you continue dragging so the content offset is < 0 and the you release, the problem is not happening.

A:

Drag TableView to return it to the min height and then tap on a cell, nothing is happening because:

When you drag to expand the table view to full screen, scrollView.isDecelerating is true. So the code inside scrollViewDidScroll method will run.
But when you drag TableView to return it to the min height, scrollViewDidScroll is false. So the code inside scrollViewDidScroll method won't run. It's make the first tap do nothing.

Simply remove guard !scrollView.isDecelerating else { return } from scrollViewDidScroll. You will tap cell normally after drag TableView down.
But you need change logic a little, animation will go wrong after remove above line.
Hope it can help you ;)

A:

After trying to figure out a solution to this without result, we (me and a UX designer) decided to change the behaviour a bit.
So in the real scenario in the app I'm implementing this in, the table view is inside another view that has also a title label and some other views above the table view. We decided to add a pan gesture recognizer to this root view and disable the scrolling of the table view when the view has the min size. This way the pan gesture recognizer will take over whenever the user tries to drag anywhere inside the view (including the table view), so the expanding of the view works. And the tap in the cell still works.
When the view has the max height the table view scroll is enabled so the user can scroll. The downside of this approach is that when the user scrolls to the top of the table view and continues scrolling the view will not decrease the size. But he still has the option to drag it down by dragging any of the views above the table view. When dragging down in this way, only the size of the table view changes, and the content offset isn't, which is the root of the problem (changing both at the same time).


Q:

Highcharts: Drilldown from map to chart

Please consider Kuwait map:
Kuwait Map
I want when a user clicked on one state (for example - Al Jahrah) then a column chart appears for Al Jahrah series. For example:
Category For: Al Jahrah            Value For: Al Jahrah
--------------------------------------------------------
Cat1                               10
Cat2                               12
Cat3                               3

I searched via the internet but I only saw country drill down to states. Is it possible?
Thanks

A:

You can create two functions that will be responsible for creating a different type of chart and call them in the right event:
function mapChart() {
    Highcharts.mapChart('container', {
        chart: {
            map: 'countries/kw/kw-all'
        },

        title: {
            text: 'Highmaps basic demo'
        },

        subtitle: {
            text: 'Source map: Kuwait'
        },

        mapNavigation: {
            enabled: true,
            buttonOptions: {
                verticalAlign: 'bottom'
            }
        },

        colorAxis: {
            min: 0
        },

        series: [{
            data: data,
            name: 'Random data',
            point: {
                events: {
                    click: function() {
                        columnChart(this.name);
                        document.getElementById("back").style.display = "block"
                    }
                }
            },
            states: {
                hover: {
                    color: '#BADA55'
                }
            },
            dataLabels: {
                enabled: true,
                format: '{point.name}'
            }
        }]
    });

    document.getElementById("back").style.display = "none";
}

function columnChart(name) {
    var data = [1, 2, 3];

    if (name === "Al Jahrah") {
        data = [2, 2, 2];
    }

    Highcharts.chart('container', {
        title: {
            text: name
        },
        series: [{
            type: 'column',
            data: data
        }]
    });
}

mapChart();

Live demo: https://jsfiddle.net/BlackLabel/bnsjgt4z/
Below you can find another solutions with drilldown from map to chart:
https://www.highcharts.com/maps/demo/rich-info
https://www.highcharts.com/maps/demo/data-class-two-ranges


Q:

Highcharts linear chart with y-axis displaying seconds and minutes

I have a chart where I have on the x-axis a datetime and on the y-axis a value in seconds, like 10, 200 or 4500. This works fine.
What I need is something like the behavior of the datetime, that when you have a date range it shows the days between that range, but if the range is really small, it displays the hours between that range. My request is that I would like to do the same but having a number in seconds, and if the range is huge, like maybe between 100 and 2500, it should be converted to minutes, what I have now is the following:
yAxis: {
        title: {
            text: 'Minutes',
            margin: 10
        },
        min: 0,
        tickInterval: 60,
        labels:{
           formatter: function(){
                var minutes = ""
                if (this.value > 59){
                    minutes = Highcharts.numberFormat((this.value/60), 0)
                }
                return minutes;
            }
       }
    }

which is great for range between 60 and 500, but when the range is longer, it draws a lot of lines to display the minutes.
Any ideas? Can I change the tickInterval depending on some value?
I already have seen this reply Plotting seconds, minutes and hours on the yAxis with Highcharts, but I don't want to handle a datetime object on that axis.

A:

I would really recommend using the inbuilt datetime axis type if you can. It takes away a lot of hassle with things like the issue you are asking about.
Failing that, you are on the right track in looking at the tickInterval. You could try not specifying a tickInterval at all, and let highcharts decide for you. It will usually find something sensible.
If that doesn't work well for you, then you will have to look at your data range and choose a sensible tickInterval yourself. One algorithm you could use is:
if (range < 500)
    tickInterval = 60
else
    tickInterval = 120

Obviously, if your range can go even bigger, you may need to have another case which switches the tickInterval to 300 or higher.


Q:

Enriched monoidal categories

This question is about (not necessarily symmetric) monoidal categories enriched over a symmetric monoidal category $\mathcal{V}$. Assume that $\mathcal{V}$ is closed. You may also assume that $\mathcal{V}$ is (co)complete if you wish.
If $k$ is a commutative ring, a $k$ algebra can be defined in two ways. Either as a $k$-module $R$ together with morphisms $k\rightarrow R$ and $R\otimes_{k}R\rightarrow R$ satisfying the well-known laws, or as a ring homomorphism to the center $k\rightarrow Z(R)$.
Let's see what happens in the categorical context.
The tensor product of $\mathcal{V}$-enriched categories can be straightforwardly defined, see Kelly's book. Then one can define what a monoidal $\mathcal{V}$-category is by reproducing the classical definition in the enriched context.
Assume now that $\mathcal{C}$ is an ordinary monoidal category. I believe that the braided center $Z(\mathcal{C})$ as defined by Joyal and Street is a well known construction. Suppose that we have a strong braided monoidal functor $z : \mathcal{V}\rightarrow Z(\mathcal{C})$ such that the functor $z(-)\otimes Y : \mathcal{V}\rightarrow \mathcal{C}$ has a right adjoint ${Hom}_{\mathcal{C}}(Y,-) : \mathcal{C}\rightarrow\mathcal{V}$ for any object $Y$ in $\mathcal{C}$. The counit is an evaluation morphism in $\mathcal{C}$,
$ev: z( {Hom}_{\mathcal{C}}(Y,Z))\otimes Y\longrightarrow Z$
One can define composition morphisms in $\mathcal{V}$
${Hom}(Y,Z)\otimes {Hom}(X,Y)\longrightarrow {Hom}_{\mathcal{C}}(X,Z) $
as the adjoint of
$z({Hom}(Y,Z)\otimes {Hom}(X,Y))\otimes X \cong
z({Hom}(Y,Z))\otimes z({Hom}(X,Y))\otimes X
\stackrel{id \otimes ev}\longrightarrow
z({Hom}(Y,Z))\otimes Y
\stackrel{ev}\longrightarrow
Z $
I think it's pretty obvious that $\mathcal{C}$ becomes $\mathcal{V}$-enriched in this way. Moreover, one can also enrich the tensor product in $\mathcal{C}$ in a similar way.
Do you guys agree? Do you know of any reference where this is checked with some detail? Is it even more obvious than I think?
Any comment is welcome!

A:

There is a theorem in category theory, generally regarded as folklore, which says that for a symmetric monoidal closed category $V$, the following structures are equivalent:

a category $C$ with an action $V\times C\to C$ of the monoidal category $V$ on $C$, which we may write as $(v,c)\mapsto v*c$, for which $-*c:V\to C$ has a right adjoint for each $c\in C$ (here the action amounts to a strong monoidal functor $V\to [C,C]$.
a $V$-category $C$ for which the $V$-functor $C(c,-):C\to V$ has a left adjoint for each $c\in C$. (such a $V$-category is said to be "tensored'' or "copowered'')

You can see this, for example, in the appendix to this paper.
In your case, unless I've misunderstood, the centre $Z(C)$ plays little role. The point is that your functor $z:V\to C$ induces an action via $v*c=z(v)\otimes c$, and $-*c$ has a right adjoint by assumption, so you get the $V$-enrichment.
(There is an analogous characterization of $V$-categories $C$ which are cotensored/powered: this means that each $C(-,d):C^{op}\to V$ has a left adjoint.)

A:

My "answer" is somewhere between "answer" and "comment", but is much too long to fit in the comment box, so I'll put it here.  The point, though, is that I don't really answer the original question.  I'm pretty sure that yes, your construction does turn any monoidal category $\mathcal C$ with a sufficiently nice functor $\mathcal V \to Z(\mathcal C)$ into an enriched category.  I haven't checked the details, but they don't look hard.  I don't know a good reference.
However, you will need more than just enriched monoidal categories in order to build an equivalence between the words "Monoidal category $\mathcal C$ enriched over $\mathcal V$", and "Monoidal category $\mathcal C$ with a braided monoidal functor $\mathcal V \to Z(\mathcal C)$". For example, let $\mathcal C$ be the category of finite-dimensional vector spaces, and $\mathcal V$ the category of all vector spaces, both with their usual tensor structures. Then $\mathcal C$ is certainly enriched over $\mathcal V$, but the corresponding functor $\mathcal V \to Z(\mathcal C)$ does not exist, because $\mathcal V$ is so much bigger than $\mathcal C$.
I do know of at least one situation where something like this should work.  It might be broadly known, but I don't think so; we (re?)construct it in current joint-work-in-progress with A. Chirvasitu.
We propose that the correct notion of "2-abelian group" is locally presentable category.  The correct 2-category with objects the 2-abelian groups is the one where a 1-morphism $A \to B$ consists of an adjoint pair, a left adjoint $f: A\to B$ and its right adjoint $A \leftarrow B$ (and all the extra stuff).  The 2-morphisms are natural transformations of adjunctions.  Since a left adjoint determines its right adjoint up to unique isomorphism, in fact we set the 1-morphisms to be precisely those functors that are left adjoints.  (Recall that a functor between locally presentable categories is a left adjoint iff it is cocontinuous, and a right adjoint iff it is continuous and commutes with $\kappa$-filtered colimits for sufficiently large cardinals $\kappa$; so the 1,2-opposite category is the one whose 1-morphisms are the continuous $\kappa$-filtered-colimit-preserving functors.)
The category of 2-abelian groups is symmetric monoidal with the "tensor product" defined in the obvious way: it is straightforward to prove that for any two 2-abelian groups $A,B$, there is a 2-abelian group representing the category-valued 2-functor $\hom(A,\hom(B,-))$.  (Note that for 2-abelian groups $B,C$, the category $\hom(B,C) = \operatorname{cocontinuous}(B \to C)$ is again a 2-abelian group.)  Thus there is a natural notion of "2-ring" and "commutative 2-ring" and the morphisms between them, their modules, etc.
In any case, in this setting given a "commutative 2-ring" $A$ (i.e. a locally presentable category with a symmetric monoidal structure that is cocontinuous in each variable), there is an equivalence of 2-categories between: {commutative monoid objects in $A\text{-mod}$}, and {commutative 2-rings with a distinguished morphism from $A$}.  (Note that these 2-categories are somewhat subtle.  For example, just like {symmetric monoidal categories} is not full in {monoidal categories}, similarly "module of a commutative 2-ring" requires more data than "module of a 2-ring that happens to be commutative"; also the tensor structure in $A\text{-mod}$ requires some work.)
We don't consider non-commutative 2-algebra, so I'd have to go over the arguments again to see about relaxing the commutativity constraints; but it should work.


Q:

TypeError: Cannot read property 'minify' of undefined in Nuxt.js

When im generating nuxt app using "npm run generate" or "npm run build" it throws TypeError: Cannot read property 'minify' of undefined
How to fix this
TypeError: Cannot read property 'minify' of undefined
    at minify (C:\Users\hiraz\webdev\vue\nuxt\demo\cms-demo002\node
js:175:23)
    at module.exports (C:\Users\hiraz\webdev\vue\nuxt\demo\cms-demo
\worker.js:13:40)
    at handle (C:\Users\hiraz\webdev\vue\nuxt\demo\cms-demo002\node
8)
    at process.<anonymous> (C:\Users\hiraz\webdev\vue\nuxt\demo\cms
\index.js:51:3)
    at emitTwo (events.js:126:13)
    at process.emit (events.js:214:7)
    at emit (internal/child_process.js:762:12)
    at _combinedTickCallback (internal/process/next_tick.js:142:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)

A:

There was a bug in a dependency called terser v3.16 released yesterday causing this problem.
Fix it by:
npm i terser@3.14


Q:

Mass readings about husbandly conduct

At Mass this weekend, we heard part of Proverbs 31 which is nice and all.  But my wife always complains that, "they always talk about how wives should act, they should say something about how husbands should act for once."
Are there any Mass readings during the 3 year cycle (or even the 2 year weekday cycle) that talk about how men should act.  I can't think of any other than "Husbands love your wives".

A:

It appears that 21st Sunday of the Year [B Cycle] has at least part of what you are looking for, as Ephesians 5:21-32 has this from the KJV:

 21Submitting yourselves one to another in the fear of God.

 22Wives, submit yourselves unto your own husbands, as unto the Lord.

 23For the husband is the head of the wife, even as Christ is the head of the church: and he is the saviour of the body.

 24Therefore as the church is subject unto Christ, so let the wives be to their own husbands in every thing.

 25Husbands, love your wives, even as Christ also loved the church, and gave himself for it;

 26That he might sanctify and cleanse it with the washing of water by the word,

 27That he might present it to himself a glorious church, not having spot, or wrinkle, or any such thing; but that it should be holy and without blemish.

 28So ought men to love their wives as their own bodies. He that loveth his wife loveth himself.

 29For no man ever yet hated his own flesh; but nourisheth and cherisheth it, even as the Lord the church:

 30For we are members of his body, of his flesh, and of his bones.

 31For this cause shall a man leave his father and mother, and shall be joined unto his wife, and they two shall be one flesh.

 32This is a great mystery: but I speak concerning Christ and the church.

For the rest you can look through http://catholic-resources.org/Lectionary/1998USL-OrdinaryA.htm and http://catholic-resources.org/Lectionary/1998USL-OrdinaryC.htm but these links don't include the readings from the daily mass, which may have some of the verses mentioned that talk about husbands.


Q:

Xamarin load listview from listview

Hi I'm using Visual Studio Enterprise and develop with Prism.Unity.Forms and Xamarin.Forms.
In my ViewModel I retrive from webservice my data (see this figure)

I would like retrieve this data into my View into ListView, but I can not have access to ListaEstadoCuenta, I can show "polizaId" and "estado"
this is the information in "ListaEstadoCuenta"

In my view I have the ListView:

Please help me how to display data "ListaEstadoCuenta" list in the Labels, I hope your help

A:

ListaEstadoCuenta is a List. This means you have to specify the item in the bindings of your Labels. E.g. for the first Item:
<ViewCell>
<!-- ... -->
    <Label Text="{Binding ListaEstadoCuenta[0].Comprobante}" />
    <Label Text="{Binding ListaEstadoCuenta[0].FechaDoc}" />
<!-- ... -->
</ViewCell>

If you want to show list items in one Label, you have to use Converters to combine the values:
Value converter
public class StringConcatenationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is IEnumerable<EstadoCuentaDetalle>)
        {

            return string.Join(", ", ((IEnumerable<EstadoCuentaDetalle>)value).Select(x => x.Combrobante));
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Resource in your Page
You have to adjust the local namespace xmlns:local to refer your assembly name.
<ContentPage ...
             xmlns:local="clr-namespace:FormsTest;assembly=FormsTest">
  <ContentPage.Resources>
    <ResourceDictionary>
      <local:StringConcatenationConverter x:Key="concatConverter"></local:StringConcatenationConverter>
    </ResourceDictionary>
  </ContentPage.Resources>

Binding
<Label Text="{Binding ListaEstadoCuenta, Converter={x:StaticResource Key=concatConverter}}" />


Q:

Change DNS A records dynamically

For example, I'll buy domain name at godaddy.com. I'll configure it with 2 A records with IPs 123.0.0.1 and 123.0.0.2.
Is it possible to ping it for availability and change A records dynamically by some script?

A:

There are ways to do dynamic updates with BIND.  But they are server-specific, and must be enabled and configured on the server.
You really need to be asking Godaddy what they support in this area.
Also note that dynamic DNS is a very poor way to do failover, as to be effective, it requires setting a very short TTL, which ends up wasting lots of bandwidth, and is generally annoying.


Q:

Gated check in for specific branch

I have multiple branches and for every one i have specific build process.
How do i set up gated build process for specific branch?
example
Development branch
 -> fast for developers
  build process this has main intergation tests
Release branch
 -> checkin before production.
 contain load testing and records steps contains automated UI tests
Now for my development i want to run tests every time when developer commits changes. but i do not want release build to run every time.
How do i set this up?

A:

You need to have two separate build definitions: One building your 'Development' branch & one building your 'Release' branch.
Both can base on the same Build process template and their differences are:

Dev-build targets in 'Workspace' the path of your development branch - Rel-build targets the path of your release branch
(This is you main question) Trigger = "Gated check-in" for your Dev-build, Trigger = "Manual" (or some other) for your Rel-build
Rel-build will probably be tasked with additional tests.

A basic walkthrough on how to setup a build definition in TFS2010 can be found here


Q:

Moqing HttpContext

I have a unit test that tests an MVC controller's result. Unfortunately the controller uses a third party library that uses HttpContext.Request.IsLocal. I cannot refactor the third party library to make it use HttpContextBase.
I need to mock this so that HttpContext.Request.IsLocal returns true. Any Ideas on how to achieve this?

A:

If you are using premium or above version of vs2012, try looking at microsoft.fakes. it should cater to your situation.
Some reading:
http://msdn.microsoft.com/en-us/library/hh549175.aspx


Q:

Find modulus of $z$ given modulus of $(z-3w)/(3-z\overline{w})$

Question:

(23) If $z_1$, $z_2$ are complex numbers such that $\left|\dfrac{z_1-3z_2}{3-z_1\overline{z}_2}\right|=1$ and $|z_2|\neq 1$, then find $|z_1|$.

How would I attempt this question? I tried using values for $z_1$ and $\overline{z}_2$ but it is coming out to be extremely lengthy. There is probably a quicker solution to this. Can someone provide me with a hint to start?

A:

When dealing with absolute values, it is usually more convenient to look at the squares, since we have $\lvert a+b\rvert^2 = \lvert a\rvert^2 + a\overline{b} + \overline{a}b + \lvert b\rvert^2$ as a convenient expansion. Here, we compute
$$\begin{align}
\lvert 3 - z_1\overline{z_2}\rvert^2 - \lvert z_1 - 3z_2\rvert^2
&= (9 - 3 z_1\overline{z_2} - 3\overline{z_1}z_2 + \lvert z_1\overline{z_2}\rvert^2) - (\lvert z_1\rvert^2 - 3z_1\overline{z_2} - 3\overline{z_1}z_2 + 9\lvert z_2\rvert^2)\\
&= 9 + \lvert z_1\rvert^2\lvert z_2\rvert^2 - \lvert z_1\rvert^2 - 9\lvert z_2\rvert^2\\
&= (9 - \lvert z_1\rvert^2)(1-\lvert z_2\rvert^2),
\end{align}$$
and find that
$$\left\lvert \frac{z_1-3z_2}{3 - z_1\overline{z_2}}\right\rvert = 1 \iff \bigl( \lvert z_2\rvert = 1 \lor \lvert z_1\rvert = 3\bigr).$$
More, we can read off exactly when $\frac{z_1-3z_2}{3-z_1\overline{z_2}}$ is in the interior or in the exterior of the unit disk.


Q:

Why does my Nikon D750 and 18-200 lens have dark corners with no lens hood or filters attached?

I am new to photography. I have a Nikon D750 with the 18-200 f/3.5-5.6 ED VRII lens on it. No filters are attached. No hood is attached. When I look through the viewfinder, it creates a circle around the outside. This appears with the camera powered on or off. The circles are bigger (worse) at 18 than they are at 200. This issue started a month ago. I tried changing the lens and the circle disappears so I know it is with this lens only. Any suggestions how to fix this problem?

A:

The D750 is a full frame camera, while the 18-200 lens is made for DX cameras, which have a smaller sensor.  So the lens can't project a big enough image onto the sensor to cover the entire sensor, which is why you see the dark circles.
The reason your other lenses don't exhibit the problem is that they are likely all FX (full frame) lenses.
The reason it used to look normal is you would have had the camera in "auto crop mode".
In the Shooting Menu, under Image area > Choose image area select "Auto DX crop".
What this mode does is recognize that you have a DX lens attached and automatically crops out the dark parts at the edges.
I'm guessing that at some point you changed this menu setting.

A:

Don't use 18-200 3.5-5.6 ED VRII on D750. That's DX (small) lens on FX(big) camera, the result is heavy vignetting, as you describe. Or the camera switching into FX crop mode. It's pretty much "a waste of full-frame camera", as you'd get better results when using much cheaper DX body.
Get a 28-300mm f/3.5-5.6 VR instead. This is the closest FX equivalent of 18-200 on DX. As a proper FX lens, it will let you use full potential of your FX camera.
If this setup was sold to you recently, I believe you should be able to return the 18-200 lens. It's not a appropriate match for D750. If the seller told you so, he mislead you.


Q:

Multiple highlight with autocmd in vimrc

I would like to use two autocmd, to highlight lines too long, and to highlight spaces at the end of lines, but I don't succeed, only the last of the two commands is displayed...
Is it possible ?
Here is the lines concerned:
augroup vimrc_autocmds
    autocmd BufEnter * highlight OverLength ctermbg=darkgrey guibg=#592929
    autocmd BufEnter * match OverLength /\%81v.*/
    autocmd BufEnter * highlight UnwantedSpaces ctermbg=red guibg=#red
    autocmd BufEnter * match UnwantedSpaces /\s\+$/
augroup END

A:

You can only use one match at a time.  If you want to use multiple you can use 2match and 3match.  You only have three of these to use simultaneously without defining syntax highlighting for what you're trying to match.


Q:

What actually happens during "Waiting for changes to be applied" and "Waiting for items to copy"?

There are literally hundreds of threads on dozens of different internet forums about iOS devices that get stuck on "Waiting for changes to be applied" and/or "Waiting for items to copy" while syncing.  I have had that problem intermittently for two years, on iOS 6, 7 and now 8, and frankly after trying all of the fixes I have read about, I have given up on trying to solve it.  That's not what this question is about.  What I want to know is:

What's supposed to happen during those stages of the sync?

Do those two messages mean the same thing, or something different?  What is iTunes trying to do?  Is it reading from an internal database on the device and comparing it to the iTunes library on the computer?  Is it writing to a device library?  What's it writing?  What file is it working on?  Is there any way to watch the activity that's in progress, either in real time or after-the-fact?

A:

Although there is no official documentation by Apple, you can still get some information by watching iTunes and iOS doing their stuff. This can be done by monitoring log files of both, on the iPhone this can be done over an USB connection. Here's a couple of what I've already seen the iPhone doing in the "waiting for xy" sync stages:

After copying new media to the iPhone, the media needs to be indexed, e.g. there's metadata to be processed, thumbnails need to be created etc. Until that is done, the media can't be displayed correctly in the corresponding iPhone apps, so iTunes waits for the iPhone Media Indexer service to complete its work.
When copying new apps to an iPhone, the packaged .ipa-files need to unpack and install, e.g. register in the iPhone's homescreen, app lists, file extension databases etc, this is done during that stages of sync.
The spotlight search might need time to index new files, iTunes waits for this as well (not always, but sometimes!)
When iTunes transfers files to an iPhone, it always verifies the file's contents in several ways, being it archive integrity or hashes that are compared. These processes do need plenty of time, depending on the size of the transferred data, and iTunes waits for successful verification in order to complete the sync.
When there are copy failures detected by any of the verification methods, iTunes will copy the files again. Often these processes are not displayed by iTunes, it is done during the "Waiting for items to copy"-processing.
iTunes will also wait for copy processes to terminate successfully, there are streams and sockets to close when data is transferred between computers. Although this should happen instantly, sometimes there are failures and the iPhone needs some time.
In general, you can say that iTunes utilizes these stages for verification and error correction as well as doing "completional" work. They get extremely useful especially when using WiFi sync, which is much more error-prone than USB.

Edit: To view the log files of an iPhone/iPad, no jailbreak is required. The best tool probably is libimobiledevice, a bundle of free open-source software licensed under LGPL 2.1. It is capable of handling an iOS device without the need of iTunes, so even on Linux machines. Although being designed for Linux machines, it can be run on Mac as well, e.g. by compiling the source code, or, even easier, by installing through homebrew. Although I'm always using it on Linux machines, this should work the same way on Mac OS X.
You probably need to pair your iPhone first, use the idevicepair-binary for this. It should find your USB-connected iPhone on its own, if it doesn't, you can try passing the UUID of your device. After pairing succeeded (it will display a success-message to your terminal interface), use the idevicesyslog-application to view the log files of your iPhone. It will connect to the syslog-socket of your device automatically, if it doesn't, you may pass the UUID again. Then all log messages will get posted to stdout on your computer, e.g. to your terminal output.
There is proprietary software as well that allows you to read the logs on your iOS device, but libimobiledevice as a command line- and open source-tool should be preferred.


Q:

What does it mean to say the CMBR has a “temperature”?

We say the cosmic microwave background radiation “has a temperature” of 2.7K.
Does this mean it has a temperature in the way we say the air around a warm lightbulb has a temperature of 120° or in the sense that the mix of electromagnetic waves given off by the lightbulb are like those emitted by a blackbody at 3000K?
Is the temperature of the electromagnetic field at some point in space the temperature “of the space” in which the field exists, or the temperature of a black body that would emit the spectrum of the EM field in the space if the blackbody were there at that moment.
I hear people speak as if the first, but I think they mean the second. Yes?

A:

It means the mix of electromagnetic waves "given off" by the CMB (really: "that constitute the CMB")  are like those emitted by a blackbody at 2.7K.
Temperature is a property of an ensemble of particles (photons in this case, could be air molecules, or even virtual particles) but not of space itself.
Yes, people speak as if the first but mean the second.


Q:

Is there a pattern for concurrent searching?

I have this concurrent pattern that came up when trying to model my problem, and I don't know if there's a name for it. Having a design pattern reference or something like that could help me implement it more safely.
Concept:
The foreman (main thread) is asked to look for a series of objects in a big warehouse.
This warehouse has n floors. The foreman has a team of n workers (helper threads), each with a dedicated floor.
The foreman recieves an object, and asks every worker to find it.
If a worker finds it on their floor, they return to the foreman with appropriate information. (location, status...)
The foreman then calls back all other workers (since the item has been found there's no need for more searching), and move on to the next object.
If everyone comes back saying "No it's not on my floor" we can act accordingly. (signal a missing product to management...)
The main problem I have is that I need to make sure threads don't waste calculation time when the item has already been found, and to ensure proper coordination.
I also can't give every thread the entire list of things to find, since this information is recieved item by item. (eg. via network)

A:

Are you looking for Observer pattern ?
Once a worker finds the item and returns to the Foreman. The Foreman should notify to all the workers that the item is found, so all the threads will stop search and return.


Q:

JDialogBox dont display content intermittently

Good evening stackoverflow.
I have a problem involving JOptionPanes.
Every so often they simply do not display the content that i give it.
And here to illustrate my problem:
This is what it should look like:

and every so often, this is what it displays:

heres the function call to build the thing. "panel" is just a simple JPanel with the widgets added.
int a = JOptionPane.showConfirmDialog(null,panel,"Please enter result details",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);

The thing with this that is driving me crazy is that it's intermittent so i have no idea what caused this.
Any ideas?

A:

You should ensure that you are calling your JOptionPane updating code on the Event Dispatching Thread.  Swing components should be updated on the EDT to ensure they are repainted properly, most issues with incorrect updating are because it is not being called on the EDT.
If you are ever unsure about whether or not you are on the EDT, SwingUtilities.isEventDispatchThread() is a good debugging tool.
Edit:  I missed that there was a comment that mentioned this, sorry.


Q:

How to tell apache to LocationMatch opposite of this?

I have the following in my apache conf:
  <LocationMatch "^/assets/.*$">

How can I put in a directive that is the opposite of this?
I tried <LocationMatch "!^/assets/.*$"> but it didn't work :(

A:

With Apache 2.2 (not sure about previous versions), you can use a regular expression with a negative lookahead to match all root location URL-path directories other than /assets like so:
<LocationMatch "^(?!/assets)/[^/]+">
    ...
</LocationMatch>

Note that this does not include the root URL-path / itself.


Q:

What is the "Stack" section in gdb

In gdb, it seems that whatever is located in the "Stack" section is always the same as the %rip register. For example:
rip 0x0000555555554603
─── Stack ────────────────────────────────────────────────────────────────────────────────────────
[0] from 0x0000555555554603 in main

And after doing si:
rip 0x0000555555554606
─── Stack ────────────────────────────────────────────────────────────────────────────────────────
[0] from 0x0000555555554606 in main

What exactly is the "Stack" section in gdb? It seems to me like it is more-or-less the instruction pointer (%rip) in the currently running function (and previous %rips in the call stack that have not completed execution). Is this correct, or what does this section tell us?
If useful, here is the front-end that I'm using in gdb, which is called gdb dashboard:

A:

That is the call stack. GDB enables you to see the call stack, so you can understand how you got to where you are (Which function calls did you go through to get to where you are).
The call stack is the list of functions that have been called and not yet returned, beginning with the current function at frame 0, and going all the way down to main at the last frame.
In your particular case, your call stack is only main, because you've not called other functions (or because they returned already). %rip points to the current instruction, so your location in the current frame always corresponds to its contents.


Q:

Copy files from directory structure but exclude a named folder

I am looking to copy files from a directory structure over to a new folder. I am not looking to preserve the file structure, just get the files. The file structure is such that there can be nested folders, but anything in a folder named 'old' I do not want moved over.
I made a couple attempts at it, but my powershell knowledge is very limited.
Example being where the current file structure exists:
Get-ChildItem -Path "C:\Example\*" -include "*.txt -Recurse |% {Copy-Item $_.fullname "C:\Destination\"}

This gives me all the files all I want, including all the files I don't want. I do not want to include any files that are in the 'old' folder. To note: there are multiple 'old' folders. I tried -exclude, but it looks like it only pertains to the file name, and I am not sure how to -exclude on a path name, while still copying the files.
Any help?

A:

How about this:
C:\Example*" -include "*.txt -Recurse |
  ?{$_.fullname -notmatch '\\old\\'}|
    % {Copy-Item $_.fullname "C:\Destination\"}

Exclude everything that has '\old\' anywhere in it's path.

A:

If we sneak a little where-object into the pipeline I think you'll get what you seek. Each object that has a property named Directory (System.IO.FileInfo) with a property named Name with a value of old will not be passed to Copy-Item.
Get-ChildItem -Path "C:\Example*" -include *.txt -Recurse | ? {-not ($_.Directory.Name -eq "old")} |  % {Copy-Item $_.fullname "C:\Destination\"}

(Untested)


Q:

run rsync as root but keep user ownership

I would like to backup user files from one server to another with rsync.
but I noticed that the user folders change to root.
how can I keep the user permissions with rsync (running by root)?

A:

Use the -a flag, which includes among other things, the options -o and -g, which preserves owners and groups. This requires that you run rsync as root.
Also, see man rsync.

A:

Keeping the permissions is achieved through "archive" mode, -a. The common example is -avz:
rsync -avz foo:src/bar/ /data/bar

This ensures that symbolic links, devices, attributes,  permissions,  ownerships,  etc.  are preserved  in  the transfer.  Additionally, compression will be used to reduce the size of data portions of the transfer.

A:

If you're using rsync for backup I can really recommend using rsnapshot instead (it uses rsync). It rotates the backups and uses hard links so you can see differences between your daily backups (but folders still look like they have the complete contents). I use this for backing up both Windows and Linux servers at work. Perfect for us!


Q:

What is the best way to deal with a failed nonce validation?

I have a vague understanding of nonces but have a little confusion.
What is the correct response when nonce validation fails?
Under what circumstances could nonce validation fail? what is the risk to genuine users?

A:

The goal of nonces with forms is generally two fold: to ensure the data is only submitted once, and to ensure the user actually does the submitting. The second point helping defend against cross site request forgeries: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Dealing with them depends on the context. If a user is filling out a form and the nonce fails, refresh the page (pre-fill the data), say something benign like "Oops there was a problem, please check your input and submit again". A valid user can hit submit, an attack will be thwarted, or the user at least made aware of what's happening.
Validation can fail for a few reasons. If you've got some form of browser cache enabled, a user visits one form (with a given nonce), then navigates to a different one (with it's own nonce) and returns to the first via the back button the nonce will likely fail. By allowing the browser cache to occur they haven't refreshed the page, and your server is likely only storing a single valid nonce for them in the session so they wont match. A valid use case, and a failed nonce (not one I'd lose sleep over, just make sure the form is re-populated).
By and large my recommendation would be: Tell the user to submit again, subtly imply they should check their input, make it easy to submit again.


Q:

Pandas Dataframe creating a unique column

I have this dataframe:

I want to add each column, as duration + credit_amount, so I have created the following algorithm:
def automate_add(add):
  for i, column in enumerate(df):
    for j, operando in enumerate(df):
        if column != operando:
            columnName = column + '_sum_' + operando
            add[columnName] = df[column] + df[operando]

with the output:

duration_sum_credit_amount
duration_sum_installment_commitment
credit_amount_sum_duration
credit_amount_sum_installment_commitment
installment_commitment_sum_duration
installment_commitment_sum_credit_amount

However, knowing that duration + credit_amount = credit_amount + duration. I wouldn't like to have repeated columns.
Expecting this result from the function:

duration_sum_credit_amount
duration_sum_installment_commitment
credit_amount_sum_installment_commitment

How can I do it?
I am trying to use hash sets but seems to work only in pandas series [1].
EDIT:
Dataframe: https://www.openml.org/d/31

A:

You have been pointed already to itertools.combinations, which is the right tool here, and will save you some for loops and the issue with repeated columns. See the documentation for more details about permutations, combinations etc.
First, let's create the DataFrame so we can reproduce the example:
import pandas as pd
from itertools import combinations

df = pd.DataFrame({
    'a': [1,2,3],
    'b': [4,5,6],
    'c': [7,8,9]
})

>>> df
    a   b   c
0   1   4   7
1   2   5   8
2   3   6   9

Now let's get to work. The idea is to get all the combinations of the columns, then do a dictionary comprehension to return something like {column_name: sum}. Here it is:
>>> pd.DataFrame({c1 + '_sum_' + c2: df[c1] + df[c2]
                  for c1, c2 in combinations(df.columns, 2)})

    a_sum_b a_sum_c b_sum_c
0   5       8       11
1   7       10      13
2   9       12      15

Notice you can replace sum with any other function that operates on two pd.Series.