text:
Q: Substract a part of a string considering some delimiters in php I have a variable in php witch can have this shape:
$a = 'help&type=client';
$b = 'account#client';
$c = 'info&type=client#new';

I need to create a substract function that will work like this:
echo myFunction($a); //&type=client
echo myFunction($b); //#client
echo myFunction($c); //&type=client#new

I will rate the more simplified answere.

A: I think that the simplest way would be using strpbrk.
$a = 'help&type=client';
$b = 'account#client';
$c = 'info&type=client#new';
echo strpbrk($a, '&#') . PHP_EOL; //&type=client
echo strpbrk($b, '&#') . PHP_EOL; //#client
echo strpbrk($c, '&#') . PHP_EOL; //&type=client#new

A: You can use regular expressions for this
preg_match('[^help](.*)', $help, $match)
echo $match[0]; //&type=client

and
preg_match('[^account](.*)', $help, $match)
echo $match[0]; //#client

You can see this website: http://regex101.com/r/zR9eD1/1 for more information about these expressions.
Just a quick explanation:
we do NOT match 'help' and we DO match everything else (after 'help')
edit:
If you only have & or # as a delimiter you can use this:
preg_match('([#].+)', $help, $match)
echo $match[0]; //#client

This matches everything starting with a #

A: myFunction would be something like this:
function myFunction($string) {

    $amp = strpos($string, '&');
        if($amp) {
            return substr($string,$amp,strlen($string)-$amp);
        } else {
            $hash= strpos($string, '#');
            return substr($string,$hash,strlen($string)-$hash);
        }
}

You might have to change if($amp) to if($amp > 0) depending on what the output of strpos is.

A: What about this.
$re = "/[&#]([a-z=]+)/";
$str = "help&type=client\naccount#client";

preg_match_all($re, $str, $matches);

http://regex101.com/r/cW3yL6/1

A: Use a simple preg_split:
function myFunction($var) {
            return $var . "\n";
        }

$a = 'help&type=client';
$b = 'account#client';

$as = preg_split('/(\w+)/', $a, 2);
$bs = preg_split('/(\w+)/', $b, 2);

echo myFunction($as[1]);  // &type=client
echo myFunction($bs[1]);  // #client


text:
Q: Prevent Kubernetes users from being able to create privileged containers I'm currently attempting to look into whether it's possible to prevent a Kubernetes user from creating privileged containers via RBAC. I'm aware that as of Kubernetes 1.1, privileged containers are enabled by default to support underlying Docker requirements. This is fine, I'm not looking to block everybody from being able to run privileged containers.
I would, however, like to work on a principle of least privilege. For example, I'd like to prevent users being able to use something such as kubectl node-shell from being able to gain root access to a worker node, preferably through RBAC.
Is this possible?

A: There are several ways to achieve this and I'd like to start with the first, official one: Pod Security Policy.
The policy you want to implement is the following: Privileged

determines if any container in a pod can enable privileged mode. By default a container is not allowed to access any devices on the host, but a "privileged" container is given access to all devices on the host. This allows the container nearly all the same access as processes running on the host. This is useful for containers that want to use linux capabilities like manipulating the network stack and accessing devices.

The Kubernetes documentation provides few examples on how to interact with PSP, although a big disclaimer must be stated: the PodSecurityPolicy admission controlled must be activated on the API Server.
Besides the official admission controller, there are other projects that allow performing the denial of containers matching criteria, as well as running as privileged: Gatekeeper, Kyverno.
There are other projects that can address your use-case but wanted to share these last two since they seem the most promising ones.
Examples

*

*Gatekeeper

*Kyverno

A: Once PodSecurityPolicies have been enabled on you cluster, the standard recommends creating 3 levels of policies:

*

*privileged

*baseline

*restricted
then you have to use RBAC to map these policies with your users. Here is a minimalist example for all of these: https://github.com/k8s-school/kind-travis-ci/tree/master/psp. It will at least allow to boostrap the control plane once PodSecurityPolicies are enabled, indeed kube-proxy and CNI daemonset, and coredns deployment service accounts require some rights on PodSecurityPolicies in order to be able to create their related pod.

A: The correct answer as of 1.23 is to use Pod Security Standards that are enforced by the Pod Security Admission controller which is included by default since 1.23. K8s has removed Pod Security Policy (PSP) in 1.25 an PSP was deprecated in 1.23.
K8s comes with 3 pre-defined Pod Security Standards: Privileged, Baseline and Restricted. Enforcing the Baseline and Restricted standards would both allow you to prevent privileged pods. However, restricted might be too restrictive for your pod so I would recommend starting with the baseline standard.
Enforcing the baseline Pod Security Standard
Enforcing a pod security standard to a namespace has the risk of preventing new pods from being deployed to the namespace. So lets do a dry-run first instead of directly enforcing baseline.
Run a dry-run and check if any warnings are thrown:
kubectl label --dry-run=server --overwrite ns default \
    pod-security.kubernetes.io/enforce=baseline

If you saw namespace/default labeled without any warnings then that means all the currently running pods inside the namespace default would have been admitted if baseline was enforced.
Assuming you had no warnings. Let's start by enforcing the baseline standard on the default namespace:
kubectl label --overwrite ns default \
    pod-security.kubernetes.io/enforce=baseline

Notice that this time the --dry-run=server parameter is not added.
Let's verify that privileged pods indeed are getting blocked.
Create a file named nginx-priv.yaml with the following content:
apiVersion: v1
kind: Pod
metadata:
  name: nginx-priv
spec:
  containers:
  - name: nginx-priv
    image: nginx:1.14.2
    ports:
    - containerPort: 80
    securityContext:
      privileged: true

Try to create the privileged pod:
kubectl apply -f nginx-priv.yaml

You should see the following output:
Error from server (Forbidden): error when creating "nginx-priv.yaml": pods "nginx-priv" is forbidden: violates PodSecurity "baseline:latest": privileged (container "nginx-priv" must not set securityContext.privileged=true)

Note you can also enforce baseline across all namespaces like this (might cause issues when deploying new pods):
kubectl label --overwrite ns --all \
  pod-security.kubernetes.io/enforce=baseline

Disclaimer: I'm the author of below source
Source: https://samos-it.com/posts/Preventing-Privileged-pods-using-Pod-Security-Admission-Standards.html

redpajama_set_name: RedPajamaStackExchange


text: Q: I want to substract only if m cell contain Yes I want to substract B7- N7 only if M7 contain Yes.... Can you please tell me how to do this. I tried isblank formula but it is not happening... Please tell me how to do it


text:
Q: Parsing text using Nokogiri I have to parse table data which is present at the url below:
http://in.reuters.com/finance/stocks/companyOfficers?symbol=GOOGL.O
I am interested in parsing out the names in the first table that lists all the people under the summary section.
I have read the url into nokogiri but unable to extract as i am new to nokogiri. Can anyone help me on this?

A: I agree that starting with Nokogiri isn't very easy.
Since you didn't provide any code, I won't give you a complete solution, but a basic structure :
require 'nokogiri'
require 'open-uri'

def company_bosses(abbreviation)
  doc  = Nokogiri::HTML(open("http://in.reuters.com/finance/stocks/companyOfficers?symbol=#{abbreviation}"))
  name = doc.xpath('//div[@id="sectionTitle"]').text.strip
  puts name
  table = doc.xpath('//tbody[@class="dataSmall"]')
  puts table.to_s.include?('Eric Schmidt')
  # Keep looking for the desired data inside 'table'!
  # ...
end

company_bosses("GOOGL.O")

It outputs :
Alphabet Inc (GOOGL.O)
true

