text:
Q: Simple jquery/javascript dropdown menu with 2 outputs (1 img, 1 title) Please forgive me I'm self-taught with large pockets of knowledge missing ><
I found some code (probably from you guys here at Stockoverflow!) and managed to get it to work in my site. There is only 1 change I need to make to my jquery but it's not working when I do it.
This is the unchanged version
(the dropdown list is what I am working on)
HTML

Title of Artwork

        <select name="printchoice" id="printchoice">
            <option data-tname="Select" value="art_images/anime_art_prints/p000a.png">Please Select your Print</option>
            <option data-tname="Selected One" value="art_images/anime_art_prints/p000b.png">A Sassy Catgirl</option>
            <option data-tname="Selected Two" value="art_images/anime_art_prints/p000c.png">Mermaid Friends</option>
            <option data-tname="Selected Three" value="art_images/anime_art_prints/p000d.png">Galaxy Girl</option>
        </select>

JS
$(document).ready(function(){

    $("#printchoice").change(function(){
        $("img[name=image-swap]").attr("src",$(this).val());
    });

    $("#printchoice").change(function(){
        $("span[name=title-swap]").html($(this).val());
    });
});

This works how I want it, but it puts the text of the option's value="" into the title span. I want the options data-tname="" text to show instead. I tried to replace val() with data('tname') in the second paragraph to no avail. that just seems to break it :(
If it isn't too much of your time, could you take a quick look and see if it is something super simple that I need to change that can make it work how I need it to?

A: $("#printchoice").change(function(){
    $("img[name=image-swap]").attr("src",$(this).val());

    $("span[name=title-swap]").html($(this).find('option:selected').attr('data-tname'));
});


text:
Q: Unit test Timeout in C# I have a Function doSomething() which should work in a specific Time (15 seconds). If Time is out then i should throw a message that says "Timeout" but i will still waiting for the result.
so i solve that with a task:
Task<A> mytask = Task.Factory.StartNew(() => ClassA.doSomething()) ;
Mytask.wait(15);
If(mytask.isCompleted)
{
    result= mytask.Result ;
}
else
{
    Debug(' Time is out ') ;
               Mytask.wait() ;
               result= mytask.Result ;
}

my Question is : how i can unit test the senario of getting Timeout
my Try :
ClassA  objectA= new ClassA() ;
Clocktime t.start() ;
Expect.Call(objectA.doSomething()) ;
t.end
Assert.isTrue(T > 15) ;
Mocks.verifyAll() ;

A: Disclaimer: Even though the scenario in the question does not follow best practices, it is still useful to demonstrate how to use TaskCompletionSource for testing task-related code.
Below is an example of how you can test the second branch - the "timeout" branch in your code using TaskCompletionSource
Do:

*

*Prefer async code over sync - not to block the threads (of course, it depends)

*Don't block on async threads

*Use parameters and named constants instead of "magic values"

*Keep your unit tests fast and focused on a single scenario

*Avoid testing built-in functionality, like Wait timeout

*Implement cooperative cancellation https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation

*Use proper instrumentation - logging long running task is just an example, in PROD use ETW - https://learn.microsoft.com/en-us/windows/win32/etw/event-tracing-portal
I have modified your code a bit, to align to these recommendations.
I hope it's clear, if not - please let me know how I can help :-)
    // This is the class that does the "long running work"
public class ClassA<T>
{
    public async Task<T> doSomething(CancellationToken cancellationToken)
    {
        const int magicNumberOfIterations = 100;
        var magicLengthOfTimeInSeconds = TimeSpan.FromSeconds(1);
        for (int i = 0; i < magicNumberOfIterations; i++)
        {
            if (cancellationToken.IsCancellationRequested)
                cancellationToken.ThrowIfCancellationRequested();

            await Task.Delay(magicLengthOfTimeInSeconds); // time - consuming work
        }

        return default;
    }
}

// This is the class that "detects" long running work based on timeout
public class SlowTaskLogger<T> {

    // Don't use this in prod - this actually blocks a thread to write a metric
    // Use ETW instead - https://learn.microsoft.com/en-us/windows/win32/etw/event-tracing-portal
    public Task<T> RunAndLogSlowRunningTask(TimeSpan logAfterTimeout, Task<T> task)
    {
        if (task.Wait(logAfterTimeout)) // DO NOT use in PROD
            return task; // don't block on async threads
        LogWarningForLongRunningTask(task);
        return task;
    }

    private void LogWarningForLongRunningTask(Task<T> task)
    {
        longRunningTasks.Add(task); // TODO: logging
    }

    private List<Task<T>> longRunningTasks = new(); // NOTE: for testing, replace with partial mock

    public IReadOnlyCollection<Task<T>> LongRunningTasks => longRunningTasks;
}

The test could look something like this
    public class InterviewTaskTests
{
    private SlowTaskLogger<string> slowTaskLogger = new();

    [Fact]
    public async Task LogSlowRunningTaskTest()
    {
        var timeout = TimeSpan.FromMilliseconds(15);
        var completionSource = new TaskCompletionSource<string>();
        var expectedResult = "foo";
        var taskWithLogging = slowTaskLogger.RunAndLogSlowRunningTask(timeout, completionSource.Task);

        await Task.Delay(timeout);

        // check that timeout method was called
        // you can use partial mocks instead of private state for production code
        Assert.Contains(taskWithLogging, slowTaskLogger.LongRunningTasks);

        // complete the task and ensure proper result is returned
        completionSource.SetResult(expectedResult);
        var actualResult = await taskWithLogging;
        Assert.Equal(expectedResult, actualResult);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opera User-JS: how do I get the raw server response? I'm writing some user-JS for Opera. It reacts on a request that doesn't have an extension, e.g. /stuff/code/MyFile, or has one not related to JavaScript, e.g. /stuff/code/load.do. The content-type of the response is set to text/html, even though it returns pure JavaScript source (text/javascript). As I don't have access to the server code I simply have to live with this.
The problem now is that I want to format the source with line numbers and such and display it inside Opera. Therefore, I wrote some user-JS to react on AfterEvent.DOMContentLoaded (also tried AfterEvent.load, same thing). It reads e.event.target.body.innerHTML to gain access to the body, i.e. the JavaScript-code.
That alone would work nicely, if only the source wouldn't contain HTML-tags or comparison operators (<, >). Since it does, I never get the output I want. Opera seems to have some internal logic to convert the text/html-response into its own representation format. This includes that e.g. a CRLF after a HTML-tag is removed or code between two "matching" < and > (comparison operators!) are crunched together into one single line applying ="" after each word in there.
And that's where the problem is.
If I request the same URL without my user-JS and then look at the source of the "page" I see a clean JavaScript-code identical to what the server sent out. And this is what I want to get access to.
If I use innerText instead of innerHTML, Opera strips out the HTML-tags making the file different to the original, too.
I also tried to look at outerHTML, outerText and textContent, but they all have the same problems.
I know that Opera doesn't do anything wrong here. The server says it's a text/html and Opera simply does what it usually does with a text/html-kind of response.
Therefore, my question is: is there any way to get the untouched response with a user-JS?

A: There isn't any way to access the pre-parsed markup from JS. The only way to do that would be to use XMLHttpRequest to request the content yourself.


text:
Q: Woocommerce shop manager role, hide woocommerce menu I am using a wordpress theme which supports woocommerce,
when adding a user with shop manager role i don't want to show the woocommerce menu.
Just need the products menu only.
please help.

A: You can use WordPress's 'remove_menus()' function to do this.
Store Managers have a capability: 'manage_woocommerce'
You can see that they are allowed to see the WooCommerce admin menu here:
'/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-menus.php'
Look for: $main_page = add_menu_page( __( 'WooCommerce', 'woocommerce' ), __( 'WooCommerce', 'woocommerce' ), 'manage_woocommerce', 'woocommerce' , array( $this, 'settings_page' ), null, '55.5' );
So much for the theory. To stop this admin menu item from displaying for anyone but an Administrator, add this to your functions.php file or plugin:
add_action( 'admin_menu', 'remove_menus' );
function remove_menus(){

    // If the current user is not an admin
    if ( !current_user_can('manage_options') ) {

        remove_menu_page( 'woocommerce' ); // WooCommerce admin menu slug

    }
}

A: Don't have the rep points to add a comment, but needs to change the hooked action from:
add_action( 'admin_menu', 'remove_menus' );

to:
add_action( 'admin_init', 'remove_menus' );

and then you can do something like:
function remove_menus(){

    // If the current user is not an admin
    if ( !current_user_can('manage_options') ) {

        remove_submenu_page('woocommerce', 'wc-status');

    }
}

if you are trying to remove core woocommerce submenu items.
(responding to Do Xuan Nguyen's comment)


text:
Q: what is the difference between version 1.0 and version 3.2 in corda List out differences between 1.0 and 3.2 version in corda .how to upgrade corda from version 1.0 to 3.2 using intellij

A: Please check out the documentation:
Release notes: https://docs.corda.net/release-notes.html
Upgrade Notes: https://docs.corda.net/upgrade-notes.html


text:
Q: Serialization pattern for models and DTO's I have some Models which I want to make serializable to use them for a rest-service.
Currently, our implementation is very elaborate. The output can differ from ApiController to ApiController. I'm not able to clear or remove the Enumerable of the Model. This should be controlled by the DTO's.
I saw lots of comments that DTO's are outdated. However, I think the idea of decoupling between model and presentation is very good.
At the moment this would lead to lots of objects which I want to reduce.
I found only a few design pattern recommendations like memento, but not sure if this is correct. I also found an advice to use Mixins but not sure yet if it helps to solve my problem.
I'm sure there are lots of best practices which I don't see because I just search for the wrong terms.
Following only some pseudo-code to clarify what I mean.
public class PersonEntity
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string Details { get; set; }

    public List<string> LotsOfSubInformation { get; set; }
}

[Serializable]
public class PersonWithoutSubDtoXml
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "Age")]
    public int Age { get; set; }

    [XmlElement(ElementName = "Details")]
    public XmlCDataSection Details { get; set; }
}

[Serializable]
public class PersonDtoXml
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "Age")]
    public int Age { get; set; }

    [XmlElement(ElementName = "Details")]
    public XmlCDataSection Details { get; set; }

    [XmlArray("LotsOfSubInformation")]
    [XmlArrayItem("Information")]
    public string[] LotsOfSubInformation { get; set; }
}

