text:
Q: Why do we need to have Object class as baseclass for all the classes? Either in C# or Java or in any other language which follows oops concepts generally has 'Object' as super class for it by default. Why do we need to have Object as base class for all the classes we create?
When multiple inheritance is not possible in a language such as C# or Java how can we derive our class from another class when it is already derived from Object class. This question may look like silly but wanted to know some experts opinions on it.

A: The fact that every class inherits object ensured by the compiler.
Meaning that is you write:
class A {}

It will compile like:
class A : Object{}

But if you state:
class B : A {}

Object will be in the hierarchy of B  but not directly - so there is still no multiple inheritance.

A: In short
1) The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
2) You can have B extend C, and A extend B.  A is the child class of B, and B is the child class of C.  Naturally, A is also a child class of C.

A: Well, the multiple inheritance of Object does not apply - you can think of it as:
"If a type doesn't have a base type, then implicitly inject Object".
Thus, applying the rule ad-nauseam, all types inherit from object once and once only - since at the bottom of the hierarchy must be a type that has no base; and therefore which will implicitly inherit from Object.
As for why these languages/frameworks have this as a feature, I have a few reasons:
1) The clue's in the name 'Object Oriented'.  Everything is an object, therefore everything should have 'Object' (or equivalent) at it's core otherwise the design principle would be broken from the get-go.
2) Allows the framework to provide hooks for common operations that all types should/might need to support.  Such as hash-code generation, string output for debugging etc etc.
3) It means that you can avoid resorting to nasty type casts that can break stuff - like (((int *)(void*))value) - since you have a nice friendly supertype for everything
There's probably loads more than this - and in the time it's taken me to write this 6 new answers have been posted; so I'll leave it there and hope that better people than I can explain in more detail and perhaps better :)

A: Having a single-rooted type hierarchy can be handy in various ways. In particular, before generics came along, it was the only way that something like ArrayList would work. With generics, there's significantly less advantage to it - although it could still be useful in some situations, I suspect. EDIT: As an example, LINQ to XML's construction model is very "loose" in terms of being specified via object... but it works really well.
As for deriving from different classes - you derive directly from one class, but that will in turn derive indirectly from another one, and so on up to Object.
Note that the things which "all objects have in common" such as hash code, equality and monitors count as another design decision which I would question the wisdom of. Without a single rooted hierarchy these design decisions possibly wouldn't have been made the same way ;)

A: Regarding the first part of your question, it's how classes receive common properties and methods. It's also how we can have strongly-typed parameters to functions that can accept any object.
Regarding your second question, you simply derive your class from the other class; it will then be a descendant of that class, which is in turn a descendant of Object. There's no conflict.

A: You have the Object base class because amongst others because the Object class has methods (like, in .NET, GetHashCode(), which contain common functionality every object should have).
Multiple inheritance is indeed not possible, but it is possible to derive class A from class B, because A may not directly derive from Object, but B does, so all classes ultimately derive from Object, if you go far enough in the class' inheritance hierarchy.