The data you're looking for is in table variable inside the method. It is a Nokogiri::XML::NodeSet.
The Nokogiri documentation is good enough, and Firefox inspector is a great help when trying to understand an HTML structure (provided the browser hasn't changed it).

A: require 'nokogiri'
require 'open-uri'

At first I open the source and use nokogiri to parse it and get a nokogiri document.
doc = Nokogiri::HTML(open("http://in.reuters.com/finance/stocks/companyOfficers?symbol=GOOGL.O"))

Now I select the elements you are interested in only via an xpath.
elements = doc.xpath('//*[@id="companyNews"]/div/div[2]/table/tbody/tr/td[1]/h2/a')

Last step is to clean the text of each element from newlines and tabs and return the names as unique values.
elements.map{|officer| officer.text.strip}.uniq
# => ["Eric Schmidt", "Sergey Brin", "Lawrence Page", "Ruth Porat", "Sundar Pichai", "David Drummond", "John Hennessy", "L. John Doerr", "Roger Ferguson", "Diane Greene", "Ann Mather", "Alan Mulally", "Paul Otellini", "Kavitark Shriram", "Shirley Tilghman"]

A: require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML(open('http://in.reuters.com/finance/stocks/companyOfficers?symbol=GOOGL.O'))
puts doc.xpath("//div[@id='companyNews']/div[@class='module']/div[@class='moduleBody']/table/tbody/tr/td/h2[@class='officers']/a").text


text:
Q: Is There a Breaking Change to the Ember.CollectionView API in the Latest Build? I have two examples with the same CollectionView code running under 9.8.1 and latest.The 9.8.1 version works: http://jsfiddle.net/ethan_selzer/kcjzw/230/. But the latest version does not: http://jsfiddle.net/kcjzw/232/.
Are there breaking-changes to the Ember.CollectionView API in the latest build? Or, is there an issue with the current build of the CollectionView?
Thanks,
Ethan

A: You can either do what Kristofor Selden suggested in this fiddle http://jsfiddle.net/krisselden/6fAHZ/ (bind the content array in the itemViewClass) or you can do it as follows:
Fiddle: http://jsfiddle.net/ppanagi/WhGjR/
App = Ember.Application.create();

App.collectionView = Ember.CollectionView.create({

    content: [
      { key: 'value one' },
      { key: 'value two' }
    ],

    itemViewClass: Ember.View.extend({
      template: Ember.Handlebars.compile('{{view.content.key}}')
    })
});

App.collectionView.append();

The default context of templates are now controller variables, so {{foo}} will return the value of the controller variable foo. If you need the value of bar variable of the View, use {{view.bar}}.

Follow up: Yet another way to change the context is to use {{with}}:
App.collectionView = Ember.CollectionView.create({
  template: Ember.Handlebars.compile('{{#with view}} {{content.key}} {{/with}}')
});


text:
Q: WebAPI and MVC application security credentials I have two applications - mvc web application for users to enter data and a telerik reporting webapi application. These are two separate sites hosted on the IIS. For both these applications, windows authentication is enabled. We created a role manager that would retrieve roles and userID for the current user from sql. I want this logic to be shared across both these applications. What's the best way to do that?
Does it make sense to use a WCF Authentication Service and create a cookie and share that between the two applications? If so, could you point me in the direction of that? Eventually, I would like for mobile applications we create to also be able to consume the same service.
I keep hearing that the webapi should not be in a different application... That it should be hosted by the main mvc application. We need to make sure that a new release of the reports does not force us to release a new version of the main application. There needs to be a separation of these two. Am I thinking through this the wrong way?
Any help would be appreciated!
Thank you


text:
Q: Graphs of derivative sin functions I am trying to find the intervals on which f is increasing or decreasing, local min and max, and concavity and inflextion points for $f(x)=\sin x+\cos x$ on the interval $[0,\pi]$.
I know at $\pi/4$ the derivative will equal zero. So that gives me my critical numbers, positive and negative $\pi/4$ so now I need to find the intervals which is not making any sense to me, I thought they could only change at critical numbers but $\pi$ and $2\pi$ are different values. I am getting a positive for $2\pi$ and a negtive for $\pi$. How can this happen if the only critical number is $\pi/4$?

A: $f(x)=\sin(x)+\cos(x)$
$f'(x)=\cos(x)-\sin(x)$
critical points are when $f'(x)=0$:
i.e, at:
$\cos(x)=\sin(x)$ which can be satisfied by the values of x such as:
...,$-7{\pi}/4$ , $-3{\pi}/4$, ${\pi}/4$, $3{\pi}/4$,...
now, you need to examine the second derivative's sign at the above points:
$f''(x)=-\sin(x)-\cos(x)$
at $-7{\pi}/4$ , $f''(x)$ is (-) --> Local Max.
at $-3{\pi}/4$,   $f''(x)$ is (+) --> Local Min.
at ${\pi}/4$ , $f''(x)$ is (-) --> Local Max.
at $3{\pi}/4$,   $f''(x)$ is (+) --> Local Min.
The link (example) may help.
also, These plots may help:

A: In short, $\pi / 4$ is not the only critical value. In general, we know $\sin$ and $\cos$ are periodic, so we expect infinitely many critical values. We also know that if $\sin a = 0$, then $\sin (a + \pi) = 0$.
So when you take the derivative, you get $f'(x) = \cos x - \sin x$. You look for critical points - so you check when $\sin x = \cos x$, and you get when they're both positive (which you got), and when they're both negative (which you did not).
Note that $- \pi / 4$ is not a solution.


text:
Q: How To Sign Out Using When Using Google+ Sign-In Google documents there gapi.auth.signOut() method here: https://developers.google.com/+/web/signin/#sign-out
The catch is that it says you can only call that method after the signinCallback has fired. So far as I can tell, the only way to fire the signinCallback is to put a sign-in button on the page.
This works great on my sign-in page itself, but as soon as I've authenticated a user, there's no need to put the G+ sign-in button on subsequent pages. I just want to have a small 'log out' link in the corner that the user can click to sign-out.
I tried having my log-out link call gapi.auth.signOut() but it does nothing unless I am also showing a useless log-in button. How do I get this to work?

A: The button just has to be in the DOM, it doesn't have to be showing. What seems to work well is:

*

*Create a hidden element and attach the gapi handler with gapi.signin.render

*Wait for the immediate_failed error - display the button then

*Otherwise, accept the signed in callback, and display the logout button

Then you'll get a callback every time, but only show the button when signed out.


text:
Q: How do i get python to tail a logfile? Tried various methods I'm trying to get python to tail a logfile e.g. syslog.
I've tried opening the file in read mode, but it never realises if another process writes to the file. Using a popen, and actual 'tail -f' together with registering the popened process to select, python is able to read any writes. And using the python systemd module, i can get systemd to respond with the contents, but I'd like to know if there are other ways instead of these methods and, why the opening a file for reading and constantly trying to read 1024 bytes, doesn't work.

A: It has to work without reopening the file for such logfiles like syslog. Tail also does not reopen files when not needed (and not asked for).
It's just that You need polling on regular files, waiting for data is only possible in pipes and sockets and such.
It would be much better to post the non working code examples You tried to tell You what You is wrong and how to fix. Also it's not very understandable what You want to achieve. If You want something like select or blocking read till data is available that's simply not possible with regular files (by design, they are files not pipes or such stuff).
Only possibility would be to rely on inotify for that or do it the plain old way with polling. (That's same as tail does.)


text:
Q: Why does range is 'reversed' when filtering objects? I've got a car database and I show "similar cars" on each car's page.
To sort the similar cars, I'm going through this filter:
min_power = int(float(car.power_ps) * .8)
max_power = int(float(car.power_ps) * 1.2)

similar_cars = Car.objects.filter(power_ps__range=(min_power, max_power))

This mostly works. However, similar cars don't show up on some cars' pages.
When I tweaked my code a bit, I figured that If I use power_kw (another power unit and model field) instead of power_ps in my queryset, similar cars successfully show up on those pages. But this time, they don't show up on some other cars' pages.
So, I have model instances that:

*

*don't show similar cars when used power_ps but get them with power_kw

*don't show similar cars when used power_kw but get them with power_ps

*don't show similar cars neither when I use power_ps nor power_kw

*show similar cars either when I use power_ps or power_kw
When I investigated further, I found out that If I swap the min_power and max_power in my range filter, similar cars that don't work before show up, but in the opposite way; i.e. they show the cars that are out of min_power-max_power range.
Any suggestion or feedback will be welcomed and greatly appreciated.
Thank you.


text:
Q: Android: running armeabi only apps on Intel devices I'm testing the app that contains some native libraries.
So far these libraries are delivered for armeabi arch only.
The device used for testing purposes is Asus Zenfone 4.
It is Intel based device, so I was expecting problems running the app, as there is no x86 version of the library.
Surprisingly, the app runs fine. The question is why?
Is it because of some kind of ARM emulation?
Is this emulation the case for all Intel Android devices?
/proc/cpuinfo contains the following:
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 53
model name  : Intel(R) Atom(TM) CPU Z2520  @ 1.20GHz
stepping    : 1
microcode   : 0x110
cpu MHz     : 800.000
cache size  : 512 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fdiv_bug    : no
hlt_bug     : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 10
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx constant_tsc arch_perfmon pebs bts nonstop_tsc aperfmperf nonstop_tsc_s3 pni dtes64 monitor ds_cpl vmx est tm2 ssse3 xtpr pdcm movbe lahf_lm arat dtherm tpr_shadow vnmi flexpriority
bogomips    : 2396.16
clflush size    : 64
cache_alignment : 64
address sizes   : 32 bits physical, 32 bits virtual
power management:

A:
Is it because of some kind of ARM emulation?

Yes. It is called libhoudini. Quoting myself:

libhoudini is a proprietary ARM translation layer for x86-powered Android devices. It allows an app that has NDK binaries for ARM, but not x86, to still run on x86 hardware, albeit not as quickly as it would with native x86 binaries.

Note that libhoudini only comes into play with the NDK. Pure Java-based apps should work fine on any supported CPU architecture.

Is this emulation the case for all Intel Android devices?

"All" is a strong word. I'll hedge and say "most Intel-powered Android devices from major manufacturers".


text:
Q: Serializing immutable collections with protobuf-net I'm trying to serialize a class with protobuf-net which contains an immutable collection as a member.
The collection type, ImmutableList<T>, implements ICollection<T> but returns true for the IsReadOnly property. So any attempts to modify it throw an exception.
Protobuf-net seems to rely on being able to call Add(T) after creating a collection in order to populate it. This obviously won't work with an immutable collection, which is a shame because protobuf-net works beautifully with all my other data types, which are also immutable.
So my question is, what options do I have to be able to serialize such collections?

The code for ImmutableList<T> is listed below:
public sealed class ImmutableList<T> : IList<T>, IList
{
    private readonly T[] m_Items;

    public ImmutableList(IEnumerable<T> source)
    {
        m_Items = source.ToArray();
    }

    public T[] ToArray()
    {
        T[] newArray = new T[m_Items.Length];
        m_Items.CopyTo(newArray, 0);
        return newArray;
    }

    private static void ThrowNotSupported()
    {
        throw new NotSupportedException("The attempted operation was not supported as the collection is read-only.");
    }

    #region IList<T> Members

    int IList.Add(object value)
    {
        ThrowNotSupported();
        return -1;
    }

    void IList.Clear()
    {
        ThrowNotSupported();
    }

    void IList<T>.Insert(int index, T item)
    {
        ThrowNotSupported();
    }

    void IList.Insert(int index, object value)
    {
        ThrowNotSupported();
    }

    void IList.Remove(object value)
    {
        ThrowNotSupported();
    }

    void IList.RemoveAt(int index)
    {
        ThrowNotSupported();
    }

    void IList<T>.RemoveAt(int index)
    {
        ThrowNotSupported();
    }

    T IList<T>.this[int index]
    {
        get
        {
            return m_Items[index];
        }
        set
        {
            ThrowNotSupported();
        }
    }

    object IList.this[int index]
    {
        get
        {
            return m_Items[index];
        }
        set
        {
            ThrowNotSupported();
        }
    }

    public T this[int index]
    {
        get
        {
            return m_Items[index];
        }
    }

    bool IList.Contains(object value)
    {
        return Array.IndexOf(m_Items, value) != -1;
    }

    int IList.IndexOf(object value)
    {
        return Array.IndexOf(m_Items, value);
    }

    public int IndexOf(T item)
    {
        return Array.IndexOf(m_Items, item);
    }

    bool IList.IsFixedSize
    {
        get
        {
            return true;
        }
    }

    #endregion

    #region ICollection<T> Members

    void ICollection<T>.Add(T item)
    {
        ThrowNotSupported();
    }

    void ICollection<T>.Clear()
    {
        ThrowNotSupported();
    }

    bool ICollection<T>.Remove(T item)
    {
        ThrowNotSupported();
        return false;
    }

    object ICollection.SyncRoot
    {
        get
        {
            return m_Items;
        }
    }

    bool ICollection.IsSynchronized
    {
        get
        {
            return true;
        }
    }

    public bool Contains(T item)
    {
        return IndexOf(item) != -1;
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        m_Items.CopyTo(array, arrayIndex);
    }

    void ICollection.CopyTo(Array array, int index)
    {
        m_Items.CopyTo(array, index);
    }

    public int Count
    {
        get
        {
            return m_Items.Length;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return true;
        }
    }

    #endregion

    #region IEnumerable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        return ((IEnumerable<T>)m_Items).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return m_Items.GetEnumerator();
    }

    #endregion
}

A: At the moment there is no support for that; but it seems a reasonable scenario. It depends on what you mean (comments) by "out of the box"; if you mean "today, without code changed", it would need to use a surrogate against the DTO, or a shim property that exposed the immutable list as a mutable one; if you mean "moving forwards", I suspect we could look at list-constructors that take (perferable) IEnumerable[<T>] or (less preferable, but doable) T[], and simply construct the list after buffering the data.


text:
Q: Using the field calculator to calculate intersections I'm comparing several maps of one area (made by different people) to each other, and used intersection to find how much of specific selected features (polygons) overlapped. I soon realised that the intersection did not calculate the overlapping area. I have been told that the easiest way to find the area of the overlap is to do it using the "Field calculator" after the intersection, but I can't figure out how.
If anyone knows an easier way, I'm open to that as well.

A: As an addition to the solution above (@babel): you can do it also only with the field calculator, without doing the intersection with the processing tools. The expression is something like this one to get the area for the blue ones:
area(intersection($geometry,aggregate('orange','collect', $geometry, intersects($geometry, geometry(@parent)))))

A: Use Menu Vector / Geoprocessing tools / Intersection, set the two polygon layers you use (named orange and blue in my case) as input and you get the intersecting area (outlined in red on the screenshot) as a output in a new polygon layer intersection. On this layer, open field calculator to calculate the area using either area ($geometry) or $area.


text:
Q: Wordpress search template for custom post type I made a custom post type plugin to display team member in wordpress name team to display custom post type I made archive-team.php and single-team.php all that works great and independent  of theme used.
Now my problem is that I want to include custom post type in search also but I think there is no such thing searh-team.php and to display search template for custom post type i have to modify search.php which varies from theme to theme.
So can anyone point me in right direction to make search template independent of theme.
Regards

A: Follow these 3 steps to achieve custom post search.
Lets say your custom post type name is employee_member.

*

*Add Below code into function.php
function template_chooser($template)
{
  global $wp_query;
  $post_type = get_query_var('post_type');
  if( $wp_query->is_search && $post_type == 'employee_member' )
  {
    return locate_template('employee-search.php');  //  redirect to archive-search.php
  }
  return $template;
}
add_filter('template_include', 'template_chooser');

*Create file employee-search.php

/* Template Name: Custom Search */
<?php get_header(); ?>

Search Result for : <?php echo "$s"; ?>

        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div id="post-<?php the_ID(); ?>" class="posts">

<a href="<?php the_permalink();?>" title="<?php the_title();?>"><?php the_title(); ?>

<?php the_exerpt(); ?>

<a href="<?php the_permalink(); ?>">Read     More

                 Post By <?php the_author(); ?>
                    | Date : <?php echo date('j F Y'); ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

*Finally create a search form for your custom post type

Search Employee Member

   <form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform">
       <input type="text" name="s" placeholder="Search Products"/>
       <input type="hidden" name="post_type" value="employee_member" />
       <input type="submit" alt="Search" value="Search" />
   </form>

A: Use pre_get_posts() to alter the query
To do this, a good practice is to use pre_get_posts() to alter the search query.
This code can be dropped in the functions.php of the theme or directly into a plugin.
<?php
// Call our function my_search()
add_filter( 'pre_get_posts', 'my_search' );

function my_search($query) {

    // Check if we are on the front end main search query
    if ( !is_admin() && $query->is_main_query() && $query->is_search() ) {

        // Change the post_type parameter on the query
        $query->set('post_type', 'team');
    }

    // Return the modified query
    return $query;
}
?>

The search will now be queried only your custom post type "team".
If you would like the research also integrates post and pages, you can modify the following line:
<?php
$query->('post_type', array('team', 'post', 'page'));
?>

If you use the add_filter() in a PHP Class, be careful to declare your filter like this:
<?php
add_filter( 'pre_get_posts', array( $this, 'my_search' ) );
?>

A: You can add this in your functions.php :
function filter_search($query) {
    if ($query->is_search) {
    $query->set('post_type', array('post', 'team')); // Add all post types you want results for.
    };
    return $query;
};
add_filter('pre_get_posts', 'filter_search');


text:
Q: KnockoutJS not updating view I am having an issue with Knockout which seems a bit puzzling.
I have a list of contacts, which I want to bind to the UI (observableArray).
However I do not need the items themselves to each be observable, since they are only updated through a dialog box and I don't need each field tracked separately.
I have the following jsFiddle to demonstrate my issue:
http://jsfiddle.net/EsgGg/12/
var c = contacts()[0];
c.name="James";
contacts.splice( 0, 1, c );
// the contacts observableArray is now correct but the UI is unchanged

For some reason the splice method does not update the View??
Thanks in advance.
I really think that Knockout should allow a trigger('change') or some other method on observables to make this type of thing easier.

A: Knockout has a change trigger on observables. It's called valueHasMutated()
contacts.valueHasMutated();

But in fact you are better off if every value that shows on the screen (and is subject to occasional change) is an actual observable in your view model.
contacts()[0].name("James");  // done


text:
Q: Notify ObservableCollection when Item changes I found on this link
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)
some techniques to notify a Observablecollection that an item has changed. the TrulyObservableCollection in this link seems to be what i'm looking for.
public class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
    public TrulyObservableCollection()
    : base()
    {
        CollectionChanged += new NotifyCollectionChangedEventHandler(TrulyObservableCollection_CollectionChanged);
    }

    void TrulyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (Object item in e.NewItems)
            {
                (item as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
            }
        }
        if (e.OldItems != null)
        {
            foreach (Object item in e.OldItems)
            {
                (item as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
            }
        }
    }

    void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
        OnCollectionChanged(a);
    }
}