[Serializable]
public class PersonDtoJson
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public int Age { get; set; }

    [JsonProperty("details")]
    public string Details { get; set; }

    [JsonProperty("lotsOfSubInformation")]
    public string[] LotsOfSubInformation { get; set; }

    public static PersonDtoJson Create(PersonEntity source)
    {
        return new PersonDtoJson
        {
            Age = source.Age,
            Details = source.Details,
            Name = source.Name,
            LotsOfSubInformation = source.LotsOfSubInformation.ToArray()
        };
    }
}

[Serializable]
public class PersonWithoutSubDtoJson
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public int Age { get; set; }

    [JsonProperty("details")]
    public string Details { get; set; }

    public static PersonWithoutSubDtoJson Create(PersonEntity source)
    {
        return new PersonWithoutSubDtoJson
                                      {
                                          Age = source.Age,
                                          Details = source.Details,
                                          Name = source.Name
                                      };
    }
}


text:
Q: Sprite Not Drawn in Pygame I'm new to Pygame and I don't understand why the sprite isn't being drawn on the screen. Can someone show me how or what I'm doing wrong?
Here's my code:
import pygame

pygame.display.set_caption('Platformer')

screen = pygame.display.set_mode((603, 480))

WHITE = (255, 255, 255)
x = "1"
y = "1"

loop = True
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = False

def Player(Sprite):
    image=("Player.png")
    def __init__(self, image,  groups):
        pygame.update

screen.fill (WHITE)
Player(x, y)

pygame.quit()
quit()

A: Why the x and y is string???
You are saying a position like a word. The type of pos must be int or float.
x = 1
y = 1


text:
Q: Annotation JMS\SecurityExtraBundle\JMSSecurityExtraBundle doesnt work? I'm tring to secure my application (SF 2.3.7) with Annotation (JMS\SecurityExtraBundle\JMSSecurityExtraBundle). But it does not work. I can access to addAction when i'm offline.
My app/config/security.yml
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
            logout:       true
            anonymous:    true
            remember_me:
                key: %secret%

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

My composer
"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.3.*",
    "doctrine/orm": ">=2.2.3,<2.4-dev",
    "doctrine/doctrine-bundle": "1.2.*",
    "twig/extensions": "1.0.*",
    "symfony/assetic-bundle": "2.3.*",
    "symfony/swiftmailer-bundle": "2.3.*",
    "symfony/monolog-bundle": "2.3.*",
    "sensio/distribution-bundle": "2.3.*",
    "sensio/framework-extra-bundle": "2.3.*",
    "sensio/generator-bundle": "2.3.*",
    "incenteev/composer-parameter-handler": "~2.0",
    "jms/security-extra-bundle": "dev-master",
    "stof/doctrine-extensions-bundle": "dev-master",
    "friendsofsymfony/user-bundle": "~2.0@dev"
}

My AppKernel
$bundles = array(
    new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
    new Symfony\Bundle\SecurityBundle\SecurityBundle(),
    new Symfony\Bundle\TwigBundle\TwigBundle(),
    new Symfony\Bundle\MonologBundle\MonologBundle(),
    new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
    new Symfony\Bundle\AsseticBundle\AsseticBundle(),
    new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
    new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

    new JMS\AopBundle\JMSAopBundle(),
    new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
    new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
    new FOS\UserBundle\FOSUserBundle(),

    new Intranet\UserBundle\IntranetUserBundle(),
    new Intranet\IntranetBundle\IntranetIntranetBundle(),
);

My Controller

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Intranet\IntranetBundle\Entity\Client;