A: Just to compare, let's take a look at a language that doesn't enforce a single root class - Objective-C. In most Objective-C environments there will be three root classes available (Object, NSObject and NSProxy), and you can write your own root class by just not declaring a superclass. In fact Object is deprecated and only exists for legacy reasons, but it's informative to include it in this discussion. The language is duck typed, so you can declare a variable's type as "any old object" (written as id), then it doesn't even matter what root class it has.
OK, so we've got all of these base classes. In fact, even for the compiler and runtime libraries to be able to get anywhere they need some common behaviour: the root classes must all have a pointer ivar called isa that references a class definition structure. Without that pointer, the compiler doesn't know how to create an object structure, and the runtime library won't know how to find out what class an object is, what its instance variables are, what messages it responds to and so forth.
So even though Objective-C claims to have multiple root classes, in fact there's some behaviour that all objects must implement. So in all but name, there's really a common primitive superclass, albeit one with less API than java.lang.Object.
N.B. as it happens both NSObject and NSProxy do provide a rich API similar to java.lang.Object, via a protocol (like a Java interface). Most API that claims to deal with the id type (remember, that's the "any old object" type) will actually assume it responds to messages in the protocol. By the time you actually need to use an object, rather than just create it with a compiler, it turns out to be useful to fold all of this common behaviour like equality, hashing, string descriptions etc. into the root class.

A: Well multiple inheritance is a totally different ball game.
An example of multiple inheritance:-
class Root
{
public abstract void Test();
}

class leftChild : Root
{
public override void Test()
{
}
}

class rightChild : Root
{
public override void Test()
{
}
}

class leafChild : rightChild, leftChild
{
}

The problem here being leafChild inherits Test of rightChild and leftChild. So a case of conflicting methods. This is called a diamond problem.
But when you use the object as super class the hierarchy goes like this:-
class Object
    {
        public abstract void hashcode();
        //other methods
     }

    class leftChild : Object
    {
    public override void hashcode()
    {
    }
    }

    class rightChild : Object
    {
    public override void hashcode()
    {
    }
    }

So here we derive both classes from Object but that's the end of it.

A: It acts like a template for all the objects which will derive from it, so that some common functionality required by every object is provided by default. For example cloning, hashcode and object locking etc.


text:
Q: text wrapping and vertical alignment of text in a table http://en.wikibooks.org/wiki/LaTeX/Tables contains an example on how to do text wrapping in tables by using p{5cm}:
\begin{center}
    \begin{tabular}{ | l | l | l | p{5cm} |}
    \hline
    Day & Min Temp & Max Temp & Summary \\ \hline
    Monday & 11C & 22C & A clear day with lots of sunshine.
    However, the strong breeze will bring down the temperatures. \\ \hline
    Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells
    across most of Scotland and Northern Ireland,
    but rain reaching the far northwest. \\ \hline
    Wednesday & 10C & 21C & Rain will still linger for the morning.
    Conditions will improve by early afternoon and continue
    throughout the evening. \\
    \hline
    \end{tabular}
\end{center}

How do I get the contents of the cells in that column to be centered?
Here is what I have tried:
\begin{table}[h]
\centering
\resizebox{\textwidth}{!}{%
\begin{tabular}{p{20cm}}
\rowcolor[HTML]{3166FF}
\pbox{
\Huge Line 1 of my long title
\\ \Huge Line2 of my long title} \\ \hline
\huge Sub title
\end{tabular}
}
\end{table}

I want to achieve something like this from Word:

I have gotten closer, but it still doesn't look professional in LaTeX:
\begin{table}[h]
\centering
\resizebox{\textwidth}{!}{%
 \begin{tabular}{p{13cm}}
 \rowcolor[HTML]{3166FF}
 \centering \Huge This is a very long title that spans multiple lines \\ \hline
 \centering \huge Sub title
 \end{tabular}
}
\end{table}

A: Use \newcolumntype from array package and define a style, say C with automatic wrapping and centering.
The principle way to define a new column type to use one of existing ones, i.e. l, r, p or c.
The syntax is (with an argument)
\newcolumntype{Y}[1]{>{some stuff before\arraybackslash}Z{#1}}, where Y stands for the new letter, Z is one of already existing types.
Just before \arraybackslash, basically anything can be inserted, say a \centering, so this will be used inside the Z - type.
Edit Some propositions to improve the look of the table.
\documentclass{article}
\usepackage{siunitx}
\usepackage{booktabs}
\usepackage{array}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}

\begin{document}

\begin{center}

    \begin{tabular}{l*{2}{C{2cm}}C{5cm}}
      \multicolumn{4}{c}{ \large \textbf{ The good table...}} \tabularnewline[2ex]

      \toprule
    Day & Min Temp (\si{\degreeCelsius}) & Max Temp (\si{\degreeCelsius})  & Summary \tabularnewline
    \midrule
    Monday & 11 & 22 & A clear day with lots of sunshine.
    However, the strong breeze will bring down the temperatures. \tabularnewline[1ex]
    Tuesday & 9 & 19 & Cloudy with rain, across many northern regions. Clear spells
    across most of Scotland and Northern Ireland,
    but rain reaching the far northwest. \tabularnewline[1ex]
    Wednesday & 10 & 21 & Rain will still linger for the morning.
    Conditions will improve by early afternoon and continue
    throughout the evening. \tabularnewline[1ex]
    \bottomrule
    \end{tabular}
\end{center}

\begin{center}
    \begin{tabular}{ | l | l | l | C{5cm} |}
      \multicolumn{4}{c}{ \large \textbf{ and the bad and ugly...}} \tabularnewline[2ex]
    \hline
    Day & Min Temp & Max Temp & Summary \tabularnewline \hline
    Monday & 11C & 22C & A clear day with lots of sunshine.
    However, the strong breeze will bring down the temperatures. \tabularnewline \hline
    Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells
    across most of Scotland and Northern Ireland,
    but rain reaching the far northwest. \tabularnewline \hline
    Wednesday & 10C & 21C & Rain will still linger for the morning.
    Conditions will improve by early afternoon and continue
    throughout the evening. \tabularnewline
    \hline
    \end{tabular}
\end{center}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS positioning problem I have some html that is inserted dynamically with javascript. I have position:absolute; so that it does not affect the layout of the page elements. However, when a flash message appears on the top of the page, all of the elements shift down except for the absolutely positioned element. So it seems that I want to combine properties of absolute and relative positioning. How do I do this?

A: Add position:relative; to the highest-level element which you think describes "the page". For example:

        ...
            ...

            ...
        ...

edit: This is an excellent demo by thirtydot which perfectly illustrates the concept: http://jsfiddle.net/qGTw6

A: Add position: relative to a parent element of your absolutely positioned element.
Make sure your "flash message" is outside this element.


text:
Q: How do I stop csslint and jshint from linting my EJS in Atom? I'm editing EJS files in Atom. I currently have linter-csslint and linter-jshint packages installed. Both seem to be recognising the .ejs files as .html and linting it as HTML.
This is what I see

How do I get the linters to ignore .ejs files? Or is there a EJS specific linter for Atom?

A: You can ignore all .ejs files with a .jshintignore file (https://jshint.com/docs/cli/#ignoring-files). I've just added one myself to fix this same issue in Atom and it seems to have worked.
I created ~/.jshintignore with the following content:
*.ejs

Worth noting that this affects anything else using jshint.

A: Based on that photo, it appears that you installed the language-ejs package and it is taking precedence on identifying the language. The problem here is not actually the linters, but rather the language-html package.
In the scopes for linter-csslint and linter-jshint, we see that both will lint on language-html scopes. However, your file is in the language-ejs scope. What is happening here is that Atom should be locking the scope down to just language-ejs, but is instead mixing between that and language-html. The reason that language-html is also a scope here is seen here.
So fixing this for yourself is actually pretty easy. You can open up the source code for the language-html package locally (should be in ~/.atom/packages/language-html/grammars/html.cson) and remove the ejs line that I showed above. However, the better long term fix is to probably raise an issue on language-html that you do not believe ejs is within the grammar scope of html. Also, Atom should probably not be identifying files as having multiple grammar scopes, but that is a more difficult issue to pursue.
PR to fix this permanently is here.

A: You could just go to the packages and disable that particular package.


text:
Q: How to split (and store) data from text file? I have a text file that isformatted where there is data that is being separated with ; (for example apples;oranges;grapes), and I need to split the list into 3 separate items (apples, oranges, grapes). So far my code is as follows
doc = open("doc.txt", "r")
alist = []
line = doc.readline()
line = line.strip()
stuff = line.split(";")
alist.append(stuff)
print(alist)
print(len(alist))

But the output is just all the items in the list stores as one element ["Apples", "Oranges", "Grapes] with the len() of 1
I would need them to be separated so that I could use formatting when printing
Thanks for the help! :)

A: its because you are using append which inserts whole list at the rear end of list instead use extend as below example might be useful to differentiate both:
>>> a = []
>>> a.extend([1,2,3])
>>> a
[1, 2, 3]
>>> a.append([4,5,6])
>>> a
[1, 2, 3, [4, 5, 6]]
>>>

A: You can use a for loop to append each item one by one.
for i in stuff:
    alist.append(i)


text:
Q: How to TEST button initiated page redirect I'm new to Salesforce and I'm trying to write some tests for our code. There is a button redirect initiated from the Visualforce page:
<apex:page standardController="Happening__c" extensions="HappeningNewActionEvent" standardStyleSheets="false" sidebar="false" showHeader="false" action="{!init}">

Here is the apex code:
public with sharing class HappeningNewActionEvent {

private ApexPages.StandardController stdController;
public HappeningNewAction(ApexPages.StandardController stdController) {
    this.stdController = stdController;
}

public PageReference init() {
    company__Happening_New_Happeninig_Event__c happening = new company__Happening_New_Happeninig_Event__c(
        company__happening__c = stdController.getRecord().Id
    );

    PageReference page = new ApexPages.StandardController(happening).view();
    page.setRedirect(true);
    return page;
}
   }

To my understanding the controller redirects the page to the happening ID. I'm however having a hard time being able to replicate the ID on my test class:
@isTest
    private with sharing class HappeningNewActionEventUnitTest {

    static testMethod void TestRedirect(){
    PageReference pf  = Page.HappeningnNewActionEvent;
    Test.setCurrentPage(pf);

    company__Happening_Eveny__c newHE = new company__Happening_Event__c();

    ApexPages.StandardController sc = new ApexPages.StandardController(newHE);
    HappeningNewActionEvent controller = new HappeningNewActionEvent(sc);
    String nextPage = controller.init().getUrl();

    //Verify that page fails without parameters
    System.assertNotEquals('/apex/failure=error=noParam', nextPage);

    //Verify that  page displays.
    System.assertEquals('/apex/happeningnewactionevent', nextPage);

}
 }

I'm having a bit hard time with the test. the controller.init().getURL() returns a null so I obviously cant get the ID forward, but as I'm a bit new with salesforce I cant find how to test for this.
Thanks.


text:
Q: Reading from XML, for loop issue The code below reads from the XML but the loop runs another time which prints null values.
Im searching inside the root ax, to display the attribute value increment, the first time it displays the correct value but it also runs another time and displays empty string
XML:
<?xml version="1.0" encoding="utf-8"?>
<config>
  <ax>
    <position start="23" increment="2" />
    <config server="127.0.0.1" location="er" />
  </ax>
  <pl>
    <position start="98" y="0.0"  />
    <config server="60" system="pop" />
  </pl>
</config>

Code:
XmlDocument document = new XmlDocument();
document.Load("config.xml");

foreach (XmlElement element in document.SelectNodes("//ax"))
{
    foreach (XmlElement element1 in element)
    {
        string incrementBy = element1.GetAttribute("increment");
        MessageBox.Show(incrementBy);
    }
}

First time it displays the right value 2, it runs second time as-well and displays null! It should run once since I have clearly mentioned SelectNode("//ax").

A: figured it out, I should check whether it has the attribute or not
     if (element1.HasAttribute("increment"))
                    {
                        string incrementBy = element1.GetAttribute("increment");
                        MessageBox.Show(incrementBy);

                    }

A: You can parse this xml with Linq (assume you there can be no child elements with increment attribute):
XDocument xdoc = XDocument.Load("config.xml");
var element = xdoc.Root.XPathSelectElement("ax/*[@increment]");
if (element != null)
{
   int increment = (int)element.Attribute("increment");
   // ...
}

Or without XPath:
var element = xdoc.Root.Elements("ax").Elements()
                  .FirstOrDefault(e => e.Attribute("increment") != null);

A: If you want to get all increment values, you can do the following using LINQ to XML
var increments = XDocument.Load("config.xml")
                 .Descendants()
                 .Where(x => x.Attribute("increment") != null)
                 .Select(x=> (string)x.Attribute("increment"));


text:
Q: Editor role cannot save custom theme options There's a few questions on this site referencing this issue and I've read them and applied the proposed solutions to no avail.
I've made a very simple theme options page that appears for the Editor role but when an Editor tries to save the options they get the "Cheatin 'Uh?" message.
The following is my options code:
<?php
function map_register_settings() {
    add_option( 'map_zoom', '1');
    add_option( 'map_longitude', 'alpha');
    register_setting( 'default', 'map_zoom' );
    register_setting( 'default', 'map_longitude' );
    register_setting( 'default', 'map_latitude' );
}
add_action( 'admin_init', 'map_register_settings' );

function map_register_options_page() {
    add_theme_page('Map Center', 'Map Center', 'edit_theme_options', 'map-options', 'map_options_page');
}
add_action('admin_menu', 'map_register_options_page');

function map_options_page() {
    ?>

Map Center Options

    <form method="post" action="options.php">
        <?php settings_fields( 'default' ); ?>

                    Zoom Level (1 - 21):

                    <input type="text" id="map_zoom" name="map_zoom" value="<?php echo get_option('map_zoom'); ?>" />

                    Latitude:
                    <input type="text" id="map_latitude" name="map_latitude" value="<?php echo get_option('map_latitude'); ?>" />

                    Longitude:
                    <input type="text" id="map_longitude" name="map_longitude" value="<?php echo get_option('map_longitude'); ?>" />

        <?php submit_button(); ?>
    </form>

<?php
}
?>

I've also added the following to my functions file in an attempt to give the editor role the necessary capability:
//ALLOW EDITOR TO CHANGE MAP CENTER
 // get the the role object
   $editor = get_role('editor');
   // add $cap capability to this role object
   $editor->add_cap('edit_theme_options');

A: There's a bug(ish) report regarding this here:
http://make.wordpress.org/themes/2011/07/01/wordpress-3-2-fixing-the-edit_theme_optionsmanage_options-bug/
You can use a filter to modify the theme page capability. First you'll want to edit your register_setting() calls to look like this:
register_setting( 'map-options', 'map_zoom' );
register_setting( 'map-options', 'map_longitude' );
register_setting( 'map-options', 'map_latitude' );

The first parameter is the settings group and this is what we're filtering the capabilities for.
Second is to add the filter:
add_filter( 'option_page_capability_map-options', 'sewp_114719_map_options_capability' );
function sewp_114719_map_options_capability( $cap ) {
    return 'edit_theme_options';
}

That should do it.
You may be able to use the customiser instead if it makes sense to, not sure if editors can use that off the top of my head though.

A: This plugin may help. Allows you to edit, create, and delete roles as well as capabilities for these roles.


text:
Q: Nginx Reverse proxy to Sonarqube not working. Getting 500 eror Using docker-compose file spinned up 3 docker containers i.e nginx,sonarqube & postgres
docker-compose file below :
version: "3.3"
services:
sonarqube:
container_name: sonarqube_9
 image: sonarqube:9-community
 restart: always
 ports:
    - "9000"

 networks:
   - sonarnet
 depends_on:
    - db
 environment:
     SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
     SONAR_JDBC_USERNAME: sonar
     SONAR_JDBC_PASSWORD: sonar
 volumes:
   - /data/docker-volumes/sonarqube/conf:/opt/sonarqube/conf
   - /data/docker-volumes/sonarqube/data:/opt/sonarqube/data
   - /data/docker-volumes/sonarqube/extensions:/opt/sonarqube/extensions
   - /data/docker-volumes/sonarqube/bundled-plugins:/opt/sonarqube/lib/bundled-plugins

db:
  image: postgres:14
  restart: always
  ports:
    - 5432:5432
  networks:
    - sonarnet
  environment:
    POSTGRES_USER: sonar
    POSTGRES_PASSWORD: sonar
  volumes:
    - /data/docker-volumes/postgresql:/var/lib/postgresql
    - /data/docker-volumes/postgresql/data:/var/lib/postgresql/data

reverse_proxy:
  container_name: reverse_proxy
depends_on:
  - sonarqube
image: nginx:latest
networks:
  - sonarnet
ports:
  - 80:80
  - 443:443
restart: always
volumes:
    - /data/docker-volumes/nginx/conf:/etc/nginx/conf.d/

networks:

 sonarnet:
   name: sonarnet
  driver: bridge

.......................................
Inside nginx container inside default.config file for reverse proxy
server
{
listen       80;
server_name  localhost:9000;

location / {

  proxy_pass http://127.0.0.1:9000;

}

}
When on browser trying to access http://localhost:80
we are getting error 500 on screen
in logs we are getting
User_Client: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
"Request: GET / HTTP/1.1
Status: 502
Request_URI: /
Host: localhost

A: localhost within nginx container refers to nginx itself. You need to use container name as proxy_pass, e.g. proxy_pass http://sonarqube_9:9000;.


text:
Q: All initial segments of a list in Prolog Q)Find all initial segments of the given list [1, 3, 6 ,9, 8]. i.e. [], [1], [1,3],[1,3,6]
I'm stuck on how to construct the recursive call to segments,I know I have to use an append function but not sure how to bring it all together, I have the following code:
append([], L, L).
append([H|L1], L2, [H|L3]):-
  append(L1, L2, L3).

segments([],[]).
segments([H|L1],R):-

A: Note that @gusbro's solution with append/3 as well as @brebs answer work well if the initial list is given, however, both permit also other solutions that are not lists.
?- L = [1|non_list], append(Segment, _, L).
   L = [1|non_list], Segment = []
;  L = [1|non_list], Segment = [1]
;  false.
?- L = non_list, append(Segment, _, L).
   L = non_list, Segment = []
;  false.

So even non_list works ; that is a term that is as far remote from a list as possible. Often such extra unwanted generalizations are accepted, in particular if you know that you will never rely upon it. Also this is know as a list prefix of a term.
But if you want to be sure that only lists are considered, use Prolog's dcg-formalism which is the method of choice in many areas.
:- set_prolog_flag(double_quotes, chars). % to make "strings" readable

... --> [] | [_], ... . % any sequence

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

segment_of(Xs, Zs) :-
   phrase((seq(Xs), ...), Zs).

?- segment_of(Xs, "abc").
   Xs = []
;  Xs = "a"
;  Xs = "ab"
;  Xs = "abc"
;  false.
?- segment_of(Xs, non_list).
   false.
?- segment_of("ab", L).
   L = "ab"
;  L = [a,b,_A]
;  L = [a,b,_A,_B]
;  L = [a,b,_A,_B,_C]
;  ... .

A: Without using append:
% Inc can be an empty list, if Lst is a list (empty or not)
increasing_list([], []).
increasing_list([_|_], []).

increasing_list(Lst, Inc) :-
    increasing_list_(Lst, Inc).

% Unify Inc with the current element (Head) of Lst
increasing_list_([Head|_Tail], [Head]).

% Add Head element from Lst to Inc
increasing_list_([Head|Tail], [Head|Inc]) :-
    % Loop through the elements in Lst
    increasing_list_(Tail, Inc).

Result in swi-prolog:
?- increasing_list([1, 3, 6 ,9, 8], Inc).
Inc = [] ;
Inc = [1] ;
Inc = [1,3] ;
Inc = [1,3,6] ;
Inc = [1,3,6,9] ;
Inc = [1,3,6,9,8]


text:
Q: Prove by Hilbert deduction: ⊢∃x(AvB)→(∃xAv∃xB); ⊢(∃xAv∃xB)→∃x(AvB) I'd really like your help proving:
1)⊢∃x(AvB)→(∃xAv∃xB)
2)⊢(∃xAv∃xB)→∃x(AvB)
Our proof system contains next Hilbert's axioms:
1.A→(B→A)
2.(A→B)→((A→(B→X))→(A→X))
3.(A&B)→A
4.(A&B)→B
5.(A→B)→((A→X)→(A→(B&X)))
6.A→(AvB)
7.A→(BvA)
8.(A→X)→((B→X)→((AvB)→X))
9.(A→B)→((A→¬B)→¬A)
10.¬¬A→A
And other two axioms: ∀xA→A{t/x}, A{t/x}→∃xA where t is free for assignment instead of x in A.
Finally theres the MP rules:
1.From A,A→B we conclude B
2.From A→B we conclude A→∀xB, where x not included in the set of variables A free
3.From A→B we conclude ∃xA→B, where x not included in the set of variables A free
I tried couple of different ways but didn't come with any smart result.