But when I try to use it, I don't get notifications on the collection. I'm not sure how to correctly implement this in my C# Code:
XAML :
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyItemsSource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        </DataGrid.Columns>
    </DataGrid>

ViewModel :
public class MyViewModel : ViewModelBase
{
    private TrulyObservableCollection<MyType> myItemsSource;
    public TrulyObservableCollection<MyType> MyItemsSource
    {
        get { return myItemsSource; }
        set
        {
            myItemsSource = value;
            // Code to trig on item change...
            RaisePropertyChangedEvent("MyItemsSource");
        }
    }

    public MyViewModel()
    {
        MyItemsSource = new TrulyObservableCollection<MyType>()
        {
            new MyType() { MyProperty = false },
            new MyType() { MyProperty = true },
            new MyType() { MyProperty = false }
        };
    }
}

public class MyType : ViewModelBase
{
    private bool myProperty;
    public bool MyProperty
    {
        get { return myProperty; }
        set
        {
            myProperty = value;
            RaisePropertyChangedEvent("MyProperty");
        }
    }
}

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
            PropertyChanged(this, e);
        }
    }
}

When i run the program, i have the 3 checkbox to false, true, false as in the property initialisation.
but when i change the state of one of the ckeckbox, the program go through item_PropertyChanged but never in MyItemsSource Property code.

A: The spot you have commented as // Code to trig on item change... will only trigger when the collection object gets changed, such as when it gets set to a new object, or set to null.
With your current implementation of TrulyObservableCollection, to handle the property changed events of your collection, register something to the CollectionChanged event of MyItemsSource
public MyViewModel()
{
    MyItemsSource = new TrulyObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}

void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Handle here
}

Personally I really don't like this implementation. You are raising a CollectionChanged event that says the entire collection has been reset, anytime a property changes. Sure it'll make the UI update anytime an item in the collection changes, but I see that being bad on performance, and it doesn't seem to have a way to identify what property changed, which is one of the key pieces of information I usually need when doing something on PropertyChanged.
I prefer using a regular ObservableCollection and just hooking up the PropertyChanged events to it's items on CollectionChanged. Providing your UI is bound correctly to the items in the ObservableCollection, you shouldn't need to tell the UI to update when a property on an item in the collection changes.
public MyViewModel()
{
    MyItemsSource = new ObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}

void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(MyType item in e.NewItems)
            item.PropertyChanged += MyType_PropertyChanged;

    if (e.OldItems != null)
        foreach(MyType item in e.OldItems)
            item.PropertyChanged -= MyType_PropertyChanged;
}

void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
        DoWork();
}

A: You could use an extension method to get notified about changed property of an item in a collection in a generic way.
public static class ObservableCollectionExtension
{
    public static void NotifyPropertyChanged<T>(this ObservableCollection<T> observableCollection, Action<T, PropertyChangedEventArgs> callBackAction)
        where T : INotifyPropertyChanged
    {
        observableCollection.CollectionChanged += (sender, args) =>
        {
            //Does not prevent garbage collection says: http://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring
            //publisher.SomeEvent += target.SomeHandler;
            //then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.
            if (args.NewItems == null) return;
            foreach (T item in args.NewItems)
            {
                item.PropertyChanged += (obj, eventArgs) =>
                {
                    callBackAction((T)obj, eventArgs);
                };
            }
        };
    }
}

public void ExampleUsage()
{
    var myObservableCollection = new ObservableCollection<MyTypeWithNotifyPropertyChanged>();
    myObservableCollection.NotifyPropertyChanged((obj, notifyPropertyChangedEventArgs) =>
    {
        //DO here what you want when a property of an item in the collection has changed.
    });
}

A: I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    private void Handle(object sender, PropertyChangedEventArgs args)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null) {
            foreach (object t in e.NewItems) {
                ((T) t).PropertyChanged += Handle;
            }
        }
        if (e.OldItems != null) {
            foreach (object t in e.OldItems) {
                ((T) t).PropertyChanged -= Handle;
            }
        }
        base.OnCollectionChanged(e);
    }

While Items are added or removed the class forwards the items PropertyChanged event to the collections PropertyChanged event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
    protected readonly CultureInfo Ci = new CultureInfo("en-US");
    private string _value;

    public string Value {
        get { return _value; }
        set {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
}

public class AItem {
    public NotifyObservableCollection<ParameterBase> Parameters {
        get { return _parameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_parameters != null) _parameters.CollectionChanged -= cceh;
            _parameters = value;
            //needed for Binding to AItem at xaml directly
            _parameters.CollectionChanged += cceh;
        }
    }

    public NotifyObservableCollection<ParameterBase> DefaultParameters {
        get { return _defaultParameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
            _defaultParameters = value;
            //needed for Binding to AItem at xaml directly
            _defaultParameters.CollectionChanged += cceh;
        }
    }

public class MyViewModel {
    public NotifyObservableCollection<AItem> DataItems { get; set; }
}

If now a property of an item in DataItems changes, the following xaml will get a notification, though it binds to Parameters[0] or to the item itself except to the changing property Value of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="Background" Value="Aqua" />
                    <Style.Triggers>
                        <DataTrigger Value="False">
                            <!-- Bind to Items with changing properties -->
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ParameterCompareConverter}">
                                    <Binding Path="DefaultParameters[0]" />
                                    <Binding Path="Parameters[0]" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="Background" Value="DeepPink" />
                        </DataTrigger>
                        <!-- Binds to AItem directly -->
                        <DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
                            <Setter Property="FontWeight" Value="ExtraBold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