class ClientController extends Controller
{
    /**
     * @Secure(roles="IS_AUTHENTICATED_FULLY")
     */
    public function addAction()
    {
        // stuff
    }

For using JMS\Security :

*

*Update composer

*Update AppKernel

*Add the line use JMS\SecurityExtraBundle\Annotation\Secure; in controller

*And use annotation

That's all right? What step did I miss?

A: I see that you don't have JMSDiExtraBundle.
Dan, here, explained his error/solution which seems to be awfully similar to yours.

A: This is just a wild guess, but since annotations are cached, have you tried clearing the cache? This may also be necessary in the dev environment..
app/console cache:clear --env=prod

The only other thing I can think of is some annotation issue. Have you tried using the @Route annotation on the action?


text:
Q: Side-menu in angular I want to make a same nav-bar like this:
https://stackblitz.com/edit/dynamic-nested-menus?file=app%2Fmenu-item%2Fmenu-item.component.html
But only with two levels,kinda like this:

*

*Menu

*

*submenu1

*

*subsubmenu1

*submenu2

*Menu2

*

*submenu1

*submenu2

So when I hovering or clicking on the Menu, the submenu come up withe their sub-menus
I hope you can understand it, and you can help to me, I can't find something like this.

A: In your app.component.ts you will find the nav items.
Just remove the childeren and you won't get the third level in your menu.
navItems: NavItem[] = [
    {
      displayName: 'AngularMix',
      iconName: 'close',
      children: [
        {
          displayName: 'Speakers',
          iconName: 'group',
          children: [
            {
              displayName: 'Michael Prentice',
              iconName: 'person',
              route: 'michael-prentice',
              children: [
                {
                  displayName: 'Delight your Organization',
                  iconName: 'star_rate',
                  route: 'material-design'
                }
              ]
            },


text:
Q: How do i track view count of different div blocks on single page while scrolling without clicking them I have many cards (div blocks) in my single page application. I want to track view counts when the user scrolls through this page. Means whenever one card visible on screen or in screen viewport area while scrolling just increments view count for that particular card (div blocks).

  <md-card md-theme="{{ showDarkTheme ? 'dark-grey' : 'default' }}" md-theme-watch>
    <md-card-title>
      <md-card-title-text>
        Card with image
        Large
      </md-card-title-text>
      <md-card-title-media>

      </md-card-title-media>
    </md-card-title>
    <md-card-actions layout="row" layout-align="end center">
      <md-button>Action 1</md-button>
      <md-button>Action 2</md-button>
    </md-card-actions>
  </md-card>

Now this card is in ng-repeat loop. Whenever user scroll down or up and particualr one card will be visible at that time I want to add Below mentioned html code to card to track view count.

It's like Facebook tracking pixel thing but I want to create custom and different tracking pixel for my cards which track view counts when div is visible.
I am using Ruby on Rails and Angularjs.

A: 1.) You need window scroll function here, so create card directive to use jquery like exampled in here except anchor use (you need to figure out the way of
 selection),
2.) Bind directive to it's controller and retrieve viewcount data from where you pull them, and pass that data to directive link function where you call scroll function


text:
Q: submit contact form and pass variables to page redirected in wordpress In wordpress I have a form using contact form 7. Upon filling the form and submitting I need it to carry variables e.g. name, address, email and amount and redirect to third party payment gateway page (hdfc in my case) so that users can just fill the form and make the payment in one go...
Woo-commerce involve 2-3 stesps i.e. add to cart, checkout, proceed to pay etc. I just wanted to fill the form and with filled information pass variables to payment page directly.
Any quick help much appreciated in advance...
Thanks!
Ranjan


text:
Q: WARNING: Can't mass-assign protected attributes I get this error "WARNING: Can't mass-assign protected attributes: races_attributes"
, when following this http://railscasts.com/episodes/196-nested-model-form-part-1 on rails 3.
Where Races are a component of Events. This is my models/race.rb:
class Race < ActiveRecord::Base
belongs_to :event

attr_accessible :name, :unit
end

This is my models/event.rb:
class Event < ActiveRecord::Base
has_many :races, :dependent => :destroy

accepts_nested_attributes_for :races

attr_accessible :name, :date, :description, :location_name, :address_one, :address_two, :city, :state, :zip, :active, :races_attributes
end

Any Ideas?

A: Shorter than using attr_accessible, safer than using whitelist_attributes: attr_protected
Just indicate the protected attributes, and Rails will infer that all others can be mass-assigned:
class MyClass < ActiveRecord::Base
  attr_protected :id
end

(I always have way more attributes that I want mass-assigned than the ones I want protected.)

A: attr_accessible specifies that you can not mass-assign attributes, using save method, for example. So, if you change an attribute that is not defined with attr_accessible, you will get a warning because it will not actually be saved in the database.


text:
Q: Matrix Azuma Inequality with non-zero mean Based on theorem 7.1 of the paper User-friendly tail bounds for sums of random matrices, we have:
Consider a finite adapted $\{ \mathbf{X}_k\}_{k=0}^{\infty}$ of self-adjoint matrices in dimension $d$, and a fixed sequence $\{ \mathbf{A}_k\}_{k=0}^{\infty}$ of self-adjoint matrices that satisfy
$$\mathbb{E}[\mathbf{X}_k]=0  \quad \text{and } \quad \mathbf{X}_k\preceq \mathbf{A}_k \quad
 \text{almost surely}$$
Compute the variance parameter
$$\sigma^2 = \| \sum_{k} \mathbf{A}_k^2 \|$$
Then, for all $t\ge 0$,
$$
\mathbb{P} \left\{ \lambda_{\max}\left( \sum_k\mathbf{X}_k \right)\ge t  \right\}\le d e^{-\frac{t^2}{8\sigma^2}}
$$
In this formula, the condition, $\mathbb{E}[\mathbf{X}_k]=0$ must hold. I am wondering if it is possible to extend it to the case that $\mathbb{E}[\mathbf{X}_k]=\mu_k \neq 0$? (Should $\mu_k$ be a matrix? So, it might be better to use sth like $\Sigma_k$, not $\mu_k$). Does expected value mean element-wise expectation?
If there is any references, I would be thankful if you could provide them.


text:
Q: Load package in Scheme48, how to get first, word variable, etc I just installed the scheme48 package from macports and have started experiencing. I was watching this youtube video, link here and was attempting to perform some of the examples. In the lecture the professor is running scheme on a Sun terminal. For example, I attempt to do '(first 473)' and get 'Error: undefined variable first'. Now, I'm assuming I haven't loaded the correct package / library or what ever it is called in scheme but am not sure what the syntax and library is. I believe that scheme48 and the scheme version on that sun terminal in the video are not the same and could be part of the problem.
So, what library do I need to use and how do I load it?

A: Those lecture notes are based on a book called Simply Scheme, and you can find the library code that is used in the book here.  Specifically, you need simply.scm.
(But whether it is a good idea to have these kind of overloading functions is debatable.  Specifically, note that first is used in a way that is different from many other languages.)


text:
Q: Bootstrap navbar refresh on tab change I use twitter bootstrap's navbar. The content of each tab comes from a php function which loads data from the database. Once the page has loaded I'd like to be able to refresh the data under each tab (which is equal to calling the respective php functions again) on tab change. I guess that would be the jquery onclick() event but how do I update the content?
<?php
    require_once 'Offers.php';
    $offers = new Offers();
?>

A

B

C

       <?php echo($offers->retrieveA());?>

       <?php echo($offers->retrieveB());?>

       <?php echo($offers->retrieveC());?>

A: So here's a very simple solution using ajax.
First we attach a jquery event click to each tab, and then fire an ajax call to our functions. Because usually ajax event calls some php script in a file and here we have to deal with functions, we put them in a separate php file and choose between them using a switch case statement.
So here we go. First we add ids to navbar tabs:

A

B

C

Then click event handlers for each tab. Each handler uses ajax to update tab content.
//Functions to dynamically update navbar
$('#nav1').click(function() {
    $.ajax({ url: 'refreshTabContent.php',
           data: {whichTab: 'tab1'},
           type: 'post',
           success: function(output) {
                     $('#tab1').html(output);
                    }
    });
});
$('#nav2').click(function() {
    $.ajax({ url: 'refreshTabContent.php',
           data: {whichTab: 'tab2'},
           type: 'post',
           success: function(output) {
                      $('#tab2').html(output);
                    }
    });
});
$('#nav3').click(function() {
    $.ajax({ url: 'refreshTabContent.php',
           data: {whichTab: 'tab3'},
           type: 'post',
           success: function(output) {
                      $('#tab3').html(output);
                    }
    });
});

Here's how. In each handler we call the new php script 'refreshTabContent.php' which we're just about to compose. In that script based on the value of whichTab we call the appropriate function that returns the content we want to display in the appropriate tab and then echo it back.
<?php

require_once 'Offers.php';
$offers = new Offers();

if(isset($_POST['whichTab']) && !empty($_POST['whichTab'])) {
    $action = $_POST['whichTab'];
    switch($action) {
        case 'tab1' :
            echo($offers->retrieveA());
            break;
        case 'tab2' :
            echo($offers->retrieveB());
            break;
        case 'tab3' :
            echo($offers->retrieveC());
            break;
    }
}

?>

A: The only way you can update anything on-the-fly without reloading the entire page is through javascript/jQuery, specifically in your case using ajax.
So you'd have to attach an onclick to your tabs that runs an ajax call back to your PHP file. (I don't remember how bootstrap attaches its own onclick, so if it's not working at all, that's where I'd check first).
However, I personally would write a second version of your PHP file in a way that it can accept $_GET parameters so it can return the content of only the selected tab.
The result is returned through ajax, and you can then send it back into the tab.
Depending on the content you're getting from PHP, this may cause a short loading pause when you click the tab.
I'm not really sure if it is even worth loading the tab content ahead of time if you're going to reload it on clicking the tab, anyway. Hard to say without more details.


text:
Q: django-ratelimit stack keys. Not the intended behaviour I think my understanding of django-ratelimit is incorrect. I am using v3.0.0 but v2.0 produces the same results.
Lets say I have this code:
@ratelimit(key='post:username', rate='5/h', block=True)
@ratelimit(key='post:tenant', rate='5/h', block=True)
@csrf_exempt
def index(request):
    print(request.POST["username"])
    print(request.POST["tenant"])
    print("")
    return HttpResponse('hallo', content_type='text/plain', status=200)

Let's say tenant A submits username "Antwon" 6 times, then tenant A will be blocked for 1 hour, which is good. But, lets say tenant B also has a user "Antwon", then that user for tenant B will not be able to log in.
I would assume that Antwon for tenant B should still be able to log in, otherwise tenant A can DOS other tenants?
Is this intended behavior or is my implementation incorrect?

A: My understanding is incorrect. Here is a response from the creator of django-ratelimit:
Hi there! I think there might be some confusion about how multiple ratelimits interact, and how the cache keys get set/rotated.

Multiple limits are ORed together—that is, if you fail any of them,
you fail—but order matters. In this case, the outer limit,
post:username, is tested first, then the tenant is tested. If the user
succeeds, it counts as an attempt, regardless of what happens later.
That's why the user keeps accruing attempts. If you want tenant to
count first, you could re-order the decorators. However...
If you want a single limit to the (username, tenant) pair, you could
combine the two fields with custom logic, by creating a callable key
that returned some combination of tenant and username (maybe
{tenant}\u04{username} or hash them together).
In terms of locking out tenants, there are a couple of things:
First, ratelimit uses a staggered fixed-window strategy, instead of a
sliding windows. So based on the rate, the period, the key value, and
the group, there'll be some calculated window. For example, for 1
hour, 11:03:29 will be the reset time, and the next reset time for
that same combination will be 12:03:29, then 13:03:29, etc... The
downside is that you if you had a limit of 100/h, you could do 200
requests in a short span around the reset point. The upsides are that
the calculation is share-nothing and can be done independently, the
window reset even if you accidentally try again a little too early.
Second, yes if you're doing hard blocks on user-supplied data like
username (instead of e.g. using the authenticated user) it creates a
denial-of-service vector. Where possible, another option is to use
block=False, and do something like require a captcha rather than fully
blocking.


text:
Q: Find difference between 2 recent transactions in 2 different weeks grouped by ID in R I have a dataframe as shown below
structure(list(ID = c(1, 1, 1, 1, 1,1,1), Start_Date = c("01-09-17",
"01-09-17", "08-09-17", "08-09-17", "08-09-17","15-09-17","15-09-17"), End_Date = c("07-09-17",
"07-09-17", "14-09-17", "14-09-17", "14-09-17","21-09-17","21-09-17"), Policy1_Date = c("05-09-17",
NA, "09-09-17", NA, "10-09-17","16-09-17","17-09-17"), Policy2_Date = c(NA, "06-09-17",
"08-09-17", "09-09-17", "10-09-17",NA,NA)), class = "data.frame", row.names = c(NA,
-5L))

What I need ? - For each ID, I am  supposed to calculate the difference between 2 dates (for each policy). Start_Date and End_Date depicts the start and end of week. Policy1_Date and Policy2_Date shows transaction dates and the weeks they fall into. For each week date, I want to find out the difference between dates in the way described below:
Policy1
For each week, say 08-09-17 till 14-09-17, I will take the Start date of week (08-09-17) and take the difference with the just previous date (not falling in the same week) i.e. 05-09-17. It should take previous non-NA date
Policy2
For each week, say 08-09-17 till 14-09-17, I need difference between 08-09-17 and 06-09-17.
In case there is no previous date available, I will simply put NA. For example, for week 01-09-17 till 07-09-17, latest transaction was 05-09-17 but there is no previous transaction available. I will mark NA for this week.
Final Output
This will have 5 columns (ID, Start_Date, End_Date, Policy1_gap, Policy2_gap).
structure(list(ID = c(1, 1, 1), Start_Date = c("01-09-17", "08-09-17",
"15-09-17"), End_Date = c("07-09-17", "14-09-17", "21-09-17"),
    Policy1_Gap = c(NA, 5, 7), Policy2_Gap = c(NA, 4, NA)), class = "data.frame", row.names = c(NA,
-3L))

Note: Entire aggregation will happen for each group/ID. I will not take difference between dates for 2 different groups/ID

A: Here is an option using data.table:
cols <- c("Policy1_Date", "Policy2_Date")
#convert columns into Date class
DT[, c("Start_Date", "End_Date", cols) := lapply(.SD, as.IDate, format="%d-%m-%y"),
    .SDcols=c("Start_Date", "End_Date", cols)]

#for each ID, Start_Date and End_Date, find the last non-NA date for each column
DT[, lapply(.SD, function(x) last(x[!is.na(x)])), .(ID, Start_Date, End_Date), .SDcols=cols][,
    #calculate the gap between dates
    c("Policy1_Gap","Policy2_Gap") := lapply(.SD, function(x) c(NA_integer_, diff(x))), ID, .SDcols=cols][,
        c("Policy1_Diff","Policy2_Diff") := lapply(.SD, function(x) Start_Date - shift(x)), ID, .SDcols=cols][]

output:
   ID Start_Date   End_Date Policy1_Date Policy2_Date Policy1_Gap Policy2_Gap Policy1_Diff Policy2_Diff
1:  1 2017-09-01 2017-09-07   2017-09-05   2017-09-06          NA          NA           NA           NA
2:  1 2017-09-08 2017-09-14   2017-09-10   2017-09-10           5           4            3            2
3:  1 2017-09-15 2017-09-21   2017-09-17         <NA>           7          NA            5            5

data:
library(data.table)
DT <- setDT(structure(list(ID = c(1, 1, 1, 1, 1,1,1), Start_Date = c("01-09-17",
    "01-09-17", "08-09-17", "08-09-17", "08-09-17","15-09-17","15-09-17"), End_Date = c("07-09-17",
        "07-09-17", "14-09-17", "14-09-17", "14-09-17","21-09-17","21-09-17"), Policy1_Date = c("05-09-17",
            NA, "09-09-17", NA, "10-09-17","16-09-17","17-09-17"), Policy2_Date = c(NA, "06-09-17",
                "08-09-17", "09-09-17", "10-09-17",NA,NA)), class = "data.frame", row.names = c(NA,
                    -5L)))


text:
Q: AssemblyInfo and accessing regular functions [assembly: AssemblyCopyright("Copyright ©  2009")]

is it possible somehow to access functions like DateTime.Now.Year inside the AssemblyInfo class? so as to put in like
[assembly: AssemblyCopyright("Copyright ©  " + DateTime.Now.Year)]

Doing the above will give, DateTime does not exist in the current context

A: Out of the box, no, but there are 2 options to access .NET functionality against your assembly file.
The easiest way to do your example would be to use the AssemblyInfo task from the MSBuildExtensionPack.
Once you have that installed you can use all the methods in that Task, http://www.msbuildextensionpack.com/help/4.0.4.0/index.html, such as the following:
    <Target Name="Version">
    <ItemGroup>
        <AssemblyInfoFiles Include="$(SourcePath)\Code\Properties\AssemblyInfo.cs"/>
    </ItemGroup>
    <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="Get" Format="yyyy">
        <Output TaskParameter="Result" PropertyName="MyStartTime"/>
    </MSBuild.ExtensionPack.Framework.DateAndTime>
    <MSBuild.ExtensionPack.Framework.AssemblyInfo ComVisible="false" AssemblyInfoFiles="@(AssemblyInfoFiles)" AssemblyBuildNumberType="YearWeekDay" FirstDayOfWeek="Sunday" AssemblyBuildNumber="4" AssemblyCopyright=" Foo Copyright $(MyStartTime)"/>
</Target>

The other option is to create a custom msbuild task on your own and expose additional functionality that way.


text:
Q: How to get XML file from FTP sever to Salesforce..? I have an XML file in FTP server, I need to read that file and loaded into document object in salesforce. I have read the below link but I am not able to understand.
http://www.chiragmehta.info/chirag/2010/03/22/salesforce-ftp-integration-data-loader-web-service-http.
Can we do an HTTP request to the FTP server..? If yes how I can achieve this without using Third-party tools like jitterbit or skyvia .Can anyone help me to solve it?
Thanks

A: You'll need some middleware that will pull the xml file from the ftp server and pass it back into salesforce.
The request process would look something like:
Apex -(Rest Request)-> Middleware -(FTP Request)-> File Server -(FTP Response)-> Middleware, then the middleware would upload file into content document via rest api.

Can we do an HTTP request to the FTP server..?

By definition an FTP server won't respond to HTTP requests.


text:
Q: What's the best way to see if someone is still using the app? Here's the problem: I have a React-Native/Redux app. I need to make sure I can lock the screen (display a modal, really) after X minutes of app inactivity (theoretically someone may have their screen "always on", so I can't rely on the screen turning itself off).
My proposed solution: I want to detect when any touch event happens. I don't want to interfere with them or do anything about it other than reset a setTimeout. But I just want to know when the screen is touched at all.
Displaying the modal itself isn't an issue and is already working. I also have it display the modal if the app leaves the foreground for any reason. I just need the timeout.
I've tried using a TouchableWthoutFeedback that wraps the whole UI and that sorta works, but it doesn't receive any event when a Touchable is farther down the component tree and handles the event. But I've also only used onPressIn and I'm unsure if anything else on it will work as needed. I've looked briefly at PanResponder but that looks a bit more complex than I might need? Not sure on that one, yet.
I'm open to other suggestions, but the only other thing I can think of is having literally every other action in the app (even ones I haven't created yet) send an dispatch up the redux flagpole, and that seems very heavy-handed and prone to error.
is this feasible? What are my options if it's not?

A: I found the solution. It's to add a onStartShouldSetResponderCapture callback as a prop on a containing View. I can return false in this callback but still notice all the touch events that come through. The Capture portion is important because it gives you access to the event before a "real" touchable can get to it.
Then, in the callback, I just clear and re-create the timer.


text:
Q: Validation for save button I've difficulty in creating a validation before saving it to sqlite, below is the code:
public void save(View v){
    String weight = weightinputid.getText().toString();
    String bmi = BMIfinal.getText().toString();
    String status = BMIStatus.getText().toString();

    long id = data.insertData(weight, bmi, status);

    if(id<0){
        message.mess(this, "Error");
    }
    else{
        message.mess(this, "BMI has been saved");
    }
}

How do I create a validation if all the textfields are empty? my problem right now, even if i pressed the save button, the empty textfields was saved inside the database

A: You can just try this, to check if value is not entered in the EditText.
if (weight .equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if (bmi.equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (status.equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value3", Toast.LENGTH_LONG).show();
}

Alternatively, you can use .matches("") instead of .equals("")
UPDATE
As @Rajesh mentioned in his comments, you can also use
TextUtils.isEmpty(weightinputid.getText())

to achieve the same functionality.

A: You can definitely do @Lal suggestion but in case the N fields are empty it's going to show the N toasts, and that's not very useful:
I'll suggest to do the following one of the following options:
a) Implement MaterialEditText:
Check the details here:
https://github.com/rengwuxian/MaterialEditText
<com.rengwuxian.materialedittext.MaterialEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Min Characters"
        app:met_minCharacters="1" />

b) Use a TextWatcher and enable the SaveButton only after you have your required fields with values:
http://developer.android.com/reference/android/text/TextWatcher.html
You can see how to it with the following question:
Disable Button when Edit Text Fields empty


text:
Q: Creating a new email in Outlook including email body text On a corporate intranet where all of our users are using Outlook 2003 I have a need to allow a user to click a link that opens a new email window with a prepopulated message body, subject and To line. The body text requirement eliminates a simple option like a MailTo link.
I know there is an EML format Outlook uses, but I don't see how to use it to open a message that displays like a new email message being sent by the user. It seems to just be a format for archiving emails in a regular folder.
Are there other options? Other file formats?

A: you CAN use mailto and have a message in the body.
http://www.ianr.unl.edu/internet/mailto.html

A: This isn't supported properly across other mail clients/webmail clients but if Outlook is your only audience you can try the following:
Link

You need to ensure that any characters are encoded properly (full stops, ampersands etc)


text:
Q: Custom validation directive with isolated scope in angularjs? Take a look at the following JSFiddle: http://jsfiddle.net/AaQtz/21/. As you can see, the custom validation runs and when the value is considered valid it is updated in the model.
However, when I add scope: {}, to the directive, the model is no longer receiving updates when the value is valid. Why is this? This behaviour makes it very hard to build a directive that validates a field depending on other fields (fields I would like to pass using the scope, such as scope: { somefield: '=' },). JSFiddle showing the problem: http://jsfiddle.net/JYUmT/1/.
Can anyone explain this?

A: ng-model and isolate scopes do not mix: Can I use ng-model with isolated scope?
Use $eval or $parse to pass/examine attributes in a directive that doesn't use an isolate scope: https://stackoverflow.com/a/15725402/215945


text:
Q: Nested functional range query with OR I'm trying to do a functional query with an OR/AND however it seems there are limitations in doing so. Here is the logic for the SQL equivalent of the query I'm trying to perform:
ABS(col1-:val1)<1 OR (col1 IS NULL AND ABS(col2-:val1)<1)

Here is my current working fq query to grab the the documents with an ABS difference of <1.
fq={!frange l=0 u=1}abs(sub(col1,val1))

Here is what I'm trying to execute but can't without error
fq={!frange l=0 u=1}abs(sub(col1,val1)) OR (-col1:[* TO *] AND {!frange l=0 u=1}abs(sub(col2,val1)))

It seems like it's not possible to use and AND or and OR in the same fq when using a functional query. How would I go about doing this? I am using solr 4.1. Thanks

A: Try
fq={!frange l=0 u=1 v=$myabs}&myabs=abs(sub(col1,val1))

A: I stumbled upon similar issue and found out the solution. Posting it here so it might help somebody.
The original query can be modified like this using query:"..." feature of solr:
fq=_query_:"{!frange l=0 u=1}abs(sub(col1,val1))" OR (-col1:[* TO *] AND _query_:"{!frange l=0 u=1}abs(sub(col2,val1)))"


text:
Q: Mapping multiple collections to a single collection using Automapper I am able to map group of sametype of collections to a single collection using the below code.
AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
                dest => dest.Drivers,
                opt => opt.MapFrom(src => src.BikeDrivers.Concat(src.CarDrivers).Concat(src.TruckDrivers)));

With the above solution I am able to map all the three type of drivers into one collection.
My destination object (Driver) has a property called DriverType which helps in identifying the type of driver. (BikeDriver/CarDriver/TruckDriver)
In the above code, how i can set the DriverType property based on the collection I am adding.
for eg: i have to hard code
DriverType = CarDriver for CarDrivers collection items
DriverType = BikeDriverfor BikeDrivers collection item.
Thanks in advance

A: To set the DriverType property you have to have this knowledge in your source object. I can't see your big picture, but this maybe used as a sample
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = new Source()
                        {
                            BikeDrivers = new List<BikeDriver>() {new BikeDriver()},
                            CarDrivers = new List<CarDriver>() {new CarDriver()},
                            TruckDrivers = new List<TruckDriver>() {new TruckDriver()},
                        };

            var d = new Destination();

            AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
                dest => dest.Drivers,
                opt => opt.MapFrom(src => src.BikeDrivers.Concat<IDriver>(src.CarDrivers).Concat<IDriver>(src.TruckDrivers)));

            var result = AutoMapper.Mapper.Map(s, d);
        }

        public class Driver : IDriver
        {
            public string DriverType { get; set; }
        }

        public class Destination
        {
            public IEnumerable<IDriver> Drivers { get; set; }
        }

        public class Source
        {
            public IEnumerable<BikeDriver> BikeDrivers { get; set; }
            public IEnumerable<CarDriver> CarDrivers { get; set; }
            public IEnumerable<TruckDriver> TruckDrivers { get; set; }
        }

        public interface IDriver
        {
            string DriverType { get; set; }
        }

        public class BikeDriver : IDriver
        {
            public string DriverType
            {
                get { return "BikeDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
        public class CarDriver : IDriver
        {
            public string DriverType
            {
                get { return "CarDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
        public class TruckDriver : IDriver
        {
            public string DriverType
            {
                get { return "TruckDriver"; }
                set { throw new NotImplementedException(); }
            }
        }
    }
}


text:
Q: Show that $\{1,x,x^2\}$ is $\mathbb{Q}-$base of $\mathbb{Q}(x)$ I want to show that $\{1,x,x^2\}$ is $\mathbb{Q}-$base of $\mathbb{Q}(x)$.
We're looking at the field extension $\mathbb{C}/\mathbb{Q}$ and $x\in \mathbb{C}$.
$\mathbb{Q}(x)$ is the smallest subfield of $\mathbb{C}/\mathbb{Q}$ that contains $x$. Also, $x$ is a complex root of $X^3-2X+2\in \mathbb{Q}[X]$.

First I showed that $m = X^3-2X+2$ is the minimal polynomial of $x$. Since it's already given that $x$ is a root of $m$, I only need to show that it's irreducible.
Let $p=2$ and $m = X^3-2X+2 = aX^3+bX+c$.
Then $p$ is a prime and $p\mid b \wedge p\mid c$ but $p^2\nmid c \wedge p\nmid a$. By Eisenstein criterion this polynomial is irreducible and therefore the minimal polynomial of $x$.
That means that $[\mathbb{Q}(x) : \mathbb{Q}] = 3$, right?
So we only need to find $3$ linearly independent vectors. Two of them are obvious to me, namely $\{1,x\}$. But I don't really get why I need $x^2$ and how I can prove that it's independent from $x$ (or $1$).
My guess is that if it was linear dependent, we then have by linear combination:
$$\lambda_1 \cdot 1 + \lambda_2 \cdot x = \lambda_3 \cdot x^2 \Rightarrow  -\lambda_3\cdot x^2 + \lambda_1 \cdot 1 + \lambda_2 \cdot x =0$$
Since that polynomial has degree $2$ and $x$ is a root, it's a contradiction because the minimal polynomial of $x$ has degree $3$.
Any help is appreciated.

A: If $1,x,x^2$ are not linearly independent then $\lambda_0,\lambda_1,\lambda_2\in\mathbb C$ exists such that: $$\lambda_0+\lambda_1x+\lambda_2x^2=0\text{ and }(\lambda_0,\lambda_1,\lambda_2)\neq(0,0,0)$$
However then $x$ is the root of a non-zero polynomial with degree less than $3$ contradicting the fact that its minimum polynomial has degree $3$.


text:
Q: Проверка ввода числа Kotlin Есть поле EditText в inputType выбрал numberDecimal.
Теперь возник вопрос проверки данных которые введёт пользователь. На пустое поле нашёл как проверять.
Осталось сделать проверку на то что пользователь введёт любые символы кроме цифр и точки, так же нужно сделать проверку на то что точка и ноль не может быть первыми символом. И проверку на то что после точки может быть только два знака.
Помогите пожалуйста а то в котлине и в андроид студио буквально пару дней) Заранее всем спасибо ;)

A: Тип numberDecimal потому так и называется, что принимает только цифры, знак минус и десятичный разделитель. Ничего дополнительно проверять не надо

A: Чтобы проверить что введенные данные не начинаются с 0 или точки можно добавить в активность/фрагмент слушатель ввода и там проверять:
editTextSample.addTextChangedListener(object : TextWatcher {

    override fun afterTextChanged(s: Editable) {}

    override fun beforeTextChanged(s: CharSequence, start: Int,
                                   count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence, start: Int,
                               before: Int, count: Int) {
    }
})

к примеру в этом методе onTextChanged вы будете проверять то что вводит пользователь сразу как он это ввел:
override fun onTextChanged(s: CharSequence, start: Int,
                                   before: Int, count: Int) {

    val text = s.toString().trim().get(0) // first letter

}

и дальше уже проверяйте на ваши условия

A: Это не изящное решение, но оно будет работать.
У вас есть два варианта, проверять поле ввода, после нажатия какой-то кнопки или же сразу (как ниже). Но тогда вам нужна некая задержка, чтобы пользователь успел ввести то, что задумал. Для этого отлично подходит Handler с задержкой в одну секунду, так пользователь поймет ошибку. Если ответ покажется вам полезным, могу его расширить.
Если правила проверки не такие, как вам нужно, опишите это в комментарии
editTextSample.addTextChangedListener(object : TextWatcher {

    override fun afterTextChanged(s: Editable) {}

    override fun beforeTextChanged(s: CharSequence, start: Int,
                                   count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence, start: Int,
                               before: Int, count: Int) {
       if (isValid(s.toString)) {
          // done
       } else {
          editTextSample.error = "your error text"
       }
    }
})

    fun isValid(text: String): Boolean {
        val firstLetter = text.firstOrNull()

        if (firstLetter == null || firstLetter == '0' || firstLetter == '.') {
            return false
        }

        if (!text.contains('.')) {
            return false
        }

        if (text.substringAfter('.').count() != 2) {
            return false
        }

        text.toDoubleOrNull() ?: return false

        return true
    }


text:
Q: How to define the type of elements in an rdf:Seq? I want to create a property defining a rdf:Seq as a rdfs:range of an object :
eg:myProperty a rdf:Property;
    rdfs:range rdf:Seq;
    .

I'm looking for a way to define the type of the elements stored in the rdf:Seq. For example, I don't want this :
eg:typeOfElement a rdf:Class;
    .

eg:somethingElse a rdf:Class;
    .

[] eg:myProperty [
        a rdf:Seq;
        rdf:_1 [a eg:typeOfElement];   # It's the type I want
        rdf:_2 [a eg:typeOfElement];   # It's the type I want
        rdf:_3 [a eg:somethingElse];   # I don't want this type
    ];
    .

Is there a way to define that the rdf:Seq elements are only of the type of eg:typeOfElement when I define eg:myProperty?
(I can use owl if necessary.)

A: There are probably a number of ways to accomplish this, depending on your implementation preferences. My advice is to use the rdf:li special property in place of the arbitrary rdf:_nnn, which is easier to extend. rdf:li is equivalent to rdf:_1, rdf:_2 in order. So the following code blocks are equivalent:
:mySeq a rdf:Seq;
  rdf:_1 :foo;
  rdf:_2 :bar .

:mySeq a rdf:Seq;
  rdf:li :foo;
  rdf:li :bar .

Note that the order in the second block is significant.
To accomplish what you are asking, you can extend rdf:li with a new property and refine its domain/range (although these are only really meaningful to human readers, as the child property inherits the semantics of the parent):
:myItem rdfs:subPropertyOf rdf:li;
  rdfs:range :typeOfElement;
  rdfs:domain :mySeq .

:myItem inherits the semantics of rdf:li, so whatever implementatin logic you have can infer that the values of :myItem are in some meaningful order. Next define the :mySeq class via a property restriction:
:mySeq rdfs:subClassOf [
    a owl:Restriction;
    owl:onProperty :myItem;
    owl:allValuesFrom :typeOfElement;].

which asserts that :mySeq is a class of all things where the property :myItem is explicitly used for values of :typeOfElement. You can now create lists with :mySeq.

To go a step further, you may define :mySeq as the intersection of the above rule and rdf:Seq:
:mySeq a owl:Class;
    owl:equivalentClass
    [ a owl:Class;
        owl:intersectionOf
          ( rdf:Seq
            [a owl:Restriction;
             owl:onProperty :myItem;
             owl:allValuesFrom :typeOfElement ]) ] .

Note the use owl:equivalentClass in place of rdfs:subClassOf. If we treat owl:equivalentClass as symmetric and subsumed by rdfs:subClassOf, eg:
owl:equivalentClass a owl:SymmetricProperty .
owl:equivalentClass rdfs:subPropertyOf rdfs:subClassOf .

then we can have equivalence that goes in both directions. Therefore all instances of rdf:Seq whose values for :myItem are of :typeOfElement are also instances of :mySeq. In this case you are inferring the type. So via the statement:
:x a rdf:Seq; :myItem :foo, :bar .

you may infer that :x a :mySeq.


text:
Q: DataTables are not styled with Bootstrap 3 classes when using RequireJS I am trying to use the DataTables jQuery plugin to style a table with the Bootstrap extension that they provide.  I am using RequireJS as it is a very large project, but I have simplified the example to a barebones implementation below.  I'm using the latest version of all plugins available as of now, and they should all work together, but they aren't.  The DataTables plugin is working fine, but the Bootstrap extension for DataTables is not applying the styles I am expecting.  For example, the pagination should be getting a
 wrapped around it, but that's not happening.  There are no errors in the console either.  What is the problem?
<!doctype html>

<title>DataTables with Bootstrap and RequireJS</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

                Name
                Position
                Office
                Age
                Start date
                Salary

                Name
                Position
                Office
                Age
                Start date
                Salary

                Tiger Nixon
                System Architect
                Edinburgh
                61
                2011/04/25
                $320,800

                Garrett Winters
                Accountant
                Tokyo
                63
                2011/07/25
                $170,750

                Ashton Cox
                Junior Technical Author
                San Francisco
                66
                2009/01/12
                $86,000

                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                22
                2012/03/29
                $433,060

                Airi Satou
                Accountant
                Tokyo
                33
                2008/11/28
                $162,700

                Brielle Williamson
                Integration Specialist
                New York
                61
                2012/12/02
                $372,000

                Herrod Chandler
                Sales Assistant
                San Francisco
                59
                2012/08/06
                $137,500

                Rhona Davidson
                Integration Specialist
                Tokyo
                55
                2010/10/14
                $327,900

                Colleen Hurst
                Javascript Developer
                San Francisco
                39
                2009/09/15
                $205,500

                Sonya Frost
                Software Engineer
                Edinburgh
                23
                2008/12/13
                $103,600

                Jena Gaines
                Office Manager
                London
                30
                2008/12/19
                $90,560

                Quinn Flynn
                Support Lead
                Edinburgh
                22
                2013/03/03
                $342,000

                Charde Marshall
                Regional Director
                San Francisco
                36
                2008/10/16
                $470,600

                Haley Kennedy
                Senior Marketing Designer
                London
                43
                2012/12/18
                $313,500

                Tatyana Fitzpatrick
                Regional Director
                London
                19
                2010/03/17
                $385,750

                Michael Silva
                Marketing Designer
                London
                66
                2012/11/27
                $198,500

                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                64
                2010/06/09
                $725,000

                Gloria Little
                Systems Administrator
                New York
                59
                2009/04/10
                $237,500

                Bradley Greer
                Software Engineer
                London
                41
                2012/10/13
                $132,000

                Dai Rios
                Personnel Lead
                Edinburgh
                35
                2012/09/26
                $217,500

                Jenette Caldwell
                Development Lead
                New York
                30
                2011/09/03
                $345,000

                Yuri Berry
                Chief Marketing Officer (CMO)
                New York
                40
                2009/06/25
                $675,000

                Caesar Vance
                Pre-Sales Support
                New York
                21
                2011/12/12
                $106,450

                Doris Wilder
                Sales Assistant
                Sidney
                23
                2010/09/20
                $85,600

                Angelica Ramos
                Chief Executive Officer (CEO)
                London
                47
                2009/10/09
                $1,200,000

                Gavin Joyce
                Developer
                Edinburgh
                42
                2010/12/22
                $92,575

                Jennifer Chang
                Regional Director
                Singapore
                28
                2010/11/14
                $357,650

                Brenden Wagner
                Software Engineer
                San Francisco
                28
                2011/06/07
                $206,850

                Fiona Green
                Chief Operating Officer (COO)
                San Francisco
                48
                2010/03/11
                $850,000

                Shou Itou
                Regional Marketing
                Tokyo
                20
                2011/08/14
                $163,000

                Michelle House
                Integration Specialist
                Sidney
                37
                2011/06/02
                $95,400

                Suki Burks
                Developer
                London
                53
                2009/10/22
                $114,500

                Prescott Bartlett
                Technical Author
                London
                27
                2011/05/07
                $145,000

                Gavin Cortez
                Team Leader
                San Francisco
                22
                2008/10/26
                $235,500

                Martena Mccray
                Post-Sales support
                Edinburgh
                46
                2011/03/09
                $324,050

                Unity Butler
                Marketing Designer
                San Francisco
                47
                2009/12/09
                $85,675

                Howard Hatfield
                Office Manager
                San Francisco
                51
                2008/12/16
                $164,500

                Hope Fuentes
                Secretary
                San Francisco
                41
                2010/02/12
                $109,850

                Vivian Harrell
                Financial Controller
                San Francisco
                62
                2009/02/14
                $452,500

                Timothy Mooney
                Office Manager
                London
                37
                2008/12/11
                $136,200

                Jackson Bradshaw
                Director
                New York
                65
                2008/09/26
                $645,750

                Olivia Liang
                Support Engineer
                Singapore
                64
                2011/02/03
                $234,500

                Bruno Nash
                Software Engineer
                London
                38
                2011/05/03
                $163,500

                Sakura Yamamoto
                Support Engineer
                Tokyo
                37
                2009/08/19
                $139,575

                Thor Walton
                Developer
                New York
                61
                2013/08/11
                $98,540

                Finn Camacho
                Support Engineer
                San Francisco
                47
                2009/07/07
                $87,500

                Serge Baldwin
                Data Coordinator
                Singapore
                64
                2012/04/09
                $138,575

                Zenaida Frank
                Software Engineer
                New York
                63
                2010/01/04
                $125,250

                Zorita Serrano
                Software Engineer
                San Francisco
                56
                2012/06/01
                $115,000

                Jennifer Acosta
                Junior Javascript Developer
                Edinburgh
                43
                2013/02/01
                $75,650

                Cara Stevens
                Sales Assistant
                New York
                46
                2011/12/06
                $145,600

                Hermione Butler
                Regional Director
                London
                47
                2011/03/21
                $356,250

                Lael Greer
                Systems Administrator
                London
                21
                2009/02/27
                $103,500

                Jonas Alexander
                Developer
                San Francisco
                30
                2010/07/14
                $86,500

                Shad Decker
                Regional Director
                Edinburgh
                51
                2008/11/13
                $183,000

                Michael Bruce
                Javascript Developer
                Singapore
                29
                2011/06/27
                $183,000

                Donna Snider
                Customer Support
                New York
                27
                2011/01/25
                $112,000

A: At the end of the dataTables.bootstrap.js file, they initialize the script as an AMD module with the name datatables.  Therefore, my shim with the same name was not working.  I modified the names in my JavaScript to the following and it works now.


text:
Q: php error handling using session and redirecting I have a php file which checks for login and password from users database, it works fine.
But I am unable to validate the exact error to display if the user does not exist or password incorrect to the user and go back to previous page after error, help me how to display these errors.
<?php // access.php
include_once 'common.php';
include_once 'db.php';

session_start();

$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];

if(!isset($uid)) {
  ?>

  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Login</title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />

  Login Required

  You must login to access this area of the site.

  If you are not a registered user, please contact your Admin
     to sign up for instant access!

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    User ID:
    <input type="text" name="uid" size="12" />

    Password:
    <input type="password" name="pwd" SIZE="12" />

    <input type="submit" value="Login" />
  </form>

  <?php
  exit;
}

$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;

dbConnect("svga");
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = '$pwd'";
$result = mysql_query($sql);
if (!$result) {
  error('A database error occurred while checking your '.
        'login details.\\nIf this error persists, please '.
        'contact you@example.com.');
   }

if (mysql_num_rows($result) == 0) {
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);
  ?>

  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title> Access Denied </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />

 Access Denied

Your user ID or password is incorrect, or you are not a
     registered user on this site. To try logging in again, click
     <a href="<?=$_SERVER['PHP_SELF']?>">here. To access, please contact our Admin     !.

<?php
  exit;
}
$username = mysql_result($result,0,'fullname');
$_SESSION['user'] = mysql_result($result,0,'userid');
?>

A: simply put
if(mysql_num_rows($result)==0) {
header('location:your_page.php');
}

this will redirect you to the page and assuming that you have defined error() method, just
echo error();


text:
Q: Does DataFrame.applymap always go from top down then left to right? I want to know if the Pandas applymap function always go through from top to bottom and left to right (iterating through each row on a per column basis).
Mainly, I'm using applymap to pass a dictionary to count the number of items as a list in each cell, BUT I have to account for it differently once the value is seen for the first time.  So if applymap always goes works consistently, I can use it, but if there are some weird potential for race conditions, then I can't.
import numpy as np
import pandas as pd

vals = np.arange(25).reshape([5,5])
df = pd.DataFrame(vals)
print(df)

    0   1   2   3   4
0   0   1   2   3   4
1   5   6   7   8   9
2   10  11  12  13  14
3   15  16  17  18  19
4   20  21  22  23  24

l = []
_ = df.applymap(lambda x: l.append(x))

print(l)

[ 0,  5, 10, 15, 20,
1, 6, 11, 16, 21,
2, 7, 12, 17, 22,
3, 8, 13, 18, 23,
4, 9, 14, 19, 24]

A: I believe this always will be consistent, as apply by default also works column-by-columns.
I found a comment here on Stack Overflow to that effect (emphasis mine):

strictly speaking, applymap internally is implemented via apply with a little wrap-up over passed function parameter (rougly speaking replacing func to lambda x: [func(y) for y in x], and applying column-wise)

A: In the source code, applymap uses apply, which work by default by column.
The order seems consistent, even on a shuffled array:
import numpy as np
import pandas as pd
from itertools import count

df = pd.DataFrame(np.zeros((5,5)))

c = count()

df.sample(frac=1).sample(frac=1, axis=1).applymap(lambda x: next(c))

output:
   1  3   2   0   4
0  0  5  10  15  20
4  1  6  11  16  21
3  2  7  12  17  22
1  3  8  13  18  23
2  4  9  14  19  24

Now, I think the real question is, "is this behavior stable or is it just an implementation detail that could change in the future?"


text:
Q: How to echo using telnet I created an echo server that listens for incoming connections and echos any received data. I am using telnet to establish the connection.
#!/usr/bin/env python
import socket
import sys

# Create socket
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Port for socket and Host
PORT = 8001
HOST = 'localhost'

# bind the socket to host and port
sockfd.bind((HOST, PORT))
# become a server socket
sockfd.listen(5)

while True:
    # Establish and accept connections woth client
    (clientsocket, address) = sockfd.accept()

    print("Got connection from", address)
    # Recieve message from the client
    message = clientsocket.recv(1024)
    reply = 'Server output: ' + message.decode('utf-8')
    if not message:
        break
    # Display messags.
    clientsocket.sendall(str.encode(reply))

# Close the connection with the client
clientsocket.close()

Currently after I prompted with "server output:  ", it hangs and nothing is echoed back on to the terminal.

A: The problem is that you have the call to sockfd.accept() inside your while-loop:
while True:
   # Establish and accept connections woth client
   (clientsocket, address) = sockfd.accept()

... because of that, after the server receives the first data, it will block again, waiting for another TCP connection.
Move that call to above the while True: line and you'll get behavior more in line with your expectations.


text:
Q: jquery-ui-draggable alignment guidelines Is it possible to show the alignment guidelines with a jquery-ui-draggable while dragging it relative to other jquery-ui-draggable?
This is not jquery-ui but you can take idea from this one https://gomockingbird.com/mockingbird/.

A: This doesn't exist that I'm aware of.  You'd have to implement a custom solution.


text:
Q: Why DBMS_Scheduler job failed? I have written one procedure and one job.
From job I am running procedure. Following is the script for creating job
DBMS_SCHEDULER.create_job  (job_name  => 'IBPROD2.RUN_FETCH_ACCT_ALERTS',
job_type        => 'STORED_PROCEDURE',
job_action      => 'FETCH_ACCT_ALERTS',
start_date      => sysdate,
repeat_interval => 'FREQ=HOURLY;INTERVAL=2;',
enabled         => TRUE,
auto_drop       => FALSE
);

After creating job I am running following command to get job details for owner IBPROD2 where I can see failure_count column value as 1 for RUN_FETCH_ACCT_ALERTS job.
There is no problem in procedure FETCH_ACCT_ALERTS when I run it manually.
Can anyone help me in why the job is failing? Am I missing something?

A: Query the ALL_SCHEDULER_JOB_RUN_DETAILS view (or perhaps the DBA equivalent).
select *
from all_scheduler_job_run_details
where job_name = 'IBPROD2.RUN_FETCH_ACCT_ALERTS'

You'll be particularly interested in the error# which will give you an Oracle error number you can look up.  Also, the additional_info column might have some, er, additional info.

The error code means this:

ORA-28179: client user name not provided by proxy
      Cause: No user name was provided by the proxy user for the client user.
      Action: Either specify a client database user name, a distinguished name or an X.509 certificate.

So it's something to do with your security set up.  Authentication is failing for reason.  As I lack a detailed knowledge of your architecture (and I'm not a security specialist) I'm not in a position to help you.

Because I have already created many jobs to run different procedures
  with same owner. All are running successfully.

So in what way does this procedure differ from all the others?


text:
Q: ie9 & Firefox focus onmousedown input I have a web page that uses dragable elements to arrange applications to the users specifications. The user can drag(onmousedown) a box and drop it inline with other boxes.
Inside of those boxes are input, textarea, radio & checkbox types of input.
Everything works perfectly in IE8
Problems with IE9, Firefox 17.0.1 & Firefox 14.0.1(just the versions I've tested)
The problem is that when I click on an input box or a textarea box, the onmousedown event fires & steals the focus. Once I release the mouse, nothing happens to release the focus back to the input box. radio & checkboxes work just fine.
There are multiple inputs & multiple elements.
Anyonehave any ideas? I don't really have an open example to play with because it is in a login restricted environment.
I've been searching on this problem all day, any direction would be amazing!
function initdragableElements()
{
    dragableElementsParentBox = document.getElementById('dragableElementsParentBox');
    insertionMarkerDiv = document.getElementById('insertionMarker');
    insertionMarkerLine = document.getElementById('insertionMarkerLine');
    dragableAreaWidth = dragableElementsParentBox.offsetWidth;

    if(!useRectangle){
        dragDropMoveLayer = document.createElement('DIV');
        dragDropMoveLayer.id = 'dragDropMoveLayer';
        document.body.appendChild(dragDropMoveLayer);
    }

    var subDivs = dragableElementsParentBox.getElementsByTagName('*');
    var countEl = 0;
    for(var no=0;no<subDivs.length;no++){
        var attr = subDivs[no].getAttribute('dragableBox');
        if(opera)attr = subDivs[no].dragableBox;
        if(attr=='true'){
            subDivs[no].style.cursor='move';
            subDivs[no].onmousedown = initDrag;

            var index = dragableObjectArray.length;
            dragableObjectArray[index] = new Array();
            ref = dragableObjectArray[index];
            ref['obj'] = subDivs[no];
            ref['width'] = subDivs[no].offsetWidth;
            ref['height'] = subDivs[no].offsetHeight;
            ref['left'] = getLeftPos(subDivs[no]);
            ref['top'] = getTopPos(subDivs[no]);
            ref['index'] = countEl;
            countEl++;
        }
    }

    /* Creating rectangel indicating where item will be dropped */
    rectangleDiv = document.createElement('DIV');
    rectangleDiv.id='rectangle';
    rectangleDiv.style.display='none';
    dragableElementsParentBox.appendChild(rectangleDiv);

    document.body.onmousemove = moveDragableElement;
    document.body.onmouseup = stop_dragDropElement;
    document.body.onselectstart = cancelSelectionEvent;
    document.body.ondragstart = cancelEvent;
    window.onresize = repositionDragObjectArray;

    documentHeight = document.documentElement.clientHeight;
}

function initDrag(e)
{
    if(document.all)e = event;
    mouse_x = e.clientX;
    mouse_y = e.clientY;
    if(!documentScrollHeight)documentScrollHeight = document.documentElement.scrollHeight + 100;
    el_x = getLeftPos(this)/1;
    el_y = getTopPos(this)/1;
    dragObject = this;
    if(useRectangle){
        rectangleDiv.style.width = this.clientWidth - (rectangleBorderWidth*2) +'px';
        rectangleDiv.style.height = this.clientHeight - (rectangleBorderWidth*2) +'px';
        rectangleDiv.className = this.className;
    }else{
        insertionMarkerLine.style.width = '6px';
    }
    dragDropTimer = 0;
    dragObjectNextObj = false;
    if(this.nextSibling){
        dragObjectNextObj = this.nextSibling;
        if(!dragObjectNextObj.tagName)dragObjectNextObj = dragObjectNextObj.nextSibling;
    }
    initDragTimer();
    return false;
}


text:
Q: Count occurrence of a value combination in R So I got these two data frames:
a <- c('A','B','C')

frame1 <- data.frame(a)

a <- c('A','A','B','B','C','C','C')
b <- c(12,18,120,9,1,7,12)

frame2<- data.frame(a,b)

Now I would like to know how many times each unique value in column 'a' occurs in frame2 and add this value to frame1.
The result should look like this:
  a c
1 A 2
2 B 2
3 C 3


text:
Q: Best practices for deploying Rails 3.2.x app to Heroku? Are there changes to the rails config files that are commonly made to boost performance before deploying most apps to production on Heroku? Curious after reading Nerian's answer to this question (summary: Heroku deployment issue solved by making "config.assets.compile = true" in config/environments/production).
Hope this isn't too general-- I'm a stack overflow newb as well. Thanks!


text:
Q: Problems with counting upper and lower case in Python Essentially, I am trying to read some text and count instances of letters. Very simple. However, no matter what I try, I get different results for "E" and "e", when I want combined results. Here is what I have:
import nltk
import re

f = open('mytext.txt')
raw = f.read()
#print raw
#print len(raw) #7234

raw.lower()

prompt = raw_input("Enter stuff: ")

potato = re.compile(r'[a-z]*', re.IGNORECASE)
potato = re.match(r'[a-z]*', prompt, re.IGNORECASE)
if potato:
   print raw.count(prompt)
else:
   print "try again"

#document control f "e" = 808
#print result "e" = 802, "E" = 6

A: Calling raw.lower() does nothing - you didn't store the result. Try this instead:
raw = raw.lower()

A: This:
raw.lower()

does not do what you think it does. Replace it with
raw = raw.lower()

Python strings are immutable; any operation that you perform on them will return a new string with that modification.
If you want it to be case-insensitive for both the input text and the prompt entered by the user, also change
prompt = raw_input("Enter stuff: ")

to
prompt = raw_input("Enter stuff: ")
prompt = prompt.lower()


text:
Q: How to access data of another variable by pointing to a slack-byte in a structure? #include <stdio.h>
#include <stdlib.h>

struct someStruct {
    int ivar;
    char cvar;
    float fvar;
};

main(argc,argv)
const char** argv;
{
    struct someStruct someObj;
    someObj.ivar = 1;
    someObj.fvar = 2.3;
    someObj.cvar = 'r';
    printf("%u\n",&someObj.fvar);
    printf("%u\n",(&someObj.cvar + 4));
    printf("%f\n",*((&someObj.cvar) + 4));
    printf("%f\n",someObj.fvar);
}

This is a program I wrote which tries to access the address of fvar by adding 4 to the address of char.
I know the concept of slack-byte. I tried to access that memory, and lo! it printed the address correctly.
printf("%u\n",&someObj.fvar);
printf("%u\n",(&someObj.cvar + 4));

Both print the same address.
Then I tried to access fvar in the following way:
printf("%f\n",*((&someObj.cvar) + 4));
printf("%f\n",someObj.fvar);

and
0.000000
2.300000

were my results.
Then I realised that char* and float* are interpreted differently.
So, I tried all kinds of typecasting from char* to float* to float and also from char to float* to float and that too at all possible points like for e.g., typecasting the returned address to float,using 4.0 instead of 4 (which I realised wasn't supposed to work... and it didn't),etc.
It somehow just doesn't print 2.300000 and keeps printing 0.000000
Where am I missing the concept?
Note that I have a 64-bit MinGW and adds slack-byte (I know some don't) which I've already verified by:
printf("%u",sizeof(someObj.ivar));
printf("%u",sizeof(someObj.fvar));
printf("%u",sizeof(someObj.cvar));
printf("%u",sizeof(someObj));

which yields 4, 4, 1 and 12 ....(sizeof(char) + 3) respectively.
P.S. I know this is a horrible idea, but this is how I usually learn concepts XD

A: Assuming that the following is true:
 &someObj.cvar + 4 == &someObj.fvar

you can cast the pointer value to a proper type:
printf("%f\n", *(float*)((&someObj.cvar) + 4));

(&someObj.cvar) is a pointer to char, so *(&someObj.cvar) is a char. The %f printf specifier expects a double or a float, passing a char is invalid. Note: float when passed in variadic functions as one of the arguments in ellipsis parameter is implicitly converted to double, see ex. cppreference implicit conversions. You have to pass a double or a float to %f, not a char.
Notes:
main(argc,argv)
const char** argv;
{

Don't use implicit int declaration and old, deprecated, obsolete style of function declaration. Use the normal style:
int main(int argc, char **argv) {

*

*printf("%u\n",&someObj.fvar); is undefined behavior. The %u expects unsigned char, not float *. You can print a void* pointer using %p specifier: printf("%p\n", (void*)&someObj.fvar); or cast it to unsinged int: printf("%u\n", (unsigned int)(uintptr_t)(void*)&someObj.fvar);

*C has an macro offsetof declared in stddef.h to access the number of "slack-bytes" (I like the name "padding bytes" better). You can: printf("%f", *(float*)((char*)&someObj + offsetof(struct someStruct, fvar)));


text:
Q: How can i say this? Is it correct? How can i say that something is left. I mean when there are some items left.
Is it:

That's what it's left from the party.

Is that correct?

A:
That's what's left from the party

or

That's what is left from the party


text:
Q: Unbounded sets in infinite-dimensional normed spaces. Let $X$ be an infinte-dimensional normed space. Let $\ell_1,\ldots, \ell_n$ be continuous linear functionals on $X$ and consider the set
$$U = \{x\in X : |\ell_j(x)| < 1,\;\; 1\leq j \leq n\}.$$
Show that the set $U$ is unbounded.
If we put the functionals together to a linear map
$L:X\rightarrow \mathbb{C}$, $L(x) = (\ell_1(x), \ell_2(x),\ldots,\ell_n(x))$.
The kernel of this map is a subspace, right? How would this kernel look? would it be anything else then $x= \textbf{0}$? I seem to be stuck here.

A: Recall that if we have a linear map $T:V\rightarrow W$ where $V,W$ are vector spaces, then:
$$V/\ker(T)\cong \textrm{im}(T). $$ As the image of the map $L$ in question is a subspace of the finite-dimensional space $\mathbb{C}^n$, we can conclude that the kernel of $L$ is nontrivial (and is in fact infinite dimensional).
This is enough to complete the proof that $U$ is unbounded.


text:
Q: VScode regex replace with literal $ in replace string? I am trying to replace css variables with sass variables.
So, find things like var(--blue500);  and replace with $blue500;
But I try find var\(--(.*)\); and replace $$1, the result is $$1.
If I try replace \$$1;, the result is \$1.
If I don't use dollar signs as a test and set the replace to zzzz$1 the result is zzzzblue500
I could do it this way and replace all zzzz with $ in a separate pass, but what am I missing here?

A: You need to escape the $ replacement with $$ and then use the substitution value of $1.
The resulting expression should be: $$$1


text:
Q: Unable to start app with SplashScreen and WebView I'm unable to run my Android app: https://github.com/iSCApps/isc.apps.android.videofy.

I created Splash.java and MainActivity.java.

Splash.java:
package isc.apps.android.videofy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class Splash extends Activity {

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

        final Handler handel = new Handler();
        handel.postDelayed(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent loadSplash = new Intent(Splash.this, MainActivity.class);

                startActivity(loadSplash);

                finish();
            }
        }, 5000);
    }
}

MainActivity.java:
package isc.apps.android.videofy;

    import android.os.Bundle;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.util.Log;
    import android.view.Menu;
    import android.view.Window;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;

public class MainActivity extends Activity {

private WebView webView;
private ProgressDialog progressBar;
private static final String TAG = "Main";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    webView = (WebView) findViewById(R.id.trnity);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);
    final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    progressBar = new ProgressDialog(MainActivity.this);
    progressBar.setMessage("Trinity tuts loading...");
    progressBar.setCancelable(false);
    progressBar.setCanceledOnTouchOutside(false);
    progressBar.show();
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(TAG, "Loading");
            view.loadUrl(url);
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Done loading " + url);
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }

        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            Log.e(TAG, "Error: " + description);
            Toast.makeText(getApplicationContext(),
                    "Oh no! " + description, Toast.LENGTH_SHORT).show();
            alertDialog.setTitle("Error");
            alertDialog.setMessage(description);
            alertDialog.setCancelable(false);
            alertDialog.show();

        }
    });
    webView.loadUrl("https://isc-host.github.io/videos.isc");

}

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

}