A: About the first formula :
a) $A \rightarrow \exists x A$ --- 2nd Axiom for quantifiers
b) $\exists x A \rightarrow ( \exists x A \lor \exists x B )$ --- from your 6)
c) $ [ \exists x A \rightarrow ( \exists x A \lor \exists x B ) ] \rightarrow [ A \rightarrow ( \exists x A \rightarrow ( \exists x A \lor \exists x B ) ) ] $ --- from your 1)
d) $ A \rightarrow ( \exists x A \rightarrow ( \exists x A \lor \exists x B ) ) $ --- from b) and c) by MP
e) $ A \rightarrow ( \exists x A \lor \exists x B ) $ --- from a) and d) using your 2) by MP twice
In the same way, you can get :
f) $ B \rightarrow ( \exists x A \lor \exists x B ) $ --- using your 7)
g) $ ( A \lor B ) \rightarrow  ( \exists x A \lor \exists x B ) $ --- from e) and f) using your 8) by MP twice
Now you can get :
h) $ \exists x ( A \lor B ) \rightarrow  ( \exists x A \lor \exists x B ) $ --- from g) using your rule 3) ( because $x$ is not free in $( \exists x A \lor \exists x B )$ ).
Following a similar approach, you can try with the second formula.


text:
Q: CTRL+mouse wheel in gvim (windows) not paging I'm loving vim, but one thing that's bugging me is that when I hold the control key and mouse wheel up or down, the window scrolls normally when the bindings are telling it to page up/down.
I'm using the exact same vimrc file (and plugins) on one of my linux machines and the CTRL+mouse wheel does page up down (as opposed to just normally scrolling like in windows).
Is there some way to force gvim to response to a ctrl+MouseUp/Down event? It seems to be ignoring it in windows ='[

A: In insert mode, pressing <Ctrl+V>, holding <Ctrl>, and then scrolling with the mouse doesn't input an escape sequence, which implies that it's not possible to remap actions from the scroll wheel. Compare, for example, <Ctrl+V> then <Ctrl> with a left click, which inserts <C-LeftMouse>. There doesn't seem to be anything in the help about mouse events beyond the clicks either.


text:
Q: InnoSetup - Set DefaultDirName at runtime I have an application that needs to allow for up to three simultaneous installations on the same machine.
For some reason, the following code behaves as if UsePreviousAppDir is set to yes.  The second time I install the app, the path ends up mangled.
The value I want to see is
C:\Our App\install_x where x corresponds to the user's selection.
It works the first time, but the second run results in something like this:
C:\Our App\install_x\install_y, where x corresponds to the value selected with the first installation and y corresponds to the value selected during this installation.
The install version is a radio button selection grabbed from the first screen in the installer.  How do I eliminate this issue?
Setup section:
[Setup]
AppName=Our App
AppId=Our App
AppVerName=Our App Version(CM)
DefaultDirName=C:\Our App
DefaultGroupName=Our Group Name
OutputDir=..\
OutputBaseFilename=mm_setup
DisableStartupPrompt=yes
Compression=zip
UsePreviousAppDir=no
VersionInfoDescription=Our App Setup
CreateUninstallRegKey=no
DirExistsWarning=no

And the method where I set the install version:
procedure gSetVersion;
begin
  if gVersionPage.SelectedValueIndex = 0 then
  begin
     gInstallArea := 'install_a';
  end
  else if gVersionPage.SelectedValueIndex = 1 then
  begin
     gInstallArea := 'install_b';
  end
  else if gVersionPage.SelectedValueIndex = 2 then
  begin
     gInstallArea := 'install_c';
  end
  WizardForm.DirEdit.Text := WizardDirValue + '\' + gInstallArea;
end;