A: All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.
this is the perfect ObservableCollection .
public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion

    public new void Clear()
    {
        foreach (var item in this)
            if (item is INotifyPropertyChanged i)
                i.PropertyChanged -= Element_PropertyChanged;
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)
                if (item != null && item is INotifyPropertyChanged i)
                    i.PropertyChanged -= Element_PropertyChanged;

        if (e.NewItems != null)
            foreach (var item in e.NewItems)
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);

    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

A: The ObservableCollection and its derivatives raises its property changes internally. The code in your setter should only be triggered if you assign a new TrulyObservableCollection<MyType> to the MyItemsSource property. That is, it should only happen once, from the constructor.
From that point forward, you'll get property change notifications from the collection, not from the setter in your viewmodel.

A: One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:
    var index = Artists.IndexOf(artist);
    Artists.RemoveAt(index);
    artist.IsFollowed = true; // change something in the item
    Artists.Insert(index, artist);

A: A simple solution is to use BindingList<T> instead of ObservableCollection<T> . Indeed the BindingList relay item change notifications. So with a binding list, if the  item implements the interface INotifyPropertyChanged then you can simply get notifications using the ListChanged event.
See also this SO answer.

A: I solved this case by using static Action

public class CatalogoModel
{
    private String _Id;
    private String _Descripcion;
    private Boolean _IsChecked;

    public String Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    public String Descripcion
    {
        get { return _Descripcion; }
        set { _Descripcion = value; }
    }
    public Boolean IsChecked
    {
        get { return _IsChecked; }
        set
        {
           _IsChecked = value;
            NotifyPropertyChanged("IsChecked");
            OnItemChecked.Invoke();
        }
    }

    public static Action OnItemChecked;
}

public class ReglaViewModel : ViewModelBase
{
    private ObservableCollection<CatalogoModel> _origenes;

    CatalogoModel.OnItemChecked = () =>
            {
                var x = Origenes.Count;  //Entra cada vez que cambia algo en _origenes
            };
}


text:
Q: Simple Probability Formula and Convergence I have the probability of an event A defined as $P(A) = \frac{N_{a}}{N}$.
In order to understand precisely this concept, i hypothesized that the meaning of this formula is :
,

as i repeat the observation of the event A in practically the same
  conditions, i get that, as $i$ grows, $\frac{\sum N_{a_{i}}}{\sum N_{i}}\Rightarrow  \frac{N_{a}}{N}$, where $N_{a_{i}}$ is a specific occurrence of event
  A.

Is it correct ?

A: You mention a limiting process. My guess is you are looking at the
so-called 'frequentist' formulation of probability.
This formulation of probability requires a repeatable experiment.
Suppose you are tossing a fair coin and are interested in the probability
of getting a Head. For simplicity we denote Heads as $1$'s and Tails as $0$'s
At the $n$th toss of the coin we get a number $T_i$ which is $0$ of $1.$
After each toss, we look at the number $A_n$
of $1$'s up through the $n$th roll and the ratio $R_n = A_n/n$
which is the proportion of $1$'s up through
the $n$th roll.
If I simulate 4000 tosses of such a coin using a computer, then I might get
a data table with the first 10 rows looking like this:
   n t a         r
   1 1 1 1.0000000
   2 1 2 1.0000000
   3 0 2 0.6666667
   4 0 2 0.5000000
   5 0 2 0.4000000
   6 1 3 0.5000000
   7 0 3 0.4285714
   8 0 3 0.3750000
   9 1 4 0.4444444
  10 1 5 0.5000000

I happened to get Heads ($1$'s) on tosses 1, 2, 6, 9, and 10.
Up to the 5th roll I had two $1$s for a ratio $R_5 = 0.4$ and
up to the 10th roll I had five $1$s for a ratio $R_{10} = 0.5.$
At the beginning, the ratios $R_n$ fluctuate greatly.
However, if we look at the last ten entries in the data table,
here is what I see:
     n t   a         r
  3991 0 2019 0.5058882
  3992 0 2019 0.5057615
  3993 0 2019 0.5056349
  3994 1 2020 0.5057586
  3995 1 2021 0.5058824
  3996 1 2022 0.5060060
  3997 1 2023 0.5061296
  3998 0 2023 0.5060030
  3999 1 2024 0.5061265
  4000 1 2025 0.5062500

The values of $R_n$ have stabilized very near to $1/2$, the probability of
getting Heads. A plot of the ratio $R_n$ against $n$ is shown below.

Because coin tossing is a random process, there is no guarantee what
value $R_{4000}$ will take. A theorem you will likely see a little later
in your course, called the Law of Large Numbers, says $R_n$ tends to
get ever closer to $1/2$ as $n$ increases. Usually, by about $n = 4000$
we get $R_n$ in the range $0.5 \pm 0.016.$
(Somewhere around $n = 300$
we happened to get a lot of Tails, but eventually those 'extra'
Tails
were balanced by the large patches of results where Heads and Tails
happened to be nearly equal. The blue line will often behave
'badly', with a lot of variability, near the left of the graph where $n$ is small. Certainly, the coin is not consciously
keeping track to compensate for patches of strange behavior early on.
It's called the law of large numbers because random anomalies early
on get 'swamped out' by huge numbers of tosses later on.)
However, this is not a
deterministic limiting process.  For the sequence $D_n = \frac{n+5}{2n-7}$
we know exactly what $D_n$ will be for each value of $n$ and we can write
$\lim_{n \rightarrow \infty} D_n = 1/2,$ without mentioning anything about
probability.
For the coin-tossing limit, we sometimes write
$\text{plim}_{n \rightarrow \infty} R_n = 1/2$ and say "$R_n$
converges in probability to $1/2.$" But that expression
needs a careful definition before we can prove theorems about it.


text:
Q: How to delete white spaces of a text in twig? I'm using the twig template engine while using symfony2. I'm trying to find a way to delete the white spaces from a text.
For example, I play shall become Iplay.
I've tried:

*

*Spaceless

*Trim

A: First let's see what you tried and why that wasn't working:

*

*Spaceless: is not working because "Use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text" see spaceless documentation.

*Trim: is not working because "The trim filter strips whitespace (or other characters) from the beginning and end of a string" see trim documentation.

What you need to use is the following:
{{ 'Some Text With Spaces'|replace({' ': ''}) }}

This will output:
SomeTextWithSpaces

More details in the documentation.

A: Try this:
{{ "I plays"|replace({' ':''}) }}

A: You can also create your own filter to do that
Example :
class MyExtensions extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('removeWhiteSpace', array($this, 'removeWhiteSpace'), array('is_safe' => array('html'))),
        );
    }

    public function removeWhiteSpace($string)
    {

       return preg_replace('/\s+/', '', $string);
    }
}

Declare it as service :
myextensions.twig_extension:
      class: YourProject\YourBundle\Twig\MyExtensions
      public: false
      tags:
          - { name: twig.extension }

And call it in yours twig template :
{{ "Test remove white space"|removeWhiteSpace }}

A: For me this was not working when string contains non-breaking whitespaces:
stringWithNonBreakingWhitespace|replace({' ':''}

To replace non-braking whitespace you have to use escape sequence:
stringWithNonBreakingWhitespace|replace({'\xc2\xa0':''}


text:
Q: How to make one validation error for 2 fields I have 2 fields for postal code main and sub.
<input type="text" name="postal01">
<input type="text" name="postal02">

I would like to have validation for numeric and size of both fields added.
What I want to do is showing validation error for one field as postal_cd, not each field error.
I had tried in a request class extended FormRequest.
class MemberRequest extends FormRequest
{
  public function all($keys = null)
  {
    $result = parent::all($keys);

    if($this->filled('postal01') && $this->filled('postal02')) {
        $results['postal_code'] = $this->input('postal01') . $this->input('postal02');
    }
    return $result;
}

However it did not work like I expected.
How can I handle this case?

A: You can use an After Validation Hook. Add the following to your Form Request:
/**
* Configure the validator instance.
*
* @param  \Illuminate\Validation\Validator  $validator
* @return void
*/
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if($validator->errors()->has('postal01') || $validator->errors()->has('postal02')) {
            $validator->errors()->add('postal_cd', 'Please enter a postal code');
        }
    });
}

... and then to display it on your blade:
{{ $errors->first('postal_cd') }}

A: That was my typo.
class MemberRequest extends FormRequest
{
  public function all($keys = null)
  {
    $result = parent::all($keys);

    if($this->filled('postal01') && $this->filled('postal02')) {
      $result['postal_code'] = $this->input('postal01') . $this->input('postal02');
   // $results['postal_code'] = $this->input('postal01') . $this->input('postal02');
    }
    return $result;
}

Returned value should have been $result. But it was typo $results['postal_code'].
It works.


text:
Q: I'm unable to get result using this query create table Item
(
    Itemid int primary key ,
    ItemName varchar(100),
    CalorificValue int,
    price int
)

Task: what item has the highest price followed by the highest calorific value?
My query solution:
Select Itemname
from Item
where price = (Select max(price) from Item)
  and CalorificValue = (Select max(CalorificValue) from Item)

But I'm not getting the answer. Can anyone solve this issue?

A: Try the following with limit
select
    TOP 1 ItemName
from yourTable
order by
    price desc,
    CalorificValue desc


text:
Q: Sql Azure storage key info I need to build the secondary key to access storage table
The questions are:

*

*Is there a limit of lengths for the secondary storage key?

*Is there a limit of which characters could be constructed secondary key?
I.e. could it have ' ',';',':' etc?
Thanks

A: Assuming you're talking about Azure Storage Service Key (for Blobs, Tables and Queues) and not SQL Database (formerly known as SQL Azure), to answer your questions:

*

*Primary and secondary keys are created by Azure for you. You can't specify these keys. When you create a storage account, these keys are automatically created for you. You could rengenerate either or both of these keys later on any time either programmatically or through Azure Portal.

*These keys are Base64 encoded string and will have all the characters allowed in a Base64 encoded string.


text:
Q: Django Admin: Add User settings.Database Improperly configured Trying to Add a User by Django Admin App I get the following error:
settings.DATABASE is improperly configured
My Databases are defined as:
DATABASE_ROUTERS = ['*****.routers.RouterDB',]
    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy'
    },
    'helpdesk': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'mongoengine.django.auth.MongoEngineBackend',
)