The app keeps crashing on my Android 4.0.3.

I also run adb logcat on a Nexus S emulator on Android Studio:
- waiting for device -
error: protocol fault (status read)

Do you know where the code error is?

A: The error could be with this line:
 webView = (WebView) findViewById(R.id.trnity);

In activity_main the id of webView is videofy and in the code its trnity.


text:
Q: Can I set extension policies locally from the registry? I have a Chrome Extension and I added a managed_schema to define a property (SomeSetting) so I can set it via a policy.
manifest.json:
"storage": { "managed_schema": "schema.json" }

schema.json:
"properties": { "SomeSetting": { "type": "string" } }

I can see SomeSetting in chrome://policy/ but I have no idea how to set the value.  Apparently I can do this at HKLM\SOFTWARE\Policies\Google\Chrome\3rdparty\extensions... but I tried and it never is shown as set in chrome://policy/.
Does anyone know if this is suppose to work?  Does it have to be HKCU instead?  Or do I need Active Directory because setting values locally via the registry is not supported?

A: I had a hard time figuring this out.  The documentation is not all that clear.
In order to get your schema to work you need to add a registry entry for "SomeSetting".
Go to the following item in your registry (create the necessary items):
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\3rdparty\extensions\aaaaaaaaaaaaaa\policy

where aaaaaaaaaaaaaa is your extension ID from chrome://extensions
Right-click on "policy" and create a new string value:
Name: SomeSetting
Data: "some value"