A: Solved the problem via the following hack.  Not sure why it was necessary to manually edit the string when the `UsePreviousAppDir=no' was set, but this works
procedure gSetVersion;
var
   installVersionIndex: Integer;
   installDir: String;
begin
  case gVersionPage.SelectedValueIndex of
    0: gInstallArea := 'install_a';
    1: gInstallArea := 'install_b';
    2: gInstallArea := 'install_c';
  end

  //Set the default installation folder.
  //This is necessary because InnoSetup intermittently
  //ignores the 'UsePreviousAppDir=no' [Setup] directive
  //and because the 'DefaultDirName' directive gets populated
  //prior to the user selecting the install version
  installVersionIndex := Pos('install_', WizardDirValue);
  installDir := WizardDirValue;
  if installVersionIndex > 0 then
  begin
    Delete(installDir, installVersionIndex, 20);
  end

  WizardForm.DirEdit.Text := installDir + '\' + gInstallArea;
end;


text:
Q: Cache-Control + mod_expires setup at .htaccess but leverage browser cache still do not work I've fine tuned the .htaccess file but could not make the Leveraged Browser Cache to work. GTMetrix tells me several .png and .svg images have no Expiration set.
1. Expires_module is enabled and running in Apache
2. Set Cache-Control and Enable Browser Cache are setup at the .htaccess.
The .htaccess code is below. Any advice to make browser caching work is welcome. :-)
#Set Cache-Control
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|svg|js|css|swf)$">
Header set Cache-Control "max-age=84600, public"
#End Cache-Control
</FilesMatch>
#Enable browser cache
<IfModule mod_expires.c>
  ExpiresActive On

  # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>
#End browser cache
#Enable HSTS

A: you need to ensure to Enable mod_expires on CentOS and Ubuntu,
Run following command on your CentOS system to see if Apache module mod_expires is enabled or not, It should show following output if enabled, otherwise you'll see nothing in output.
httpd -M | grep expires

Another way to verify it is via httpd.conf file, open apache configuration file in your favorite text editor application (Vi/ViM, Nano etc) and search for following line.  If successfully found, then your Apache has  mod_expires enabled.
LoadModule expires_module modules/mod_expires.so

For Ubuntu system, we need to use a2enmod utility to enable Apache modules, simply run following command to enable expires module on Ubuntu.
sudo a2enmod expires

Once done, we need to restart apache for this change to take effect.
sudo /etc/init.d/apache2 restart

or
sudo service apache2 restart

Then go to GTmetrics or Google PageSpeed and test your url for "Browser Leverage caching" and check if cache time is updated as per your entry in .htaccess


text:
Q: Laravel Query in if else converting to common query this is my code I want to convert this query in to a common query
 if ($limit == 0) {
   $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->get();
   } else {
  $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->limit($limit)->get();
            }

A: You can save the query in a variable above the if/else statement. So something like this would work. Now if this is not the answer you are looking for please specify what you mean by common query!
$query = WebhookErrorNotification::where('is_error', true)->orderByDesc('id');
if ($limit == 0) {
  $response = $query->get();
} else {
  $response = $query->limit($limit)->get();
}

A: you can do something like this
$response = WebhookErrorNotification::where('is_error', true)
    ->when($limit !== 0, function ($query) use ($limit) {
        $query->limit($limit);
    })->orderByDesc('id')->get();


text:
Q: Vb.net project with c# fluent nHibernate mappings project Having successfully tried out nHibernate, I would now like to try using Fluent for mapping.  My main project is in vb.net but I would really like to use c# for the mappings since the lambda expression capability makes it much cleaner.  Can you have a separate project/assembly for your mapping files without creating a circular dependency with domain objects?

A:
Can you have a separate
  project/assembly for your mapping
  files without creating a circular
  dependency with domain objects?

Yes, your domain objects are not (and should not be) dependent on the NHibernate mappings, whether they be defined the traditional way (.hbm.xml files) or with Fluent.  You can safely store these mappings in another assembly, and they only need to be referenced by your data access layer (DAL) and your executable project.  Since your domain objects don't need a reference to your DAL, it works just fine.
Just follow the instructions at Fluent's Wiki and in the same assembly where you defined your CreateSessionFactory() method, you'll need a reference to your mapping project.
-Doug


text:
Q: How to use a  virtual event with tkinter I am using a tkk.Combobox themed widget in Python 3.5.2.  I want an action to happen when a value is selected.
In the Python docs, it says:

The combobox widgets generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.

Here on the Stack, there are a number of answers (1, 2, etc) that show how to bind the event:
cbox.bind("<<ComboboxSelected>>", function)

However, I can't make it work.  Here's a very simple example demonstrating my non-functioning attempt:
import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)

cbox.bind("<<ComboboxSelected>>", print("Selected!"))

tkwindow.mainloop()

I get one instance of "Selected!" immediately when I run this code, even without clicking anything.  But nothing happens when I actually select something in the combobox.
I'm using IDLE in Windows 7, in case it makes a difference.
What am I missing?

A: The problem is not with the event <<ComboboxSelected>>, but the fact that bind function requires a callback as second argument.
When you do:
cbox.bind("<<ComboboxSelected>>", print("Selected!"))

you're basically assigning the result of the call to print("Selected!") as callback.
To solve your problem, you can either simply assign a function object to call whenever the event occurs (option 1, which is the advisable one) or use lambda functions (option 2).
Here's the option 1:
import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)

def callback(eventObject):
    print(eventObject)

cbox.bind("<<ComboboxSelected>>", callback)

tkwindow.mainloop()

Note the absence of () after callback in: cbox.bind("<<ComboboxSelected>>", callback).
Here's option 2:
import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)

cbox.bind("<<ComboboxSelected>>", lambda _ : print("Selected!"))

tkwindow.mainloop()

Check what are lambda functions and how to use them!
Check this article to know more about events and bindings:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

A: Thanks you for the posts. I tried *args and it workes with bind and button as well:
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')

def callback(*args):
    print(eventObject)

cbox.bind("<<ComboboxSelected>>", callback)
btn = ttk.Button(tkwindow, text="Call Callback", command=callback);

tkwindow.mainloop()


text:
Q: one line placing inside overflow I try to make a slider but have trouble, with placing all my div tags in one line. How do I do that?
And how to do auto-width for #slider_content?

1

2

3

4

5

6

A: The width of your outermost DIV is far too narrow - increase it to be at least 300px.
Alternatively set the widths of your innermost DIVs to be a percentage which total <= 100%, then set slider_content to have width of 100%.
e.g.

1

2

3

4

5

6

A: you dont really need auto width just set it higher than what you require!
.slider_content{
width:1000px;
}


text:
Q: How to find parent implicit parameter with scala-reflect? I have two classes:
class X[A](implicit ord: Ordering[A]) // + other irrelevant parameters
class Y[A: Ordering] extends X[A]

Given a Symbol corresponding to Y's implicit constructor parameter, I want to find the symbol for the parent class implicit parameter it corresponds to (if one exists).
val yOrdSym = ...
val yOrdType = yOrdSym.typeSignature
val xImplicitParams =
  xSym.primaryConstructor.paramLists.flatten.
  filter(xParam => xParam.isImplicit && ???)

Now I need to filter it for having the same type as well (or a supertype, but this doesn't matter for my usecase). I've tried xParam.typeSignature =:= yOrdSym.typeSignature, which didn't work. This makes sense, because the type parameters have different owners. However, xParam.typeSignature =:= yOrdSym.typeSignatureIn(xSym.toType) and xParam.typeSignatureIn(ySym.toType) =:= yOrdSym.typeSignature don't work either. How to do it correctly?


text:
Q: Can I set docker container resource limit to unlimited? I understand that we can set docker container resource limit, is it possible to set it as unlimited? so it can use all the resource that the server has.

A: Docker documentation says:

By default, a container has no resource constraints and can use as much of a given resource as the host's kernel scheduler allows.

https://docs.docker.com/config/containers/resource_constraints/


text:
Q: Cosmos Design Questions I have the following top level simplified design for my Cosmos project. Some introduction and then followed up by some questions. Thank you in advance for reading this.
I have 3 collections: Memberships, Discounts and Vouchers:

Each collection stores different entities. The entities in each collection are not the same but belong to the same partition and have inherited properties:

*

*id - unique id (a Cosmos requirement...I tink)

*upsertDate - updated at the time of upsert so i can order documents (see below)

Each collection entity has:

*

*code - the partition key

*type - a discriminator for the diffrent entities in the collection.

There are thousdans of memberships, vouchers and discounts. When the system receives a membership code, for example, it can quickly look up the document as it is the partition key.
If one does this, it returns all the entity documents that belong to the same code:
SELECT * FROM c WHERE c.code = 'YTR3IO'

If one does this, it returns all the entity documents that belong to the same code and type:
SELECT * FROM c WHERE c.code = 'YTR3IO' and c.type = 10

type is usually an enumeration for the different entities that can be stored in a specific collection. For example, in the case of memberships, type can be notication, comment, request, transaction, etc
The reason I have the upsertDate in every document so I can do things like this:
SELECT * FROM c WHERE c.code = 'YTR3IO' AND c.type = 10 ORDER BY c.upsertDate DESC

For the indexing policy, I have overridden the policy to what I think is best:
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.Id = _docDbMembershipsCollectionName;
collectionDefinition.PartitionKey.Paths.Add("/code");
collectionDefinition.DefaultTimeToLive = -1;

// If queries are known upfront, index just the properties we need
collectionDefinition.IndexingPolicy.Automatic = true;
collectionDefinition.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
collectionDefinition.IndexingPolicy.IncludedPaths.Clear();

IncludedPath path = new IncludedPath();
path.Path = "/code/?";
path.Indexes.Add(new RangeIndex(DataType.String) { Precision = -1 });
collectionDefinition.IndexingPolicy.IncludedPaths.Add(path);

path = new IncludedPath();
path.Path = "/upsertDate/?";
path.Indexes.Add(new RangeIndex(DataType.String) { Precision = -1 });
collectionDefinition.IndexingPolicy.IncludedPaths.Add(path);

path = new IncludedPath();
path.Path = "/type/?";
path.Indexes.Add(new RangeIndex(DataType.Number) { Precision = -1 });
collectionDefinition.IndexingPolicy.IncludedPaths.Add(path);

collectionDefinition.IndexingPolicy.ExcludedPaths.Clear();
collectionDefinition.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/*" });

DocumentCollection ttlEnabledCollection = await
_docDbClient.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(_docDbDatabaseName), collectionDefinition, new RequestOptions { OfferThroughput = 1000 });

QUESTIONS:
QUESTION 1: If I have a query that has oredering by the upsertDate, the cost shoots up the roof:
FeedOptions queryOptions = new FeedOptions { MaxItemCount = 100, PartitionKey = new Microsoft.Azure.Documents.PartitionKey(code.ToUpper()) };

var query =  this._docDbClient.CreateDocumentQuery<MembershipDeviceRegistrationItem>(
                UriFactory.CreateDocumentCollectionUri(_docDbDatabaseName, _docDbMembershipsCollectionName), queryOptions)
                .Where(e => e.CollectionType == MembershipCollectionTypes.DeviceRegistrationItem && e.Code.ToUpper() == code.ToUpper())
                .OrderByDescending(e => e.UpsertDate)
                .AsDocumentQuery();

List<MembershipDeviceRegistrationItem> allDocuments = new List<MembershipDeviceRegistrationItem>();
while (query.HasMoreResults)
{
    var queryResult = await query.ExecuteNextAsync<MembershipDeviceRegistrationItem>();
    cost += queryResult.RequestCharge;
    allDocuments.AddRange(queryResult.ToList());
}

return allDocuments.ToList();

How can I make use of the upsertDate to order my documents and select top most recent ones for example?
QUESTION 2: How do I calculate the cost of a query that has an aggregate?
FeedOptions queryOptions = new FeedOptions { MaxItemCount = 1, PartitionKey = new Microsoft.Azure.Documents.PartitionKey(code.ToUpper()) };

return _docDbClient.CreateDocumentQuery<int>(
            UriFactory.CreateDocumentCollectionUri(_docDbDatabaseName, _docDbMembershipsCollectionName),
            new SqlQuerySpec()
            {
                QueryText = $"SELECT value count(m.id) FROM {_docDbMembershipsCollectionName} m WHERE m.code = @code AND m.collectionType = @type",
                Parameters = new SqlParameterCollection()
                {
                    new SqlParameter("@code", code.ToUpper()),
                    new SqlParameter("@type", MembershipCollectionTypes.DeviceRegistrationItem)
                }
            }, queryOptions).AsEnumerable().First();

QUESTION 3: I have a need to produce an Omni document that contains everything about a specific membership and return to some client so they can show its different parts. So I created something like this (simplified):
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, PartitionKey = new Microsoft.Azure.Documents.PartitionKey(code.ToUpper()) };
var query = _docDbClient.CreateDocumentQuery<dynamic>(
            UriFactory.CreateDocumentCollectionUri(_docDbDatabaseName, _docDbMembershipsCollectionName),
            new SqlQuerySpec()
            {
                QueryText = $"SELECT * FROM {_docDbMembershipsCollectionName} m WHERE m.code = @code",
                Parameters = new SqlParameterCollection()
                {
                    new SqlParameter("@code", code.ToUpper())
                }
            }, queryOptions).AsDocumentQuery();

List<dynamic> items = new List<dynamic>();
while (query.HasMoreResults)
{
    var queryResult = await query.ExecuteNextAsync();
    cost += queryResult.RequestCharge;
    items.AddRange(queryResult.ToList());
}

var omni = new DigitalMembershipOmni();
foreach (var item in items)
{
    var collectionType = (MembershipCollectionTypes)item.collectionType;
    if (collectionType == MembershipCollectionTypes.Membership)
    {
        omni.Clone((DigitalMembership)item);
    }
    else if (collectionType == MembershipCollectionTypes.RefreshItem)
    {
        omni.RefreshItems.Add((DigitalMembershipRefreshItem)item);
    }
    else if (collectionType == MembershipCollectionTypes.OfferItem)
    {
        omni.OfferItems.Add((DigitalMembershipOfferItem)item);
    }
    else if (collectionType == MembershipCollectionTypes.TrackingTransactionItem)
    {
        omni.TrackingTransactionItems.Add((DigitalMembershipTrackingTransactionItem)item);
    }
    else if (collectionType == MembershipCollectionTypes.BookingTransactionItem)
    {
        omni.BookingTransactionItems.Add((DigitalMembershipBookingTransactionItem)item);
    }
    else if (collectionType == MembershipCollectionTypes.MembershipTransactionItem)
    {
        omni.MembershipTransactionItems.Add((DigitalMembershipTransactionItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.NotificationItem)
    {
        omni.NotificationItems.Add((DigitalMembershipNotificationItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.CommentItem)
    {
        omni.CommentItems.Add((DigitalMembershipCommentItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.ContactUsItem)
    {
        omni.ContactUsItems.Add((DigitalMembershipContactUsItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.ReferralItem)
    {
        omni.ReferralItems.Add((DigitalMembershipReferralItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.EcertPinItem)
    {
        omni.EcertPinItems.Add((DigitalMembershipEcertPinItem)item);
    }
    else if (collectionType == DigitalMembershipCollectionTypes.ProfileUpdateItem)
    {
        omni.ProfileUpdateItems.Add((DigitalMembershipProfileUpdateItem)item);
    }
}

return omni;

The above works....but it is costly....and...it does not scale well....so if the a membership accumulates more data, the cost will go up signifcantly. I tried to do a query for each type specifying the top items to produce such as top 100 notifications...but the order by upsertDate (as noted above) makes the queries very expensive....so the total cost is even worst. How would one accomplish something like this with a reasonable cost and performance.
QUESTION 4: I have a membershipCode property in the vouchers and the discounts collections, how can I do a JOIN query that picks up the vouchers that belong to a specific membership without exhausting my RUs and killing my performance? I think JOIN queries will end up scanning the entire vouchers collection with different partitions and might have a significant cost and throughput issues. The only way I was able to get it to work reasonably well is to use Table DB to link vouchers to memberships. The Table DB queries are fast...but this added a significant complication to my little project.
I appreciate any pointer.
Regards


text:
Q: What environment change causes get_header to return a different output? like the title states I'm running the same script on two different PHP versions.

*

*My Server 1- 5.2.17

*My Server 2- 5.3.19

get_headers($url, 1);
$url was google (no www) with http and .co.uk - Or use any url that returns a 404
An example of the different outputs are:
My Server 1-

*

*[Server] => gws   [gathered from the header]

My Server 2-

*

*[Server] => Array    [gathered from the header]
(
    [0] => gws
    [1] => gws
)

What I presume is that Server 2 is following the location of a 301 and adding that to the header, where Server 1 only has the 301 header in the array.
So Server 2 would go to "http://google.co.uk" (this returns 301); and then follows it to "http://www.google.co.uk/"
and adds both responses to the same output.
What my question is- what causes the change? I've checked over the PHP channel log and I can't see a mention to get_headers so I must be missing something.
If you know what causes the different outputs, and even better know how I can revert the change (without changing back to the old PHP version) I'd greatly appreciate it. I know I could use cURL but I wouldn't really want to do that.
Full-ish code (without validation etc.)
1.$address = ($_POST['address']);
2.$headerinfo = get_headers($url, 1);
$server = $headerinfo[Server];

*

*In PHP 5.2 - if I echo $server it would be something like "Apache".

*In PHP 5.3 - If I echo $server it would be "Array" (if it hits a 301).
In the end I'm planning on storing the $sever in a DB. I can't/don't want "Array" stored there.
Thanks.


text:
Q: How would I find the time complexity of the following recursive algorithm? Assuming that r is the root of a tree (may be non-binary), c is a child of r, and each node contains an integer.
Algorithm findMax(r)
if r = null return null
int maxValue = r.value
if r.isLeaf return maxValue;
for each child c of r do{
    if findMax(c) > maxValue
        maxValue = findMax(c)
}
return maxValue

A: Currently it does have O(n) complexity when consider n to be number of node in the tree.
For each child-node of the root you call recursive function to all sub-tree root in c. So basically, you preform DFS on this graph which make in O(V+E) -> in your case, when the graph is a tree, it equel to O(V).
Notice, that you call recursive function of findMax in the if-statement - if it true you calculate it again - which increase complexity to O(2*n). Calculate the findMax function once, assign its result to local var and check and update the maxValue with it will reduce complexity to O(n).


text:
Q: Windows Programs and Files stop working after checking disk I encountered a problem randomly that most likely started last night (I'll explain why).
I was using my computer as usual; I downloaded a series of a television show and updated an online game. I shut off my computer before I went to sleep for the night. Next morning, I booted up my computer and I received the infamous frozen "Starting Windows" screen for nearly 30 minutes. Then I rebooted the computer to the BIOS menu and set the mode from LEGACY to UEFI just for the heck of it. I'm not sure if this fixed it, but it managed to get out off "Starting Windows" after a bit and led me into disk check for my secondary drive for et cetera programs, movies, and games.
After logging into Windows 7, I felt like watching a TV show on my hard drive and opened it up in MPC-HC. It proceeded to stutter constantly and wouldn't play at all after a few seconds in. This isn't a MPC-HC problem because I tried it in VLC and MPV and also encountered similar problems. It happened to nearly all my TV shows. Also, games like osu! crash after you get to the song menu, so the problem must be universal for most media files on my TB hard drive.
I tried system restoring to the day before it began, but I also encountered the "Starting Windows" error. I chose the same procedures as earlier, except I changed UEFI to LEGACY in my BIOS menu. I still have the same problem. I'm not sure how I should tackle this as it could be caused by practically anything.
I'm not a expert at computer knowledge, so I would be very grateful of your input. Thank you.

A: In case you do have a classical hard disk (no SSD) built in that may be a sign of a dying disk. If there are read errors on the disk the software / operating system tries to read over and over again several times until it ultimately fails after several attempts (or succeeds after a few attempts) - and that slows down everything.
First make sure that you have a backup of all your (important) data on the device.
Afterwards I would recommend to check hard disk health (e.g. using CrystalDiskInfo for S.M.A.R.T. diagnostic values and / or with the tool provided by the manufacturer of your harddisk, which commonly provides a low level full disk scan). S.M.A.R.T. values will probably already tell you whether the disk is really the source of the error or not.

A: Bad Sectors on Disk
As the Windows has already attempted to rectify the situation with a Check Disk to some partial success I would assumed from the information given that one or more of your HDD's is failing.
Test for Bad Sectors
There are many software suites out there dedicated to checking the integrity of Hard Disk Drives.
I personally use HDD Regenerator but this software is not free, unfortunately I do not know of any free alternatives other than the built in Check Disk function of Windows.
Check Disk
You can open CMD prompt
Run the following command:
chkdsk C: -r
This will find and repair bad sectors by marking them out of use to ensure that the computer does not attempt to store anything on the bad parts of the drive.
You can check all of the partitions and drives on your computer by replacing the C with the drive letter to be checked.
Further Information
If you drive is drying which is very likely in my opinion then you need to replace it sooner than later and backup your stuff immediately.


text:
Q: Registry API 32 vs 64bit, and VS2010 setup We have a .net 4.0 app which uses a couple of registry keys and a vs2010 setup & deployment project which creates those keys @ setup
Problem - (default) RegEdit shows the keys exist but the .net code returns null on OpenSubKey with the correct path ( incl. the \ )
Which as it turns out is due to 32 & 64 bit registries per  KB305097
and which requires code such as
RegistryKey someFunc()
{
    var r64o32 = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
                Environment.Is64BitOperatingSystem  ? RegistryView.Registry64 :
           RegistryView.Registry32);

    return r64o32.OpenSubKey(regKey);
}

However i cannot test the code above as I don't have a 32bit machine available but the app needs to be available on 32bit machines as well
so looking for help on -

*

*is the approach above correct for both 64/32bit ?

*does the setup created by vs2010 setup project install the defined registry
entry on 64/32 registry based on the the machine ?

*Any other gotchas ?

A: You don't need to do special casing on the RegistryView as you are using OpenBaseKey this is asking for a specific view of the Registry regardless of how you compiled your application
RegistryKey r = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                                                        RegistryView.Registry64);

Also remember that if you are on a 32bit machine, then OpenBaseKey will just fallback to Registry32


text:
Q: VS Code Git, 3000+ commits I recently installed VS code on Ubuntu, and when trying to set up Git, I realized that all changes to my files are registered as changes in a Git repository, leading to me having to commit any changes to any file that is augmented on my device, such as cache files from Google Chrome.
This leads to over 3371 commits that I have to accept every time I open another document and files that I am actually using get lost in this mush of files.

The specific problem is: How can I avoid having to version all my files?
(which is why I see all those "changes" in VSCode Source Control section)

A:
ahh, I just checked, yes my entire user directory is a get repo.

If you have a ~/.git folder, you should remove it (at at least rename it): there is no good practice recommending to put its entire home folder under version control.
Or you should at least have a .gitignore file properly configured.
But if you did not explicitly setup that Git repository in ~, delete it.


text:
Q: Packing fraction of atoms in a HCP structure I am looking to find the ratio of atomic sphere to unit cell volume in  a HCP (hexagonal close packing) arrangement.  Some sources I have say it is 0.74
My unit cell structure is that shown below. I labeled the height between the two hexagonal planes by $h$ and the length of the equilateral triangles comprising the hexagon by $2r$. If we then consider a 1/6 of this structure in the obvious way and orient it suitably so that one of the sides of the lower triangles coincides with the x axis say, then the volume of 1/6 of this structure is $$V = 2 \int_0^{r} \int_0^{\sqrt{3}x} \int_0^h dx dy dz = \sqrt{3}hr^2.$$ Multiply this by 6 to get the whole volume of the unit cell structure shown below.
I am struggling to find an expression for the height between consecutive planar hexagons in terms of the radius $r$, so that in the end I can take ratios. Doing this for a FCC or BCC structure  is fine since then we are dealing with a cube structure.
Many thanks (apologies for the size of the image, I can't see how to make it smaller)
.


text:
Q: html5:how to make poster image to be displayed in android 4.0.4 devices? I'm using html5  to display/play the videos on android devices. But image set through "poster" tag is not displayed. How to make it displayed? Or is there any alternate solution to have a preview image for the html5 videos ?
<video width="100%" height="350" preload="none" controls="controls" poster="img path">
 <source src="mp4 image path" type="video/mp4">
 <source src="ogv image path" type="video/ogv">
 <source src="mov image path" type="video/mov">
 <source src="webm image path" type="video/webm">
</video>


text:
Q: How to allow App Users to share files in-between each other (like share-contact) My App's main function is a short-hand Note taker... Users' input is stored in a [String] and these Strings are used in a replayer to show an animated version of what was noted.
The file will contain this Array of Strings and a few thumbnail Images.
How can I allow users to share this file with a friend that has the same App? I prefer users to be able to text the file (like in contacts "Share contact") and when the receiver taps the file...The App is opened and Replayer starts.

A: There are a number of ways to do this, I strongly recommend using a web service to perform the communication between applications. You can use a REST API (examples on how to develop your own API here) so your users can upload the files, and other users can download these files onto their mobile device.
If you do not want (or do not have time) to develop your own REST API, you can sign up with Parse which offers several options for solving your needs (REST API, mobile SDK's, etc), with a very simple user interface. This way your information is not stored on your user's physical device, it is instead stored in a server. This enables sharing of information and/or files.


text:
Q: How to change all the elements of a list that are equal? How can I replace all elements of a list which are equal to c to t in OCaml?
I have tried List.filter without success:
List.fold_right (fun c -> t) (List.filter c myLst) []

Does the List module contain a function for this task?

A: You can use map (see the List module):
open Printf;;

let l = ['a'; 'b'; 'c'; 'd'; 'c']
let l2 = List.map (fun x -> if (x = 'c') then 't' else x) l;;
List.iter (printf "%c ") l2;;

which prints
a b t d t

A: If you would like to use List.fold_right, here is the way to do it:
let replace lst = List.fold_right (fun elmt accum ->
    let e = if elmt = 'c' then 't' else elmt in
    e::accum
) lst [];;
      val replace : char list -> char list = <fun>
# replace ['a'; 'b'; 'c'];;
- : char list = ['a'; 'b'; 't']

Notice : Do NOT use == instead of = in OCaml, they have different meanings.
== tests for physical equality, but = tests for semantical equality. So when you use ==, it could return false even if the two values are semantically equal.


text:
Q: Query to get ids of entries which appear in arbitrary amount different lists

id
category_id
product_id
status

13
93
2137
1

14
94
2137
1

15
93
2138
2

16
94
2138
2

17
87
2128
1

18
94
2128
1

19
87
2139
2

20
94
2139
2

21
88
2132
1

22
93
2132
1

23
88
2140
2

24
93
2140
2

25
87
2137
1

26
87
2141
2

27
93
2136
1

28
93
2137
1

29
88
2134
1

30
88
2143
2

I have this kind of data presented to me. For my query I'm given a list of category ids.
Let's say I'm given three lists with
1. {93, 94}
2. {88, 87, 86}
3. {93}

Now I would need a query, which would give me product ids, which appear at least once in ALL of those lists and for which the status is 1. So for the example query the result should be:

product_id

2137

A: This should work for SQL Server 2016 and above.
CREATE TABLE table1
(
id INT,
category_id INT,
product_id INT,
status INT
)

INSERT INTO table1
    (id, category_id, product_id, status)
VALUES
    ( 13, 93, 2137, 1)
    ,( 14, 94, 2137, 1)
    ,( 15, 93, 2138, 2)
    ,( 16, 94, 2138, 2)
    ,( 17, 87, 2128, 1)
    ,( 18, 94, 2128, 1)
    ,( 19, 87, 2139, 2)
    ,( 20, 94, 2139, 2)
    ,( 21, 88, 2132, 1)
    ,( 22, 93, 2132, 1)
    ,( 23, 88, 2140, 2)
    ,( 24, 93, 2140, 2)
    ,( 25, 87, 2137, 1)
    ,( 26, 87, 2141, 2)
    ,( 27, 93, 2136, 1)
    ,( 28, 93, 2137, 1)
    ,( 29, 88, 2134, 1)
    ,( 30, 88, 2143, 2)

CREATE TABLE Input
    (IdLst varchar(100))
INSERT INTO Input (IdLst)
VALUES
    ('{93, 94}')
    ,('{88, 87, 86}')
    ,('{93}')

;WITH Categories AS (
    SELECT CONVERT(INT, Value ) category_id
    FROM Input
    CROSS APPLY STRING_SPLIT(REPLACE(REPLACE( IdLst, '{', ''), '}', ''), ',')
)
SELECT product_id
FROM Categories
INNER JOIN table1 ON table1.category_id = Categories.category_id
GROUP BY product_id
HAVING COUNT(1) = (SELECT COUNT(1) cntCategories FROM Categories )

A: The first step in any solution is to normalize the selection criteria data into a table of the form { category_group_id, category_id } with only one category_id for row. There are several ways to do this but I've used the relatively new STRING_SPLIT function here (same as Luis LL). This normalized criteria may be loaded into a temp table or included as a Common Table Expression (CTE) as is done below.
Once the criteria is normalized, the real problem can be solved by (1) filtering the input data by status, (2) joining it with the normalized selection criteria from above, (3) grouping by product ID, and then  (4) counting the number of distinct category group IDs matched. If that count matches the total number of category group IDs (three for the sample data), we have a match.
;WITH NormalizedCategoryIds AS (
    SELECT C.category_group_id, CAST(S.Value AS INT) AS category_id
    FROM CategoryIds C
    CROSS APPLY STRING_SPLIT(
        REPLACE(REPLACE(category_id_list, '{', ''), '}', ''),
        ',') S
)
SELECT D.product_id
FROM SampleData D
JOIN NormalizedCategoryIds C on C.category_id = D.category_id
WHERE D.status = 1
GROUP BY D.product_id
HAVING COUNT(DISTINCT C.category_group_id) = (SELECT COUNT(*) FROM CategoryIds)

If we started with criteria that was already normalized, the HAVING clause could be changed to:
HAVING COUNT(DISTINCT C.category_group_id)
    = (SELECT COUNT(DISTINCT C2.category_group_id) FROM NormalizedCategoryIds C2)

That value could also be calculated ahead of the query.
Sample results:

product_id

2132

2137

Even though not in the original posted results, 2132 is also included here, because it matches all three category groups. The 93 row matches category groups 1 and 3 and the 88 record matches category group 2.
See this db<>fiddle for a working demo including some extra test data.


text:
Q: help with circuit design I have a problem and some of the components I think I need to solve the problem but I do not have the knowledge or understanding to put it all together and what I read online is just not connecting the dots for me.
Ultimately what I need to have happen is a PIR sensor detects movement and triggers a string of LEDs. Which seems like it should be simple enough. I can get the PIR sensor to light an individual LED but anything beyond that and the PIR is to weak.
The LEDs I am trying to light are in a ribbon format and I want them to run off of bare minimum 12v but preferably 18vdc as this is when they are at their absolute brightest. At 18vdc they draw about 2 amps of current.
The PIR is powered off of 6Vdc and outputs 3.3VDC with around 300uA.
I want to use a relay that I have which the coil can be pulled in at a little under 3 volts but needs around 100mA of current and the contacts could handle the 18vdc and 2 amps I want to run my lights.
My problem is how can I get more current from the output of my PIR to trigger the relay, being that I can't increase the voltage coming out of the sensor?
I have some transistors to work with but I don't have enough understanding to connect a proper circuit up and I believe I have been burning out some components needlessly just playing around with stuff.
My PIR is an HC-Sr501, my Relay is a JQC-3F (T73), the LEDs are a 12V RGB ribbon style, and I have available some standard NPN and PNP transistors BC547, BC557, 2N2222, and 2N3904. I also have a variety of common resistors and other standard components. Either a circuit somebody has already created or just some specific instructions of how the connections should be made in order to accomplish my goal would be appreciated.

I don't have a data sheet for the LEDs. This is what they are and all the specs I could get on them.
SUPERNIGHT (TM) 16.4FT 5M SMD 5050 Waterproof 300LEDs RGB Color Changing Flexible LED Strip Light
Voltage 12 volts
Wattage 60 watts
I don't have a problem running them at 12v if I have to and I understand it would be a better idea.
here is a data sheet to my PIR sensor http://www.datasheet-pdf.info/entry/HC-SR501-Datasheet-PDF .
Although it isn't marked as an HC-sr501 when I purchased it from a chinese supplier this is
what they claimed it to be.
I know you need real information from data sheets but I don't have much of that stuff.
I know what I can read from my DMM. The sensor puts out 3.3 volts as expected when triggered but the current is only 300 micro amps. my relay coil will react at about 2.8 volts but draws about 100 milliamps in order to do so. The LEDs are designed to operate on 12 volts but when I crank it up to 18 volts they are bright and although they will eventually burn out I have run them at 18volts for more than 24 continuous hours without fail, that doesn't matter so much to me anyways, even if I only supplied them with 12 volts that would be ok. I just can't get my PIR to trigger my relay to turn my leds on in the first place. There isn't enough current coming out of my PIR output to activate the coil.

A: The below schematic demonstrates a circuit that will do this for you. When the PIR signal is low, the NPN transistor will be off, and no current will flow through the relay. When the PIR signal turns goes high, this causes the transistor to turn on, drawing current through the relay coil turning the relay on.

simulate this circuit – Schematic created using CircuitLab
Winny in the comments is correct, you should not use 18Vdc on the 12Vdc rated LEDs. While they may be brighter in the short term, this can lead to a few issues:
The LEDs will dim much faster over time than if you used 12Vdc.
 There is a chance of overheating, and by extension, fire.
Now, you also say you have an RGB LED strip, not a simple one color strip. You will need to supply power to all three colors, not just one, if you want a white(ish) color out of them. (This is also assuming this strip is a common cathode model, datasheet/links haven't been provided)
EDIT:
To address @user2913869's concern that the sensor may not be able to drive a single NPN transistor, according to this website, and this datasheet, the actual output of that chip is approximately 10mA @ 5V supply voltage.
EDIT 2:
D6 is what is called a flyback diode. This is a necessary component when using relays (and other inductive loads). Inductive loads don't allow current to change immediately in a circuit. This diode allows current to flow back to the relay, rather than trying to push that current through the transistor, which can break the transistor. To put it  simply, it allows the energy stored in the coil of the relay to dissipate without breaking the transistor.


text:
Q: How do I load data from a external json api using angularJS? for example I want to view data from two urls:
1- http://jsonplaceholder.typicode.com/posts/
2- http://jsonplaceholder.typicode.com/todos/
Can I load data from these two url's in one app with two controllers in one view page?

A: Use $http.get to issue the query (JSFiddle):
angular.module('Joy', [])
.controller('CtrlOne', ['$http', '$scope', function ($http, $scope) {
    $http.get('http://jsonplaceholder.typicode.com/posts/').then(function (data) {
        $scope.posts = data.data;
    });
}])
.controller('CtrlTwo', ['$http', '$scope', function ($http, $scope) {
    $http.get('http://jsonplaceholder.typicode.com/todos/').then(function (data) {
        $scope.todos = data.data;
    });
}]);

HTML:

{{ posts[0] | json }}

{{ todos[0] | json }}


text:
Q: Weekly Schedule with SQL I need a weekly scheduler for students.

*

*Rows are 12 hours (08:00-20:00),

*columns are 6 days (Monday-Saturday).

*Student has a course at monday between 9-11 and tuesday 11-14.

*Others will be shown empty.

Can i create a query (matrix) like that just with SQL?
My current query is like that:
SELECT courseName, courseDay, courseStartHour, coursEndHour
FROM courses WHERE studentId = 1

This is what i want:

I had that with Pivot:

Same hour can include multiple course. (max 2)
Note: We have Oracle 11g.
Sample (Simplified) Data:
CREATE TABLE StudentCourses ( courseCode varchar2(8) NOT NULL,  courseName varchar2(64) NOT NULL,  day number(10),  startHour number(10),  endHour number(10));

INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 352','Advertising Copywriting','1','9','11' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 352','Advertising Copywriting','1','11','13' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 332','Positioning Strategy in Advertising','2','9','12' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'COMM 324','Persuasion and Perception','2','14', '17' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 312','Corporate Communications Practicum','3','14','17' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 302','Strategic Media Planning','4','9','11' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 302','Strategic Media Planning','4','11','13' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 412','Case Studies in Advertising','4','13','15' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 411','Advertising Photography','4','14','16' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 412','Case Studies in Advertising','4','15','17' );
INSERT INTO StudentCourses (courseCode, courseName, day, startHour, endHour ) VALUES ( 'ADV 411','Advertising Photography','4','16','18' );

A: Here is a simpler one.
WITH TEMP AS(SELECT LEVEL+7 AS HR  FROM DUAL CONNECT BY LEVEL <= 12)
SELECT TEMP.HR AS "HOUR",
       CASE WHEN TEMP.HR BETWEEN 9 AND 11 THEN 'X' ELSE NULL END AS MON,
       CASE WHEN TEMP.HR BETWEEN 11 AND 14 THEN 'X' ELSE NULL END AS TUE,
       NULL AS WED,
       NULL AS THU,
       NULL AS FRI,
       NULL AS SAT,
       NULL AS SUN
       FROM DUAL, TEMP

A: is that what you Need?
with tab as (
select 8 as "hour", null as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday from dual union all
select 9 as "hour", 'x' as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 10 as "hour", 'x' as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 11 as "hour", 'x' as monday, 'x' as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 12 as "hour", null as monday, 'x' as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 13 as "hour", null as monday, 'x' as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 14 as "hour", null as monday, 'x' as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 15 as "hour", null as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 16 as "hour", null as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 17 as "hour", null as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual union all
select 18 as "hour", null as monday, null as tuesday, null as wednesday, null as thursday, null as friday, null as saturday  from dual
)
select * from tab


text:
Q: Can GemFire OQL query be done on all the child-regions of a parent-region, in a single query I need to make a hierarchy of regions like following, as usually I query by country and type. I put all data in country level regions. Sometimes I query across countries in NAM_Type1 and sometimes Global.
Global_Type1
-> NAM_Type1
-->  USA
-->  Mexico
-> APAC_Type1
-->  Japan
-->  HongKong

Is there a way I can query parent-region, without querying multiple times on individual countries?
Can indexes be made at parent level?
I use GemFire 7.0 with spring-gemfire for connection.

A: @Ashish
If I understand your problem correctly, the quick answer is no.
It seems you want to use a parent (e.g. NAM_Type1) Region to refer to, or rather query across data contained in multiple Sub-Regions of the parent (e.g. USA, MEXICO, etc) and "aggregate" the results from all the Sub-Regions???
For example, assuming your Sub-Regions contain Customer objects...
public class Customer ... {
  private String firstName;
  private String lastName;
  private boolean active;
  ...
}

Then...
SELECT * FROM /NAM_Type1 nam WHERE nam.active = 'true';

This OQL query is broken as their is no reference between the parent Region (e.g. NAM_Type1) and the entries in the Sub-Regions (e.g. USA, etc).  If you are using the "parent" Regions just for a namespace hierarchy, then they contain no data at all.
I am wondering what the need is to have "Sub-Regions"?  A Sub-Region is not viewed any differently than a top-level Region when it comes to data access (particularly with OQL/querying).
By using Sub-Regions, it implies you are using and are limited to using REPLICATE Regions as mentioned in the GemFire User Guide here (http://gemfire.docs.pivotal.io/latest/userguide/index.html#basic_config/data_regions/managing_data_regions.html).  For this reason, amongst others, the GemFire team generally discourages the use of Sub-Regions, especially where the transactional data might change a lot.
In general, you want to use PARTITION Regions for transactional data and REPLICATE Regions mostly for smaller data sets and usually reference/lookup type data.
So, in your case, you might achieve similar behavior by...

*

*Using PARTITION Regions...

*Configured and created on different Servers...

*Organized into different server groups based the hierarchical organization you stated above.

Then, you can target and run a GemFire Function on Servers in specific server groups hosting the data for the demographic area(s) of interest to run an OQL Query on the local data set of the Region.  The Function will aggregate and then return the results.
There are different ways to organize and partition the data, even using custom "PartitionResolvers", etc, or to target Functions, and so on.
By using PARTITION Regions you can still achieve HA (redundancy) using the "copies" attribute on  (which corresponds to GemFire's PartitionAttributes.redundantCopies property).  You have the option to "co-locate" data making equi-join Queries possible/optimal.
DISCLAIMER: not being intimately familiar with your use case(s) and requirement(s), my suggestions may or may not work for your situation, but usually the effects of Sub-Regions can be achieved more elegantly and effectively using GemFire's other features.  If anything, maybe this will give you some ideas.
Hope this helps!
-John


text:
Q: ckEditor in modal Does not works when reopened without page reload I'm having isssue in CKEditor load in my modal (of Material Design Template).
It works on first load of modal.
But when I open modal by ajax call without re-loading(refreshing) page then CKeditor does not works to give text to textarea.  It gives error while CKEditor load in console stating
"  TypeError: $(...).get(...) is undefined " in Firefox
" Uncaught TypeError: Cannot read property 'contentWindow' of undefined " in Chrome
My jquery method is following which i call on each modal open.
    //being callled in ajax success and modal open
var description = CKEDITOR.replace( 'description' );
loadEditorData();

// Function to get and Load Editor's contents.
function loadEditorData() {
 setTimeout(function(){
         $( $("#cke_1_contents iframe" ).get(0).contentWindow.document ).keypress( function() {
             setTimeout(function(){
              var editorText = CKEDITOR.instances.description.getData();
              console.log(editorText);
              $("#description").html(editorText);
              }, 10);
            });
     }, 5000);
 }


text:
Q: How to make start and end slope points zero in spline? This is my MATLAB code:
a = [-1, 0, 1, 2];
b = [1, 0, -1, 1];
ss = spline(a, b, 1.5)

I want MATLAB to calculate the answer when s0=s3=0. What should I do?

A: Take a look at "Input Arguments" section of the spline documentation. It says that if the vector b has exactly two more elements than the vector a, then the first and last values of b are used to specify slope values at the ends.
Since you require zero slopes at the two ends, you should do:
a = [-1, 0, 1, 2];
b = [0, 1, 0, -1, 1, 0]; %first and last values specify end slopes
ss = spline(a, b, 1.5)


text:
Q: Column family stores vs document stores I've read several posts, such as this one, that compare document stores like MongoDb, CouchDb and CouchBase with column family stores like Cassandra.
One comparison is the fact that document stores work at a higher level of granularity as opposed to column family stores that let you work on individual parts of the document. I find that to be simply untrue because Redis supports this via the hset operation and so does mongodb.
Is the argument then, that although both types of solutions allow updating / reading parts of a document, column family stores are simply more efficient at doing this than document stores?
Does that also mean that I should take the document store route for insert and read heavy applications but the column family route for update and read heavy applications?
What are some other differences that would help me choose one solution over the other?
Thanks!

A: I would suggest that the main difference is in the query model. They can both store similar data structures (you can put a JSON document into a CF store, for example), but document stores typically give you query-by-value capability whereas CF stores typically do not.  However the lines are blurring, and it seems that such generalizations are becoming less applicable as each database project matures.  Cassandra (a popular CF store), for example, does offer some query-by-value functionality with secondary indexes.  However most CF stores require you to write the data the way you intend to read it, meaning you must think about your data model in terms of your queries.
It would seem to me that there are other equally important distinctions between various database technologies, such as consistency model, datacenter replication capability, scaling model, ease of management, caching capabilities, etc.


text:
Q: Page stops responding and freezes while sending continuous request to web server from ajax I'm trying to create a signal on the webpage and display green or red color on the basis of values retrieved from a database. But when I'm sending request after 10 seconds page seems to be freezed and not responding. I'm unable to find out where I'm going wrong, please help me to resolve this problem.
Techstack Using - HTML, CSS, Js, Ajax, Python(Flask) and PostgreSQL
function latest_status(){

    var header = document.getElementById("circle");

    var tbid = $('#mtb').val();

    var signal = $.ajax({
        type: 'POST',
        url: '/status?tbid='+tbid,
        data: "",
        contentType: false,
        dataType: "json",
        async:false,
        cache: false,
        processData: false,
        success: function(data) {
        },
        //error: function(data) {
        //  alert("Data Not received !!");
        //},
        complete: function(data){
            setTimeout(latest_status, 10000);
        }
    });

    var signaldata = JSON.parse(signal.responseText);

    var signalvalue = signaldata[0].signalvalue;
    var datevalue = signaldata[0].date;

    if(signalvalue == '1')
    {
        header.style.background = "green";
    }
    else
    {
        header.style.background = "red";
    }
};

setTimeout(latest_status, 10000);

Flask Code :
from flask import Flask, redirect, url_for, request, render_template
from flask_socketio import SocketIO
from werkzeug.utils import secure_filename
from flask import jsonify
import json
import eventlet

from collections import OrderedDict

import psycopg2

app = Flask(__name__)
app.config['SECRET_KEY'] = 'project!'
socketio = SocketIO(app)

@app.route('/status', methods = ['POST', 'GET'])
def latest_status():

    tbid = request.args['tbid']

    if request.method == 'POST':

        connection = psycopg2.connect(user = "postgres", password = "abcd",host = "localhost",port = "5432", database="mydb")
        cursor = connection.cursor()

        sql1 = "Select * from hst_vw where tb_id = %s"

        record_to_update = (tbid,)

        cursor.execute(sql1,record_to_update)
        record = cursor.fetchall()
        connection.commit()

        status_arr = []

        for i in record:
            hs = OrderedDict()
            hs["signalvalue"] = i[0]
            hs["date"] = i[1]
            hs["tbid"] = i[2]

            status_arr.append(hs)

        json_date = json.dumps(status_arr, default = str)

        return json_date

if __name__ == '__main__':
    socketio.run(app)

A: If you put the setTimeout(latest_status, 10000); inside success block then it will run once the request is completed so your code will look something like this.
var signal = $.ajax({
    type: 'POST',
    url: '/status?tbid='+tbid,
    data: "",
    contentType: false,
    dataType: "json",
    async:false,
    cache: false,
    processData: false,
    success: function(data) {
        setTimeout(latest_status, 10000);
    },
});

I hope this will help.


text:
Q: How to combine two columns in a dataframe in R? I have a dataframe "df" like below:
Samples Status  last_contact_days_to    death_days_to
Sample1 Alive   [Not Available]       [Not Applicable]
Sample2 Dead    [Not Available]             724
Sample3 Dead    [Not Available]            1624
Sample4 Alive      1569               [Not Applicable]
Sample5 Dead    [Not Available]            2532
Sample6 Dead    [Not Available]            1271

I want to combine columns last_contact_days_to and death_days_to where in the result it should show only values not any other characters. And if both the columns has characters it should remove the whole row.
The result should look like following:
Samples Status  new_column
Sample2 Dead    724
Sample3 Dead    1624
Sample4 Alive   1569
Sample5 Dead    2532
Sample6 Dead    1271

A: We can change the [Not Available] and [Not Applicable] to NA and use coalesce
library(tidyverse)
df1 %>%
   mutate_at(3:4,
      funs(replace(., .%in% c("[Not Available]", "[Not Applicable]"), NA))) %>%
   transmute(Samples, Status,
             new_column = coalesce(last_contact_days_to, death_days_to)) %>%
   filter(!is.na(new_column))
#  Samples Status new_column
#1 Sample2   Dead        724
#2 Sample3   Dead       1624
#3 Sample4  Alive       1569
#4 Sample5   Dead       2532
#5 Sample6   Dead       1271

Note: As @Roland suggested, if the columns 3 and 4 have only numeric values in addition to the '[Not Available]', '[Not Applicable]', then the mutate_at can be changed to as.numeric.  It will convert all non-numeric elements to NA with a friendly warning and it would not have any problems
df1 %>%
    mutate_at(3:4, as.numeric)
    # if the columns are `factor` class then wrap with `as.character`
    # mutate_at(3:4, funs(as.numeric(as.character(.))))

NOTE: In the OP's dataset, these are factor class.  So, uncomment the code above and use that instead of directly applying as.numeric
data
df1 <- structure(list(Samples = c("Sample1", "Sample2", "Sample3", "Sample4",
"Sample5", "Sample6"), Status = c("Alive", "Dead", "Dead", "Alive",
"Dead", "Dead"), last_contact_days_to = c("[Not Available]",
"[Not Available]", "[Not Available]", "1569", "[Not Available]",
"[Not Available]"), death_days_to = c("[Not Applicable]", "724",
"1624", "[Not Applicable]", "2532", "1271")), .Names = c("Samples",
"Status", "last_contact_days_to", "death_days_to"),
 class = "data.frame", row.names = c(NA,
-6L))


text:
Q: How to use the parameter passed through url in validation of form I have following model:
class ArticleUser(models.Model):
   email = models.EmailField(max_length=200)
   fullname = models.CharField(max_length=200)
   article = models.ForeignKey(Article)
   create_time =models.DateTimeField()
   def save(self, *args, **kwargs):
       ''' On save, update timestamps '''
       self.create_time = datetime.datetime.utcnow().replace(tzinfo=utc)
       super(ArticleUser, self).save(*args, **kwargs)

   class Meta:
       unique_together = (('email','article'),)

I am passing the article_id through the url:
url(r'^articlebuffer/(?P<mid>\d+)/$',views.articlebuffer, name="articlebuffer"),

I need to use the article_id in the validation of the form so that article and email are unique together. How can I achieve it in the formset as well as in form
Here is my view using formset:
def articlebuffer(request,mid):
   ArticleBufferFormSet = modelformset_factory(ArticleUser,exclude=('article','create_time'))
    if request.method == 'POST':
        formset = ArticleBufferFormSet(request.POST)
        if formset.is_valid():
            instances = formset.save(commit=False)
            for instance in instances:
                instance.article_id = mid
                try:
                    instance.save()
                except:
                    error="Unique Constraint Error"

            return HttpResponseRedirect('')
    else:
        formset = ArticleBufferFormSet(queryset= ArticleUser.objects.none())
    return render (request, 'tracking/createarticlebuffer.html',{'formset':formset,
                                                       })

A: Include it with your POST data when you create a new ArticleBufferFormSet
formset = ArticleBufferFormSet(dict(request.POST.items() + {'article_id': article_id}))


text:
Q: Convert bitarray to string Could someone help me to convert bittarray to string properly?
I wrote this:
static String BitArrayToStr(BitArray ba)
        {
            byte[] strArr = new byte[ba.Length / 8];

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            for (int i = 0; i < ba.Length / 8; i++)
            {
                for (int index = i * 8, m = 1; index < i * 8 + 8; index++, m *= 2)
                {
                    strArr[i] += ba.Get(index) ? (byte)m : (byte)0;
                }
            }

            return encoding.GetString(strArr);
        }

but on the output I have this: "���*Ȱ&����L9��q�zȲP���*Ȱ&����L9��q�zȲP���*Ȱ&Y(W�" -many unrecognised symbols, what shoud I do?

A: Are you sure your input bit array is from a string that was encoded as ASCII?
Using your code I did the following test
string s = "Hello World";
byte[] bytes = Encoding.ASCII.GetBytes(s);
BitArray b = new BitArray(bytes);
string s2 = BitArrayToStr(b);

And s2 came out with the value Hello World as expected.
Update:
As described in the comments, the ASCII Encoder only handles the bytes 32-127 as printable characters, 0-32 which are control characters will display symbols and everything above 127 will use the ASCII fallback to handle the bad bytes.
Here is a quote from MSDN
http://msdn.microsoft.com/en-us/library/system.text.decoderfallback.aspx
A decoding operation can fail if the input byte sequence cannot be mapped by the encoding. For example, an ASCIIEncoding object cannot decode a byte sequence that yields a character having a code point value that is outside the range U+0000 to U+007F.
When an encoding or decoding conversion cannot be performed, the .NET Framework provides a failure-handling mechanism called a fallback. Your application can use predefined .NET Framework encoder and decoder fallbacks, or it can create a custom encoder fallback derived from the EncoderFallback and EncoderFallbackBuffer classes or a custom decoder fallback derived from the DecoderFallback and DecoderFallbackBuffer classes.

A: You can use this extension method:
public static string ToBitString(this BitArray bits)
{
    var sb = new StringBuilder();

    for (int i = 0; i < bits.Count; i++)
    {
        char c = bits[i] ? '1' : '0';
        sb.Append(c);
    }

    return sb.ToString();
}

A: You could use this method to convert the BiArray into a byte array:
public static byte[] ToByteArray(this BitArray bits)
{
    int numBytes = bits.Count / 8;
    if (bits.Count % 8 != 0) numBytes++;

    byte[] bytes = new byte[numBytes];
    int byteIndex = 0, bitIndex = 0;

    for (int i = 0; i < bits.Count; i++)
    {
        if (bits[i])
            bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));

        bitIndex++;
        if (bitIndex == 8) {
            bitIndex = 0;
            byteIndex++;
        }
    }

    return bytes;
}

And then:
BitArray ba = Fill();
string result = Encoding.ASCII.GetString(ba.ToByteArray());

A: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/e2403fd6-61ce-4487-b11a-fddcef40c87f


text:
Q: How to go to another page if fancybox right clicked? Friends,
I have an image gallery and it is functioning with fancybox plugin. This works perfectly on normal click.If I right click and open the link in a new tab,then the image is displaying in new tab.
<a href="<?php echo $data['path'];?>" class="fancybox" rel="road">View Image

What I want to do is,

*

*If the user clicks right mouse button and open in a new tab then i want to display the image on a page that i have designed.

Is this possible? or how can i fulfill my goal.Thanks

A: If your page is accessible you could just change the anchors href attribute and why not make it open in a new tab/window automatically with a target attribute?
<a href="<?php echo $mypage;?>" target="_blank" class="fancybox" rel="road">View Image

If you want to do this with javascript, see documentation on the "contextmenu" event (right-click)
How to add a custom right-click menu to a webpage?


text:
Q: Wrong Error Message Prints in the Wrong Place I am trying to validate an HTML form, and print out an error if the submissions are formatted wrong. But, instead of printing out an error below it all, it prints a very long message directly into the form.
I've tried reformatting almost everything and looking for errors, but so far I've found nothing.
In assignment_8_mortgaga_calc.php. This is the function that calls the other file.
function calcMortgage()
    {

      if(XMLHttpRequestObject) {

        XMLHttpRequestObject.open("POST", "assignment_8_mortgage_ajax.php");

        XMLHttpRequestObject.setRequestHeader('Content-Type',
          'application/x-www-form-urlencoded');

        XMLHttpRequestObject.onreadystatechange = function()
        {
          if (XMLHttpRequestObject.readyState == 4 &&
            XMLHttpRequestObject.status == 200) {

              var returnedData = XMLHttpRequestObject.responseText;

              processData(returnedData);
          }
        }

        var amountfinanced = document.getElementById('amountfinanced').value;
    var interestrate = document.getElementById('interestrate').value;

        var data = amountfinanced + '|' + interestrate + '|';

        XMLHttpRequestObject.send("data=" + data);
      }

      return false;

    }

This is the div under the form that is used to display the errors (theoretically)

Receiving data from the HTML form in the other file (assignment_8_mortgage_ajax.php)
<?php

$myData = $_POST['data'];  //This receives the data passed from the HTML form

list($amountfinanced, $interestrate) = explode('|', $myData);

Doing the validations:
//Do Validations

$msg = "ERROR: ";
$error_cnt = 0;

if (empty($amountfinanced))
{
    $msg .= "
Please enter an amount ";
    $error_cnt++;
} else {
    if (!is_numeric($amountfinanced))
    {
        $msg .= "
Amount entered, '".$amountfinanced."' is not numeric  ";
        $error_cnt++;
    }
}

if (empty($interestrate))
{
    $msg .= "
Please enter an interest rate  ";
    $error_cnt++;
} else {
    if (!is_numeric($interestrate))
    {
        $msg .= "
Interest rate entered, '".$interestrate."' is not numeric  ";
        $error_cnt++;
    }
}

Calculating Mortgage:
$interestrate_forcalc = $interestrate / 100 ;

$monthy_payment = ($amountfinanced * $interestrate_forcalc) / 12;

$monthy_payment_formatted = number_format($monthy_payment, 2);

And displaying the page:
if ($error_cnt > 0)
{
    print $msg;
} else {
    print $monthy_payment_formatted;
}

?>

Home Page of the Calculator
With Calculated Monthly Payment
When Clicked With Empty Fields
Here is the message that shows up in the little box:
Error Message
Sorry that I had to include an image only of the error message. When I pasted it into the text box, it wouldn't all show up. I expected it to show up in a div under the "Calculate Payment" button.
Any help would be very much appreciated. Thank you in advance.

A: I have solved the issue. I changed the section that said:
$interestrate_forcalc = $interestrate / 100 ;

$monthy_payment = ($amountfinanced * $interestrate_forcalc) / 12;

$monthy_payment_formatted = number_format($monthy_payment, 2);

and
if ($error_cnt > 0)
{
    print $msg;
} else {
    print $monthy_payment_formatted;
}

?>

and I changed it to say
if ($error_cnt > 0)
{
    echo $msg;
} else {
    $interestrate_forcalc = $interestrate / 100 ;

    $monthly_payment = ($amountfinanced * $interestrate_forcalc) / 12;

    $monthly_payment_formatted = number_format($monthly_payment, 2);

    echo $monthly_payment_formatted;
}

so that I can check if there is an error before calculating (like aynber said).
Then, I went to a part in my code that said:
    function processData(returnedData)
    {

      if (returnedData.substr(0,5) == 'ERROR')
      {
        var errorDiv = document.getElementById('errordiv');
        errorDiv.innerHTML = "ERROR ON DATABASE";
      } else {
        monthlypayment = document.getElementById('monthlypayment');
        monthlypayment.value = returnedData;
      }

      return false;
    }

which is where it takes the data and checks to see if there is an error, and I changed it to:
function processData(returnedData)
    {

        if (returnedData.substr(0,5) == 'ERROR')
        {
            var errorDiv = document.getElementById('errordiv');
            errorDiv.innerHTML = returnedData;
        } else {
            monthlypayment = document.getElementById('monthlypayment');
            monthlypayment.value = returnedData;

            var errorDiv = document.getElementById('errordiv');
            errorDiv.innerHTML = "";
        }

        return false;
    }

Now it properly displays the error messages.
Thank you!