And in my Router: So If the App is different from **** I get the 'helpdesk' DB that is the SQLite with Django Users.
The Mongo Database stores Users for another app that it's not to use Django App
from django.conf import settings

class RouterDB:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == '****':
            return 'default'
        return 'helpdesk'

    def db_for_write(self, model, **hints):
        if model._meta.app_label == '****':
            return 'default'
        return 'helpdesk'

    def allow_relation(self, obj1, obj2, **hints):

        if  obj1._meta.app_label == 'helpdesk' or \
            obj2._meta.app_label == 'helpdesk':
            return True
        if  obj1._meta.app_label == 'default' or \
            obj2._meta.app_label == 'default':
            return True
        return False

    def allow_migrate(self, db, app_label, model_name=None, **hints):

        if app_label == 'helpdesk':
            return db == 'helpdesk'
        if app_label == '****':
            return db == 'default'
        return 'default'


text:
Q: R: circlize circos plot - how to plot unconnected areas between sectors with minimal overlap I have a data frame with common features between 4 groups of patients and cell types. I have a lot of different features, but the shared ones (present in more than 1 group) are just a few.
I want to make a circos plot that reflects the few connections between shared features across groups of patients and cell types, while giving an idea of how many unshared features there are in each group.
The way I think of it, it should be a plot with 4 sectors (one for each group of patient and cell type) with a few connections between them. Each sector size should reflect the total number of features in the group, and most of this area should not be connected to other groups, but empty.
This is what I have so far, but I do not want sectors dedicated to each feature, only to each group of patient and cell type.
MWE:
library(circlize)

patients <- c(rep("patient1",20), rep("patient2",10))
cell.types <- c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4))
features <- c(paste("feature",1:12,sep="_"), paste("feature",9:16,sep="_"), paste("feature",c(1,2,9,10,17,18),sep="_"), paste("feature",c(1,18,19,20),sep="_"))
dat <- data.frame(patient=patients, cell.type=cell.types, feature=features)
dat
dat <- with(dat, table(paste(patient,cell.type,sep='|'), feature))
dat

chordDiagram(as.data.frame(dat), transparency = 0.5)

EDIT!!
What @m-dz shows in his answer is actually the format I am looking for, 4 sectors for the 4 different patient/cell.type combinations, showing just the connections, while the non-connected features, though not shown, should account for the size of the sector.
However, I am realizing I have a more complicated scenario than the one in the MWE above.
A feature is considered to appear in 2 patient/cell.type groups, not only when it is identical in the 2 groups, but also when it is similar... (sequence identity above a threshold). This way, I have redundancies...
Feature A in patient1-cell1 can be connected to feature A in patient2-cell1, but also to feature B... Feature A should only be counted once (unique counts) for patient1-cell1, and expand to 2 different features in patient2-cell1.
See below an example of how my actual data looks like more precisely, and see if working with this example we can get the final circos plot! Thanks!!
##MWE
#NON OVERLAPPING SETS!

#1: non-shared features
nonshared <- data.frame(patient=c(rep("pat1",20), rep("pat2",10)), cell.type=c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4)), feature=paste("a",1:30,sep=''))
nonshared

#2: features shared between cell types within same patient
sharedcells <- data.frame(patient=c(rep("pat1",3), rep("pat2",4)), cell.types=c(rep("cell1||cell2",3),rep("cell1||cell2",4)), features=c("b1||b1","b1||b1","b1||b1","b2||b2","b3||b3","b4||b4","b4||b5"))
sharedcells

#3: features shared between patients within same cell types
sharedpats <- data.frame(patients=c(rep("pat1||pat2",2), rep("pat1||pat2",6)), cell.type=c(rep("cell1",2),rep("cell2",6)), features=c("c1||c1","c2||c1","c3||c3","c3||c4","c3||c5","c6||c5","c7||c7","c8||c8"))
sharedpats

#4: features shared between patients and cell types
#4.1: shared across pat1-cell1, pat1-cell2, pat2-cell1, pat2-cell2
sharedall1 <- data.frame(both=c(rep("pat1-cell1||pat1-cell2||pat2-cell1||pat2-cell2",4)), features=c("d1||d1||d1||d1","d2||d2||d2||d3","d4||d4||d3||d3","d5||d5||d5||d5"))
#4.2: shared across pat1-cell1, pat1-cell2, pat2-cell1
sharedall2 <- data.frame(both=c(rep("pat1-cell1||pat1-cell2||pat2-cell1",2)), features=c("d6||d6||d6","d7||d7||d7"))
#4.3: shared across pat1-cell1, pat1-cell2, pat2-cell2
sharedall3 <- data.frame(both="pat1-cell1||pat1-cell2||pat2-cell2", features="d8||d8||d9")
#4.4: shared across pat1-cell1, pat2-cell1, pat2-cell2
sharedall4 <- data.frame(both="pat1-cell1||pat2-cell1||pat2-cell2", features="d10||d10||d9")
#4.5: shared across pat1-cell2, pat2-cell1, pat2-cell2
sharedall5 <- data.frame(both=c(rep("pat1-cell2||pat2-cell1||pat2-cell2",3)), features=c("d11||d11||d11","d12||d13||d13","d12||d14||d14"))
#4.6: shared across pat1-cell1, pat2-cell2
sharedall6 <- data.frame()
#4.7: shared across pat1-cell2, pat2-cell1
sharedall7 <- data.frame(both=c(rep("pat1-cell2||pat2-cell1",2)), features=c("d15||d16","d17||d17"))

sharedall <- rbind(sharedall1, sharedall2, sharedall3, sharedall4, sharedall5, sharedall6, sharedall7)
sharedall
#you see there might be overlaps between the different subsets of sharedall, but not between sharedall, sharedparts, sharedcells, and nonshared

#I NEED A CIRCOS PLOT THAT SHOWS ALL THE CONNECTIONS. THE NON-CONNECTED (nonshared) FEATURES SHOULD NOT BE SHOWN, BUT THE SHOULD COUNT TO THE SIZE OF THE SECTOR (CORRESPONDING TO A PATIENT-CELL COMBINATION)

#THE FEATURES SHOULD BE COUNT UNIQUELY, SO IF THERE ARE ENTRIES LIKE:
#3 pat1||pat2     cell2   c3||c3
#4 pat1||pat2     cell2   c3||c4
#5 pat1||pat2     cell2   c3||c5
#THE FEATURE c3 SHOULD BE COUNT ONCE FOR pat1, AND EXPAND TO 3 DIFFERENT FEATURES IN pat2

A: A side note about the expected outcome: aim was to create a plot showing simply how much features are shared, ignoring individual features (1st plot below) or shared features overlap (e.g. on the 2nd plot it looks like the same features are shared between all groups, which is not true looking at the 1st plot, but what is important here is the ratio of features shared between groups).
Code below produces the following two figures (fig. 1 left for reference):
All individual features

Simple counts of unique and shared features

One of those should meet the expectations.
# Prep. data --------------------------------------------------------------

nonshared <- data.frame(patient=c(rep("pat1",20), rep("pat2",10)), cell.type=c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4)), feature=paste("a",1:30,sep=''))
sharedcells <- data.frame(patient=c(rep("pat1",3), rep("pat2",4)), cell.types=c(rep("cell1||cell2",3),rep("cell1||cell2",4)), features=c("b1||b1","b1||b1","b1||b1","b2||b2","b3||b3","b4||b4","b4||b5"))
sharedpats <- data.frame(patients=c(rep("pat1||pat2",2), rep("pat1||pat2",6)), cell.type=c(rep("cell1",2),rep("cell2",6)), features=c("c1||c1","c2||c1","c3||c3","c3||c4","c3||c5","c6||c5","c7||c7","c8||c8"))
sharedall1 <- data.frame(both=c(rep("pat1-cell1||pat1-cell2||pat2-cell1||pat2-cell2",4)), features=c("d1||d1||d1||d1","d2||d2||d2||d3","d4||d4||d3||d3","d5||d5||d5||d5"))
sharedall2 <- data.frame(both=c(rep("pat1-cell1||pat1-cell2||pat2-cell1",2)), features=c("d6||d6||d6","d7||d7||d7"))
sharedall3 <- data.frame(both="pat1-cell1||pat1-cell2||pat2-cell2", features="d8||d8||d9")
sharedall4 <- data.frame(both="pat1-cell1||pat2-cell1||pat2-cell2", features="d10||d10||d9")
sharedall5 <- data.frame(both=c(rep("pat1-cell2||pat2-cell1||pat2-cell2",3)), features=c("d11||d11||d11","d12||d13||d13","d12||d14||d14"))
sharedall6 <- data.frame()
sharedall7 <- data.frame(both=c(rep("pat1-cell2||pat2-cell1",2)), features=c("d15||d16","d17||d17"))
sharedall <- rbind(sharedall1, sharedall2, sharedall3, sharedall4, sharedall5, sharedall6, sharedall7)

#I NEED A CIRCOS PLOT THAT SHOWS ALL THE CONNECTIONS. THE NON-CONNECTED (nonshared) FEATURES SHOULD NOT BE SHOWN, BUT THE SHOULD COUNT TO THE SIZE OF THE SECTOR (CORRESPONDING TO A PATIENT-CELL COMBINATION)

#THE FEATURES SHOULD BE COUNT UNIQUELY, SO IF THERE ARE ENTRIES LIKE:
#3 pat1||pat2     cell2   c3||c3
#4 pat1||pat2     cell2   c3||c4
#5 pat1||pat2     cell2   c3||c5
#THE FEATURE c3 SHOULD BE COUNT ONCE FOR pat1, AND EXPAND TO 3 DIFFERENT FEATURES IN pat2

# Start -------------------------------------------------------------------

library(circlize)
library(data.table)
library(magrittr)
library(stringr)
library(RColorBrewer)

# Split and pad with 0 ----------------------------------------------------
fun <- function(x) unlist(tstrsplit(x, split = '||', fixed = TRUE))

nonshared %>% setDT()
sharedcells %>% setDT()
sharedpats %>% setDT()
sharedall %>% setDT()