Go back to Chrome and reload chrome://policy/
The new policy should appear.
From your extension, you can access the value like this:
chrome.storage.managed.get("SomeSetting", function(setting_val) {
   console.debug(setting_val);
});

I'm not sure if this requires Active Directory to work.

A: It was mentioned in Alternative Extension Distribution Options that:

Google Chrome supports the following extension installation methods:

*

*Using a preferences JSON file (for Mac OS X and Linux only)

*Using the Windows registry (for Windows only)

More information regarding other mechanisms on extensions distribution options can be found in the documentation.


text:
Q: Query to Stored Procedure I have been trying to learn using the Pubs database. I have been trying to figure out how to create a stored procedure to create a profitability column.
The current code I have is this.
SELECT DISTINCT pub_id, ((price * ytd_sales) - advance / 100 * royalty) as [Profit]
FROM titles
WHERE price IS NOT NULL

The two issues I am having are pub_id contains duplicates since they're sorted using title_id and one publisher can publish more than one book.
I am trying to add all the profits together and only have 1 row per publisher. And I am trying to turn that into a stored procedure.

A: Do you mean-
SELECT pub_id, sum((price * ytd_sales) - advance / 100 * royalty) as [Profit]
FROM titles
WHERE price IS NOT NULL
GROUP BY pud_id
ORDER BY pub_id