nonshared <- nonshared[, .(group = paste(patient, cell.type, sep = '-'), feature)][, feature := paste0('a', str_pad(str_extract(feature, '[0-9]+'), 2, 'left', '0'))]
sharedcells <- sharedcells[, lapply(.SD, fun), by = 1:nrow(sharedcells)][, .(group = paste(patient, cell.types, sep = '-'), feature = features)][, feature := paste0('b', str_pad(str_extract(feature, '[0-9]+'), 2, 'left', '0'))]
sharedpats <- sharedpats[, lapply(.SD, fun), by = 1:nrow(sharedpats)][, .(group = paste(patients, cell.type, sep = '-'), feature = features)][, feature := paste0('c', str_pad(str_extract(feature, '[0-9]+'), 2, 'left', '0'))]
sharedall <- sharedall[, lapply(.SD, fun), by = 1:nrow(sharedall)][, .(group = both, feature = features)][, feature := paste0('d', str_pad(str_extract(feature, '[0-9]+'), 2, 'left', '0'))]

dt_split <- rbindlist(
  list(
    nonshared,
    sharedcells,
    sharedpats,
    sharedall
  )
)

# Set key and self join to find shared features ---------------------------
setkey(dt_split, feature)
dt_join <- dt_split[dt_split, .(group, i.group, feature), allow.cartesian = TRUE] %>%
  .[group != i.group, ]

# Create a "sorted key" ---------------------------------------------------
# key := paste(sort(.SD)...
# To leave only unique combinations of groups and features
dt_join <-
  dt_join[,
          key := paste(sort(.SD), collapse = '|'),
          by = 1:nrow(dt_join),
          .SDcols = c('group', 'i.group')
          ] %>%
  setorder(feature, key) %>%
  unique(by = c('key', 'feature')) %>%
  .[, .(
    group_from = i.group,
    group_to = group,
    feature = feature)]

# Rename and key ----------------------------------------------------------

dt_split %>% setnames(old = 'group', new = 'group_from') %>% setkey(group_from, feature)
dt_join %>% setkey(group_from, feature)

# Individual features -----------------------------------------------------

# Features without connections --------------------------------------------

dt_singles <- dt_split[, .(group_from, group_to = group_from, feature)] %>%
  .[, N := .N, by = feature] %>%
  .[!(N > 1 & group_from == group_to), !c('N')]

# Bind all, add some columns etc. -----------------------------------------

dt_bind <- rbind(dt_singles, dt_join) %>% setorder(group_from, feature, group_to)

dt_bind[, ':='(
  group_from_f = paste(group_from, feature, sep = '.'),
  group_to_f = paste(group_to, feature, sep = '.'))]
dt_bind[, feature := NULL]  # feature can be removed

# Colour
dt_bind[, colour := ifelse(group_from_f == group_to_f, "#FFFFFF00", '#00000050')]  # Change first to #FF0000FF to show red blobs

# Prep. sectors -----------------------------------------------------------

sectors_f <- union(dt_bind[, group_from_f], dt_bind[, group_to_f]) %>% sort()

colour_lookup <-
  union(dt_bind[, group_from], dt_bind[, group_to]) %>% sort() %>%
  structure(seq_along(.) + 1, names = .)
sector_colours <- str_replace_all(sectors_f, '.[a-d][0-9]+', '') %>%
  colour_lookup[.]

# Gaps between sectors ----------------------------------------------------

gap_sizes <- c(0.0, 1.0)
gap_degree <-
  sapply(table(names(sector_colours)), function(i) c(rep(gap_sizes[1], i-1), gap_sizes[2])) %>%
  unlist() %>% unname()
# gap_degree <- rep(0, length(sectors_f))  # Or no gap

# Plot! -------------------------------------------------------------------

# Each "sector" is a separate patient/cell/feature combination

circos.par(gap.degree = gap_degree)
circos.initialize(sectors_f, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), track.height = 0.05, bg.col = sector_colours, bg.border = NA)

for(i in 1:nrow(dt_bind)) {
  row_i <- dt_bind[i, ]
  circos.link(
    row_i[['group_from_f']], c(0, 1),
    row_i[['group_to_f']], c(0, 1),
    border = NA, col = row_i[['colour']]
  )
}

# "Feature" labels
circos.trackPlotRegion(track.index = 2, ylim = c(0, 1), panel.fun = function(x, y) {
  sector.index = get.cell.meta.data("sector.index")
  circos.text(0.5, 0.25, sector.index, col = "white", cex = 0.6, facing = "clockwise", niceFacing = TRUE)
}, bg.border = NA)

# "Patient/cell" labels
for(s in names(colour_lookup)) {
  sectors <- sectors_f %>% { .[str_detect(., s)] }
  highlight.sector(
    sector.index = sectors, track.index = 1, col = colour_lookup[s],
    text = s, text.vjust = -1, niceFacing = TRUE)
}

circos.clear()

# counts of unique and shared features ------------------------------------

xlims <- dt_split[, .N, by = group_from][, .(x_from = 0, x_to = N)] %>% as.matrix()
links <- dt_join[, .N, by = .(group_from, group_to)]
colours <- dt_split[, unique(group_from)] %>% structure(seq_along(.) + 1, names = .)

library(circlize)

sectors = names(colours)
circos.par(cell.padding = c(0, 0, 0, 0))
circos.initialize(sectors, xlim = xlims)
circos.trackPlotRegion(ylim = c(0, 1), track.height = 0.05, bg.col = colours, bg.border = NA)

for(i in 1:nrow(links)) {
  link <- links[i, ]
  circos.link(link[[1]], c(0, link[[3]]), link[[2]], c(0, link[[3]]), col = '#00000025', border = NA)
}

# "Patient/cell" labels
for(s in sectors) {
  highlight.sector(
    sector.index = s, track.index = 1, col = colours[s],
    text = s, text.vjust = -1, niceFacing = TRUE)
}

circos.clear()

Edit: Just adding the link from removed comment: See this answer for a nice example of labelling!

A: @m-dz provides a correct direction. I can provide more details regarding to your simulated data.
Let's start from here:
patients <- c(rep("patient1",20), rep("patient2",10))
cell.types <- c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4))
features <- c(paste("feature",1:12,sep="_"), paste("feature",9:16,sep="_"), paste("feature",c(1,2,9,10,17,18),sep="_"), paste("feature",c(1,18,19,20),sep="_"))
dat <- data.frame(patient=patients, cell.type=cell.types, feature=features)
dat <- with(dat, table(paste(patient,cell.type,sep='|'), feature))

as.data.frame converts dat to a three-column data frame (i.e. an adjacency list where links start from the first column and point to the second column)
dat = as.data.frame(dat, stringsAsFactors = FALSE)

Generate colors for patients/cells and features.
features = unique(dat[[2]])
features_col = structure(rand_color(length(features)), names = features)
patients_col = structure(2:5, names = unique(dat[[1]]))

If a feature only exists in one patient/cell combination, you don't want to
show it but still want to keep its position in the plot, you can just set
#FFFFFF00 as its color (a white color with full transparency so that it will
not cover other links). Here we want the link color to be same as the feature sectors.
col = ifelse(dat[[3]], features_col[dat[[2]]], "#FFFFFF00")
col = gsub("FF$", "80", col) # half transparent
features_count = tapply(dat[[3]], dat[[2]], sum)
# set color to white if it only exists in one patient/cell
col[features_count[dat[[2]]] == 1] = "#FFFFFF00"

And the final chord diagram:
chordDiagram(dat, col = col, grid.col = c(features_col, patients_col))

You can see in the feature sectors there are at least two links pointing to
patients/cells.

A: get data prepared
    library(circlize)
    patients <- c(rep("patient1",20), rep("patient2",10))
    cell.types <- c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4))
    features <- c(paste("feature",1:12,sep="_"), paste("feature",9:16,sep="_"),     paste("feature",c(1,2,9,10,17,18),sep="_"), paste("feature",c(1,18,19,20),sep="_"))
    dat <- data.frame(patient=patients, cell.type=cell.types, feature=features)
    dat <- with(dat, table(paste(patient,cell.type,sep='|'), feature))
    dat<-as.data.frame(dat,stringsAsFactors = FALSE)

get all combination of patient and celltypes
    df=NULL
    for(i in levels(as.factor(dat$feature))){
        temp<-as.data.frame(matrix(combn(dat[which(dat$feature==i),1],2),byrow = TRUE,ncol=2),stringsAsFactors = FALSE)
        temp$feature=i
        temp$Freq=1
        Freq_0<-subset(dat$Var1,dat$feature==i & dat$Freq==0)
        for(j in Freq_0){
          temp$Freq[temp$V1==j | temp$V2==j]=0
        }
        df<-rbind(df,temp)
    }

add color
    df$color=rainbow(dim(df)[1])
    df[which(df$Freq==0),5]="white"
    df$Freq=1
    chordDiagram(df[,c(-3,-5)], transparency = 0.5,col = df$color)

different link means different feature,and the link color is white where 'Freq' is 0

I turn the color 'white' into 'black' while black is more conspicuous

If you want to left behind the 'feature' attribute......
let's get data prepared first
    library(circlize)
    patients <- c(rep("patient1",20), rep("patient2",10))
    cell.types <- c(rep("cell1",12), rep("cell2",8),rep("cell1",6), rep("cell2",4))
    features <- c(paste("feature",1:12,sep="_"), paste("feature",9:16,sep="_"), paste("feature",c(1,2,9,10,17,18),sep="_"), paste("feature",c(1,18,19,20),sep="_"))
    dat <- data.frame(patient=patients, cell.type=cell.types, feature=features)
    dat <- with(dat, table(paste(patient,cell.type,sep='|'), feature))
    dat<-as.data.frame(dat,stringsAsFactors = FALSE)
    df=NULL
    for(i in levels(as.factor(dat$feature))){
      temp<-as.data.frame(matrix(combn(dat[which(dat$feature==i),1],2),byrow = TRUE,ncol=2),stringsAsFactors = FALSE)
      temp$feature=i
      temp$Freq=1
      Freq_0<-subset(dat$Var1,dat$feature==i & dat$Freq==0)
      for(j in Freq_0){
        temp$Freq[temp$V1==j | temp$V2==j]=0
      }
      df<-rbind(df,temp)
    }

processed it
    library(dplyr)
    df1<-subset(df,df$Freq==1)
    df0<-subset(df,df$Freq==0)
    df1_mod<-summarise(group_by(df1,V1,V2),Freq=n())
    df0_mod<-summarise(group_by(df0,V1,V2),Freq=n())

add color
    df1_mod$color<-rainbow(5)
    df0_mod$color<-"white"
    df_res<-rbind(df0_mod,df1_mod)

draw it
chordDiagram(df_res, transparency = 0.5,col = df_res$color)

These picture shows there are many zeros in the 'Freq'.


text:
Q: FileName in OpenFileDialog appears empty I have two radio buttons and a regular button - button2.
I've created an if else statement that checks which of the radio buttons is clicked and accordingly preforms a given task. In particular, if:

*

*Radio button 1 is clicked: Ask's to select one pdf file, opens a axAcroPDF1 connection and outputs the OpenFileDialog FileName into a textbox

*Radio button 2 is clicked: Something else

*No radio button is clicked: Sends a messege.. select a file.

This is my attempt:
    {

        if (radioButton1.Checked == true)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "PDF|*pdf";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.Show();
                axAcroPDF1.src = ofd.FileName;
            }

            textBox1.Text = ofd.FileName;

            MessageBox.Show(ofd.FileName);
        }

        else if (radioButton2.Checked == true)
        {
            OpenFileDialog ofd3 = new OpenFileDialog();
            ofd3.Filter = "PDF|*pdf";
            textBox1.Text = ofd3.InitialDirectory + ofd3.FileName;

            if (ofd3.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.Show();
            }
        }

        else if (radioButton2.Checked == false & radioButton1.Checked == false)
        {
            MessageBox.Show("Please select a processing option");
        }

        else
        {
            MessageBox.Show("Error.");
        }

    }

The issue is that I can't extract the FileName string in:  textBox1.Text = ofd.FileName;
Basically, this returns an empty string. I'm not sure how this is possible, when in fact the  axAcroPDF1.src successfully opens the selected pdf.
Any ideas?

A: It is the ofd.ShowDialog() method which populates the ofd.FileName property.
Following the logic of your code:
For checkbox 1, you do the right thing to check the appropriate return of ofd.ShowDialog() before you access your axAcroPDF1 but there is no check that the user selected a file before you display the name in the checkbox.
For the checkbox 2 scenario, you are trying to access the ofd3.FileName before it is set by running the ofd3.ShowDialog() method.
The crucial point here is that ofd3.ShowDialog() is the point in your code where the dialog pops for the user.
You will want to move all of your calls to ofd.FileName and ofd3.FileName inside their respective if checks on the dialog.

A: //Try this one
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axAcroPDF1.src = ofd.FileName;
                axAcroPDF1.Show();
                textBox1.Text = ofd.FileName;
            }


text:
Q: How to identify a google home (mini) device? I want to identify a google home device via the SDK request / response call to serve the request properly. Basically I need this information to know the location / room / floor / venue where this device is installed or kept.
Example: If I make a request to google mini - "Switch off the lights", I want to know the device id so the service can do a lookup and find the room where this device is located and switch off the lights of that room.
I don't need this for android phones/devices. It is very specific to google home devices.
I have seen originalRequest.data.user.userId but not sure if i can use this (as user of the device will not have any google login or account linking)
Is this information is exposed via dialogflow api?

A: The Google Home device information, including its ID and room assignment, are not available to developers.
This is why the Google Home Smart Home API handles most of this for you. It reports exactly which lights are being controlled - you do not need to know which device did the controlling, the Smart Home API tells you exactly which devices are being controlled.
You do not need to use Dialogflow in these cases, since the Assistant does all the Natural Language Processing and simply gives you directions for which devices need to be updated.


text:
Q: CSS based 50% Transparent border without using transparent image I need to make the border of fancy box transparent after i have made some modifications to it. For some reason i cant make it work with transparent.
I have create a sample example which is somewhat & i want to make the borders of the inner DIV transparent. i tried few thing but did not work. I would appreciate a pure CSS solution without using any transparent images
Example: JSFiddle
Is their a way we can add Opacity to border

A: Just use color as transparent like this for making it fully transparent
border:10px solid transparent;

My fiddle
And if you want to add opacity, than this approach of your's is correct, it does make the border opaque
border-color:rgba(17,17,17,0.7);

You can use this too border-color:rgba(244,244,244,0.4); My fiddle


text:
Q: Grouping Consecutive Rows in DB2 I have a table in DB2 that looks like the following:-
ID        DESCRIPTION        TYPE    AMOUNT
--        -----------        ----    ------
1         Item 1             ONE     100
2         Item 2             ONE     50
3         Item 3             TWO     100
4         Item 4             TWO     50
5         Item 5             ONE     100
6         Item 6             TWO     50
7         Item 7             ONE     100
8         Item 8             TWO     50
9         Item 9             TWO     100
10        Item 10            ONE     50

I want to group consecutive rows with the same type so it looks like the following:-
TYPE    AMOUNT
----    ------
ONE        150            -- (ID 1,2)
TWO        150            -- (ID 3,4)
ONE        100            -- (ID 5)
TWO        50             -- (ID 6)
ONE        100            -- (ID 7)
TWO        150            -- (ID 8,9)
ONE        50             -- (ID 10)

Note the last column is just to denote which Id's are in the rollup.
I'd rather do this with a query than a Stored Procedure.

A: Unless I miss my guess, this can be trivially done with a double-ROW_NUMBER() constant expression:
SELECT type, SUM(amount) AS amount
FROM (SELECT type, amount, id,
             ROW_NUMBER() OVER(ORDER BY id)
                          - ROW_NUMBER() OVER(PARTITION BY type ORDER BY id) AS groupId
      FROM tbl) grouped
GROUP BY groupId, type
ORDER BY groupId, MIN(id)

SQL Fiddle Example
(Thanks to Brian for the initial fiddle setup)
...which yields the desired results.  Note that MIN(id) is required to ensure a consistent sort order - groupId is not universally unique, so otherwise some ONE or TWO rows can end up flipped.
As a side note, I dislike ordering on an id column, as the only thing such an id is really good for is uniqueness.  This is especially true in cases where rows may be updated or otherwise reinterpreted - do you have something like an insertedAt timestamp you could use for ordering instead?

A: Think I got it:
Fiddle:
with sub1 as
 (select x.*,
         case when chk is not null
              then row_number() over(order by id)
              else null
              end as rn
    from (select id,
                 description,
                 type,
                 amount,
                 case when lag(type, 1) over(order by id) <> type
                      then 'X'
                      else null
                      end as chk
            from tbl
           order by id) x)
select min(type),
       sum(amount) as amount,
       listagg(id, ', ') within group(order by id) as ids
  from (select z.id, z.description, z.type, z.amount, y.rn
          from sub1 z
         cross join sub1 y
         where z.rn is null
           and y.rn = (select max(x.rn)
                         from sub1 x
                        where x.id < z.id
                          and x.rn is not null)
        union all
        select id, description, type, amount, rn
          from sub1
         where rn is not null
        union all
        select id, description, type, amount, 1
          from sub1
         where id < (select min(id) from sub1 where rn is not null)
         order by id) x
 group by rn
 order by rn

I tested it in Oracle but it just relies on the with clause and window functions which I believe DB2 has so it should work, if anything with minor modifications.


text:
Q: install mlpy 3.5.0 on mac 10.9 error.Please help me The following is the error which I am getting. Please help me to fix it.
apple:mlpy-3.5.0 apple$ python setup.py install
running install
running build
running build_py
running build_ext
building 'mlpy.gsl' extension
cc -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -arch x86_64 -arch i386 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c mlpy/gsl/gsl.c -o build/temp.macosx-10.9-intel-2.7/mlpy/gsl/gsl.o
mlpy/gsl/gsl.c:223:10: fatal error: 'gsl/gsl_sf.h' file not found
#include "gsl/gsl_sf.h"
         ^
1 error generated.

A: MLPy depends on GNU Scientific Library (GSL), which you need to install first.
You can install it either with brew install gsl or manually from source.
For manual installation, instructions can be found here. The relevant steps are as follows:

*

*go to: http://www.gnu.org/prep/ftp.html

*click on an ftp link close to your location

*find the gsl/ directory and click on it

*find the gsl-VERSION.tar.gz file, where version is 1.14 or greater. Click on that file to download it.

*In a terminal window extract the tar.gz file using tar -xzf gsl-VERSION.tar.gz and then cd to the ./gsl-VERSION directory

*Look at the INSTALL file. It will probably tell you to run ./configure, then make, and then make install (and you might have to
  login as the superuser (sudo)

A: I am actually getting the same issue today while installing mlpy. Based on the mlpy documentation. Here is the method to solve this issue.
According to the installation section in the mlpy documentation:

If the GSL header files or shared library are in non-standard locations on your system, use the --include-dirs
  and --rpath options to build_ext:
$ python setup.py build_ext --include-dirs=/path/to/header --rpath=/path/to/lib
$ python setup.py install

We have to assign the header and lib. Based on How to obtain and install GSL,

Under Search Paths/Header Search Paths type /opt/local/include
Under Search Paths/Library Search Paths type /opt/local/lib

The quick answer is running the below command:

sudo python setup.py build_ext --include-dirs=/opt/local/include --rpath=/opt/local/lib
sudo python setup.py install

Hope this will be helpful.


text:
Q: Geocode address to county in R I have a list of street addresses I would like to geocode to county. I am working in R. Simplified example follows. Unfortunately, due to the new Google API terms of service, you will need to have your own API key to run my code--it should not be shared, so please do not include it in your solution code.
I suspect this is a formatting issue but I am too new to R to know the solution.
library(tidyverse)
library(ggmap)

register_google(key = <YOUR GOOGLE KEY>)

ltr <- letters %>% head(5)
adr <- c('110 State St, Albany, NY' ,
           '100 State Cir, Annapolis, MD' ,
           '206 Washington St SW, Atlanta, GA' ,
           '210 State St, Augusta, ME' ,
           '1100 Congress Ave, Austin, TX')

rawAdr <- data.frame(ltr , adr)

# the following only retrieves latitude and longitude
latlonAdr <- geocode(location = rawAdr$adr) %>%
  bind_cols(rawAdr , .)

# the following retrieves county (among much other information),
# but it is formatted in a way that is
# impossible to use. For instance, county a is in variable long_name...17,
# but the same name is repeated for all addresses. The county for address b is given in
# long_name...64, again the same name for all addresses.

geoAdr <- geocode(location = rawAdr$adr , output = 'all') %>%
  bind_cols(rawAdr , . )

I would like to have a file that lists ltr, adr and (correct) county. Thanks for your any help! (Apologies, I will not be able to look at answers for a couple of hours.)

A: The return value from the geocode function is a long nested list, you need to drill through the list to find the field of interest.
Here is a solution which bypasses the ggmap package and returns a JSON response, this is slightly easier to parse:
library(magrittr)

ltr <- letters %>% head(5)
adr <- c('110 State St, Albany, NY' ,
         '100 State Cir, Annapolis, MD' ,
         '206 Washington St SW, Atlanta, GA' ,
         '210 State St, Augusta, ME' ,
         '1100 Congress Ave, Austin, TX')
rawAdr <- data.frame(ltr , adr)

#replace spaces with + for a valid web address
adrs <-gsub(" ", "+", adr)
#add the key here to the http address
urls <-paste("https://maps.googleapis.com/maps/api/geocode/json?","address=",adrs,"&key=***keyGoesHere***",sep="")

#query the API, and search for the row that contains the word County and return that value
counties <- sapply(urls, function(url) {
   print(url)
   rgc <- jsonlite::fromJSON(url)
   county <-rgc$results$address_components[[1]]$long_name[grep("County", rgc$results$address_components[[1]]$long_name)]
   county
})
rawAdr$County <- counties
rawAdr


text:
Q: Insert an image on mouseclick location I need to insert an image wherever the user clicks on a specified element (another image), and for it to sit in front of that image. Can this be done in javascript? If not, with what?
Thanks

A: You should post your html/structure too but you can go about something like this:
var el = document.getElementById('image_id');
var img = document.getElementById('image_id2');
var container = document.getElementById('container_id');

el.onclick = function(){
  container.appendChild(img);
};

A: unless you're set on not using any external libraries, I would take a look at jQuery, which can make your life a whole lot easier for this kind of stuff

A: Sure, the basic flow would be to add an event listener to the onclick event. That event listener would then append the image to some container div.
The key point is the CSS for your images. Make sure that you're absolutely positioning your images and would be a good idea to use an incrementing z-index. You can capture the position values from the onclick event (for all the different values, see: http://www.quirksmode.org/js/events_properties.html#position). You would set these CSS values when you insert the image in javascript.

A: It should be possible. I personally use JQuery which makes these things pretty easy:
http://jquery.com
This example should give you an idea of how you would accomplish this:

        <title>My Page></title>

A: Make sure you have the image in the img src location specified...


text:
Q: Подскажите в чем синтаксическая ошибка? Есть код, на котором браузер выдает ошибку (LINE 221):
$query = "INSERT INTO active (
    inv_n, name_act, id_cat, ed_izm, quantity, price, id_dep, comments, id_stat)