text:
Q: Is it good to use inner function in a python function to make the logic clear? Below is the basic logic for function foo:
def foo(item_lst):
    val_in_foo_scope = 1

    for item in item_lst:
        # some logic to deal with item
        # val_in_foo_scope used
        pass

    return 0

The logic in the loop can be very complex, in order to make the code more clear, I want to split the logic with a separate function.

With inner function:
def foo(item_lst):
    val_in_foo_scope = 1

    def some_logic(item):
        # val_in_foo_scope used
        pass

    for item in item_lst:
        some_logic(item)

    return 0

With outer function:
def some_logic(item, val):
    # val used
    pass

def foo(item_lst):
    val_in_foo_scope = 1

    for item in item_lst:
        some_logic(item, val_in_foo_scope)

    return 0

The inner function version

*

*val_in_foo_scope can be used directly -- good

*we can easily know that the some_logic is relevant with foo, actually only be used in function foo -- good

*each time function foo is called, a new inner function will be created -- not so good
The outer function version

*

*val_in_foo_scope can not be used directly -- not so good

*we can not see the relevance between some_logic and foo directly -- not so good

*some_logic will be created one time -- good

*there will be so many functions in the global namespace -- not so good

So, which solution is better or is there any other solutions?
Factors below or any other factors you come up with can be considered:

*

*val_in_foo_scope is used or not

*whether the time cost to create inner function each time can be ignored

A: Use lambda if it's a simple function.
Use an inner function if it is complex and you don't want to make it "public".
Use a "private" method if you want to mark it hidden and uses members of the instance.
Use a method if you want to make it "public" and uses members of the instance.
Use a class method if it uses class members.
And lastly use a global function if it's general enough to be used by other classes/functions.

A: You forgot one point in your pro/cons list: testability. Keeping some_logic out of foo makes it testable in isolation, which is important if it's indeed a "complex" (hence very probably critical) function.
As a general rule, only use inner functions when you have both of those conditions: it's trivial stuff  and  passing the required context (the 'outer' function's context) would be a pain.
(nb: I'm of course not talking about using inner functions for closures - like in a decorator - here).


text:
Q: How do I create wp-cron job and access the data? This is my first time trying to write a cron job, so I need some assistance.
I have a PHP function that sorts a bunch of stuff into date order. I want it to run once a day in the background, instead of when the user logs in as a session variable.
I have two questions - how do I create the cron job to call the function, and then what should I do with the sorted array (and how can I access it later)?

A: This is function to schedule cron job in wordpress:
http://codex.wordpress.org/Function_Reference/wp_schedule_event
You have to store the sorted array in some way, for example serialize it and save in db or file, then you can read it. This only makes sense if the query is very heavy.
Enjoy your code!


text:
Q: Alias WB name for vlookup I need to assign an alias to a WB because of its changing name and I need to use this alias in a vlookup. I have used a few examples found online without success.
Here is what I have at this point:
' assigns an alias to the workbook since the file name changes
Set AllAcctsWB = ThisWorkbook
AllAcctsWB.Activate

' switches to the correct WB for the vlookup to occur
InfluencerWB.Activate

' counts the number of used rows in this sheet
LastRowA = Range("A1").End(xlDown).Row

' selects the starting point for the vlokup
Range("F2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-5], '[" & AllAcctsWB & "]Filtered _
    data'!C1:C31,31,0)"

' fills the column to the length of column A
Selection.AutoFill Destination:=Range("F2:F" & LastRowA)

Any useful advice or guidance is definitely welcome.
In advance, thanks for the assistance.

A: ThisWorkbook returns a Workbook object corresponding to the current workbook, not the name of the current workbook.
To reference the name of the current workbook, use ThisWorkbook.Name


text:
Q: Получение разметки веб страницы без участия браузера Для того, чтобы получить html разметку страницы и её содержимое, написал небольшое приложение на NET C#. Помогла библиотека WatiN. Например:
using (var browser = new IE("http://www.адрес_страницы.ru/"))
{
   //Выполняемый код. Вызываем методы для парсинга страницы
}

Парсинг так можно делать, НО минус в том, что участвует браузер, т.е. дополнительное звено, которое может давать дополнительные ошибки.
Вопрос такой - есть есть ли библиотеки, инструменты, которые позволяют делать запрос к странице, веб-ресурсу без участия браузера, получать её содержимое и парсить. Отправляем запрос - получили html.
Буду очень признателен за помощь!

A: HttpClient
static async void DownloadPageAsync()
{
    // целевой сайт
    string page = "http://ru.stackoverflow.com/";

    // используем HttpClient
    using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
            using (HttpContent content = response.Content)
            {
                // читаем содержимое как текст
                string result = await content.ReadAsStringAsync();

                // делаем что-то полезное
                if (result != null)
                {

                }
            }
}

Есть еще WebClient, но уже считается как бы слегка устаревшим что-ли, ну в общем HttpClient вам в руку.


text:
Q: What is the input format of fastText and why does my model doesn't give me a meaningful similar output? My goal is to find similarities between a word and a document. For example, I want to find the similarity between "new" and a document, for simplicity, say "Hello World!".
I used word2vec from gensim, but the problem is it does not find the similarity for an unseen word. Thus, I tried to use fastText from gensim as it can find similarity for words that are out of vocabulary.
Here is a sample of my document data:
[['This', 'is', 'the', 'only', 'rule', 'of', 'our', 'household'],
 ['If',
  'you',
  'feel',
  'a',
  'presence',
  'standing',
  'over',
  'you',
  'while',
  'you',
  'sleep',
  'do'],
 ['NOT', 'open', 'your', 'eyes'],
 ['Ignore', 'it', 'and', 'try', 'to', 'fall', 'asleep'],
 ['This',
  'may',
  'sound',
  'a',
  'bit',
  'like',
  'the',
  'show',
  'Bird',
  'Box',
  'from',
  'Netflix']]

I simply train data like this:
from gensim.models.fasttext import FastText

model = FastText(sentences_cleaned)

Consequently, I want to find the similarity between say, "rule" and this document.
model.wv.most_similar("rule")
However, fastText gives me this:
[('the', 0.1334390938282013),
 ('they', 0.12790171802043915),
 ('in', 0.12731242179870605),
 ('not', 0.12656228244304657),
 ('and', 0.11071767657995224),
 ('of', 0.08563747256994247),
 ('I', 0.06609072536230087),
 ('that', 0.05195673555135727),
 ('The', 0.002402491867542267),
 ('my', -0.009009800851345062)]

Obviously, it must have "rule" as the top similarity since the word "rule" appears in the first sentence of the document. I also tried stemming/lemmatization, but it doesn't work either.
Was my input format correct? I've seen lots of documents are using .cor or .bin format and I don't know what are those.
Thanks for any reply!

A: model.wv.most_similar('rule') asks for that's model's set-of-word-vectors (.wv) to return the words most-similar to 'rule'. That is, you've provided neither any document (multiple words) as a query, nor is there any way for the FastText model to return either a document itself, or a name of any documents. Only words, as it has done.
While FastText trains on texts – lists of word-tokens – it only models words/subwords. So it's unclear what you expected instead: the answer is of the proper form.
Those don't look like words very-much like 'rule', but you'll only get good results from FastText (and similar word2vec-algorithms) if you train them with lots of varied data showing many subtly-contrasting realistic uses of the relevant words.
How many texts, with how many words, are in your sentences_cleaned data? (How many uses of 'rule' and related words?)
In any real FastText/Word2Vec/etc model, trained with  asequate data/parameters, no single sentence (like your 1st sentence) can tell you much about what the results "should" be. That only emerged from the full rich dataset.


text:
Q: Double assigned shortcut key when using firefox In Firefox, I can press Ctrl+L to jump to the URL box.
When I am in the edit post box on Stack Exchange sites, Ctrl+L creates a link in the edit box, instead of jumping to the URL box.
I don't want to change the key settings in either firefox or in Stack Exchange editing box.
I wonder if I can add some escape modifier key before ctrl+L to jump to Firefox URL box in this case?

A: Use F6 to go to the URL box. Or press Tab (to go to the tags box) and then Ctrl+L may work?