VALUES (
    '".$inv_n."','".$name_act."','".$id_cat"','".$ed_izm"','".$quantity"',
    '".$price"','".$ed_dep"','".$comments"','".$id_stat"');";

Сама ошибка выглядит вот так:

Parse error: syntax error, unexpected '"','"' (T_CONSTANT_ENCAPSED_STRING) in E:\OpenServer\OSPanel\domains\uchet\active.php on line 221

A: $query = "INSERT INTO tbl_name(id,name) VALUES('$id','$name')";


text:
Q: import python modules directly from raw git tree I have the following directory directly in a git tree that I'd like to reference by adding its base directory to PYTHONPATH without needing to package and install the modules.
Once added to PYTHONPATH, if the inner cstruct dir was pulled out one level then since it has a init.py file, it's trivial to just do an
import cstruct

however, since I'm also keeping the setup files, it needs to be nested another level which makes importing like above not work.
Is there any way to get around this?  I was thinking about constructing some init.py in the base dir that could "pull" the inner cstruct out or somehow add the outermost cstruct to the python path but I'm not sure how to go about it.
For clarity, I'm using cstruct here as an example that I pulled from github however I have a half-dozen such libs that I'd really like to just reference ad-hoc in my dev environment without needing to package + install.
.
├── cstruct
│   ├── cstruct
│   │   ├── examples
│   │   │   ├── fdisk.py
│   │   │   └── __init__.py
│   │   ├── __init__.py
│   │   └── tests
│   │       ├── __init__.py
│   │       └── test_cstruct.py
│   ├── LICENSE
│   ├── MANIFEST.in
│   ├── mbr
│   ├── README.md
│   ├── setup.cfg
│   └── setup.py

A: I don't know why you don't install this in a virtualenv, but given your specific question, why can you not simply do what you initially propose and add the outer directory to the PYTHONPATH?
You can either do that from the shell:
export PYTHONPATH=$PYTHONPATH:/path/to/outer/cstruct

or from inside Python:
import sys
sys.path.insert(0, '/path/to/outer/cstruct')


text:
Q: Default Order of Case Statement, for use in SSRS I'm building a report in SSRS. I have values from a DB column populating the row headings in a matrix in the report. These are display fine. The problem is that they display alphabetically and i don't know how to have them display in an order i have defined.
The SQL query looks like:
 CASE
   WHEN Age >= 0 AND Age <3 THEN 'Newborn 0-3 Months'
   WHEN Age > 3 AND Age <= 12 THEN 'Infant 3-12 Months'
   When Age > 12 THEN 'Child'
   ELSE 'Invalid Age'
 END AS AgeGroup

Which works. But in my report it displays the columns so 'Child' displays before 'Infant' and so on.
Is there a way i can define the order? Thanks in advance

A: You have to add a second case statement to use in the ordering:
CASE
   WHEN Age >= 0 AND Age <3 THEN 10
   WHEN Age > 3 AND Age <= 12 THEN 20
   When Age > 12 THEN 30
   ELSE 40 -- or 0, perhaps
END AS AgeGroupOrder


text:
Q: mvc3 areas have hostname I am looking to create a MVC3 website.  We need at least two areas but we need different url's for each of the areas. Like this:

domain.com/ goes to /
admin.domain.com/ goes to /areas/admin
anotherSite.com/ goes to /areas/portal

After doing some research I have found Lucero's link that you can use HostNameContraint as follows:
public class HostNameContraint : IRouteConstraint
{
    protected string _hostname;

    public HostNameContraint(string hostname)
    {
        _hostname = hostname;
    }

    bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (httpContext.Request.Url.Host == _hostname)
            return true;
        return false;
    }
}

and then register the constraints like this:
routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { hostname = new HostNameContraint("domain.com") },
            new[] { "MVCProject.Controllers" }
        );

        routes.MapRoute(
            "Admin_Default2", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { hostname = new HostNameContraint("admin.domain.com") },
            new[] { "MVCProject.Controllers.Areas.Admin.Controllers" }
        );

        routes.MapRoute(
            "Portal_Default2", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { area = "Portal", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { hostname = new HostNameContraint("anotherSite.com") },
            new[] { "MVCProject.Controllers.Areas.Portal.Controllers" }
        );

I have IIS setup so that they point to the root folder of the application for each of the sites.  Pointing to the root "Domain.com" works fine but going to either "Admin.domain.com" or "Domain.com/admin/" comes up with a 404 "Resource cannot be found."
Update
I have tried it both with the Area name at the beginning of the url and without.

"Portal/{controller}/{action}/{id}"

The issue is that when the "Portal" area is in the route, the signature does not match the name as "anotherSite.com" and therefore it comes back and says 403.14 - Forbidden.  Cannot list contents of this directory.  It is also important to note that the constructor for HostNameConstraint is never called when the "Portal" area is url parameter.

A: In order to indicate distinguish the URL as going to an area, the area name needs to be part of the URL.  Otherwise, the area will not be parseable from the URL and you will fall back to the default routing.  Also, it is a good idea to put your default route last - to ensure all other route mappings are tested
Note the addition of "Admin/" and "Portal/" in the corresponding MapRoute call:
    routes.MapRoute(
        "Admin_Default2", // Route name
        "Admin/{controller}/{action}/{id}", // URL with parameters
        new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        new { hostname = new HostNameContraint("admin.domain.com") },
        new[] { "MVCProject.Controllers.Areas.Admin.Controllers" }
    );

    routes.MapRoute(
        "Portal_Default2", // Route name
        "Portal/{controller}/{action}/{id}", // URL with parameters
        new { area = "Portal", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        new { hostname = new HostNameContraint("anotherSite.com") },
        new[] { "MVCProject.Controllers.Areas.Portal.Controllers" }
    );

routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        new { hostname = new HostNameContraint("domain.com") },
        new[] { "MVCProject.Controllers" }
    );


text:
Q: NSDateFormatter: stringFromDate and dateFromString not reversible? I'm having problems using a custom date formatter with NSDateFormatter to convert a string into a date. Here's a short example that creates a string from today's date but fails to convert this back to an NSDate:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"Mdyyyy"];
NSString *example = [dateFormatter stringFromDate:now];    // e.g., 10292013
NSDate *reverse = [dateFormatter dateFromString:example];  // nil?

So basically it seems that NSDateFormatter is creating a date string that it itself can't turn back into a NSDate using the same format that created the string.
Using MMddyyyy as the date string works, although I can't see from the documentation (which conveniently only goes up to iOS 6.0) why it would matter:
month   M   1..2    09  Month - Use one or two for the numerical month, ....
...
day d   1..2    1   Date - Day of the month

The reason why I'm trying to use Mdyyyy instead of MMddyyyy is because it's closer to what NSDateFormatterShortStyle returns for my current NSLocale (M/d/yy).
Perhaps someone might have some insight here as two what I'm doing wrong, or if I'm wrong in my understanding of how this should work. (I know there are a lot of questions here regarding NSDateFormatter, but I didn't find one that fits my problem.)

A: Mdyyyy is ambiguous as a string ->date mapping. One cannot tell if "1112013" is Jan 11 or November 1. Hence NSDateFormatter will not allow it for string ->date.


text: Q: Which parameters should I consider to choose safety capacitor? I know the X and Y capacitors, how they are connected and why they are used but I am not sure about selection criteria and how they are exactly affecting the signal. I would appreciate with some help and explanation.


text:
Q: How can I convert a string slugify in the equivalent in human I want transform a string that it is slugified in another string that it is the equivalent in human readable?
I take the parametesr from an url:
bookmark/10/disco%20asdasd

So I have the nome that is "disco%20asdasd". But in this way it not confrontable so I need to convert "disco%20asdasd" in "disco asdasd" that is the operation opposite to slugify. Anyone can help me?

A: It would really help if you showed an example of a string that you want to convert and an example of a string that you want to convert it to. Without that I can only recommend you some general solutions. See:

*

*https://www.npmjs.com/package/slug

*https://www.npmjs.com/package/slugify

*https://www.npmjs.com/package/slugg

*https://www.npmjs.com/package/clean-up-string

*https://www.npmjs.com/package/speakingurl

*https://www.npmjs.com/package/sluggin

*https://www.npmjs.com/package/simple-slug

*https://www.npmjs.com/browse/keyword/slug
See the code examples in the docs of those projects.
Update
If you want to convert: disco%20asdasd to: disco asdasd then use:
let decoded = decodeURI(yourString);

or:
let decoded = decodeURIComponent(yourString);

but this is not a slug - this is URI-encoding and decoding.
See:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent
More info on Wikipedia:

*

*https://en.wikipedia.org/wiki/Percent-encoding