text:
Q: Creating a data vizualization using Python vertical line Hello everyone I got a question about creating a data visualization using python.
I got this following data like this
        index   trk  rbegin  rend      suffix  prefix    id
        0     STWOS  130.30  129.00    NaN      H        1
        1   missing  129.00  128.00    NaN      H        1
        2     STWOS  128.00  125.61    NaN      H        1
        3   missing  125.61  125.00    NaN      H        1
         4      STWS  125.00  121.37    NaN      H        1
        5     STWOS  121.37  114.50    NaN      H        1
        6     DTWOS  114.50  106.84    NaN      H        1
       7     STWOS  106.84  101.50    NaN      H        1
      8      STWS  101.50   98.57    NaN      H        1
     9     STWOS   98.57   92.18    NaN      H        1
     10     STWS   92.18   90.25    NaN      H        1
     11    STWOS   90.25   86.00    NaN      H        1
     12    DTWOS   86.00   81.00    NaN      H        1
    13    STWOS   81.00   78.59    NaN      H        1
     14     STWS   78.59   75.07    NaN      H        1
   15    STWOS   75.07   69.71    NaN      H        1
    16     STWS   69.71   67.78    NaN      H        1
     17    STWOS   67.78   60.60    NaN      H        1
      18     STWS   60.60   58.00    NaN      H       1
     19    STWOS   58.00   55.40    NaN      H        1
      20     STWS   55.40   53.31    NaN      H        1
     21    STWOS   53.31   47.96    NaN      H        1
     22     STWS   47.96   45.00    NaN      H        1
     23    STWOS   45.00   43.05    NaN      H        1
     24     STWS   43.05   40.29    NaN      H        1

Basically I am trying to create a graph. It is a bunch of vertical from the rbegin to rend.
If the trk is STWOS it is just a black line from rbegin to rend. If the trck is missing it is a black dashed line. if the trk is dtwos it is two parallel black lines.
enter image description here
However I cannot get it too look like that I get this
enter image description here
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax

df1=pd.read_csv("line3.csv")
egs=df1["line_id"]
egs=df1["line_id"]
#for the column return only unique values
egs2=egs.unique()
b=1
a=df1[df1["line_id"]==b]
a=a.sort_values(by="rbegin",ascending=False)
a1=a.drop(["Unnamed: 0","index"],axis=1)
c=max(a1["rbegin"])
d=max(a1["rend"])
z=max(a1["rbegin"])
z2=min(a1["rend"])
ogig=z-z2
r=max(c,d)
a2=a1.to_numpy()
for i in range(0,len(a2)):
    plt.axis(xmin=1,xmax=3)
    yTick=np.arange(0,r,5)
    plt.title("line:"+str(b))
    #plt.yticks(yTick)
    if a2[i][0]=="STWOS":
        plt.vlines(2,a2[i][1],a2[i][2],linewidth=1,color="black")
    if a2[i][0]=="DTWOS":
            plt.annotate(str(a2[i][2]),(1.85,a2[i][2]),fontsize=5)
            plt.vlines(2,a2[i][1],a2[i][2],linewidth=1,color="black")
            plt.vlines(1.95,a2[i][1],a2[i][2],linewidth=1,color="black")
    if a2[i][0]=="DTWS":
        plt.vlines(2,a2[i][1],a2[i][2],linewidth=1,color="black")
        plt.vlines(2.05,a2[i][1],a2[i][2],linewidth=1/2,color="red")
        plt.axhline(y=a2[i][1],xmin=.51,xmax=.53,linewidth=1/7,color="red")
        plt.axhline(y=a2[i][2],xmin=.51,xmax=.53,linewidth=1/7,color="red")
    if a2[i][0]=="missing":
        plt.annotate(str(a2[i][2]),(1.85,a2[i][2]),fontsize=5)
        plt.vlines(2,a2[i][1],a2[i][2],color="black",linewidth=1,linestyles="dashed")
    if a2[i][0]=="STWS":
        plt.annotate(str(a2[i][2]),(1.85,a2[i][2]),fontsize=5)
        plt.vlines(2.05,a2[i][1],a2[i][2],linewidth=1/2,color="red")
        plt.axhline(y=a2[i][1],xmin=.51,xmax=.53,linewidth=1/7,color="red")
        plt.axhline(y=a2[i][2],xmin=.51,xmax=.53,linewidth=1/7,color="red")
        plt.vlines(2,a2[i][1],a2[i][2],linewidth=1,color="black")
fig = plt.figure()
plt.figure().clear()
plt.close()
plt.cla()
plt.clf()

A: Vertical lines, horizontal lines, and annotations are made into functions to eliminate redundancy in the code. We have also made the y-axis ticks more detailed. Also, since we are handling the data as a data frame, we have changed to using it as is. Also, if you have multiple ids, you need to add a loop process and add the x-axis position value to the drawing function.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax

def draw_vline(ax, r, x, l, c, ls='solid'):
    ax.vlines(x, r[1], r[2], lw=l, color=c, ls=ls)

def draw_hline(ax, r, l, c):
    ax.axhline(y=r[1], xmin=0.52, xmax=0.54, lw=l, color=c)
    ax.axhline(y=r[2], xmin=0.52, xmax=0.54, lw=l, color=c)

def annot(ax, r):
     ax.annotate(str(r[2]),(0.1,r[2]), fontsize=5)

fig,ax = plt.subplots(figsize=(1,8))
ax.axis(xmin=0, xmax=1)
x1,x2,x3 = 0.5,0.45,0.55
b=1

for idx, row in df1.iterrows():
    ax.set_title("line:"+ str(b))
    if row[0]=="STWOS":
        draw_vline(ax, row, x1, 1, 'k')
    if row[0]=="DTWOS":
        annot(ax, row)
        draw_vline(ax, row, x1, 1, 'k')
        draw_vline(ax, row, x2, 1, 'k')
    if row[0]=="DTWS":
        draw_vline(ax, row, x1, 1, 'k')
        draw_vline(ax, row, x3, 1/2, 'r')
        draw_hline(ax, row, 1/4, 'r')
    if row[0]=="missing":
        annot(ax, row)
        draw_vline(ax, row, x1, 1, 'k', ls='dashed')
    if row[0]=="STWS":
        annot(ax, row)
        draw_vline(ax, row, x3, 1/2, 'r')
        draw_hline(ax, row, 1/4, 'r')
        draw_vline(ax, row, x1, 1, 'k')

ax.set_xlim(0,1)
ax.set_ylim(40,130)
ax.set_yticks(np.arange(40.0,131.0,2.5))
ax.grid(color='0.9', lw=0.5, ls='dashed')

plt.show()


text:
Q: Merging objects for RestKit How can I map more than one object to one JSON-object?
Here are my two objects
#import <RestKit/RestKit.h>

@interface Account : NSObject
@property NSInteger id;
@property NSString* secret;
@end
@implementation Account @end

@interface Entry : NSObject
@property NSString* name;
@end
@implementation Entry @end

And I wish to map these objects to the following JSON:
    /* Goal JSON:
     {
     "id":10,
     "secret":"supersecret",
     "eventName":"Hayooo"
     }
     */

First try was using a RKMapperOperation directly:
void testMergeMap(){
    Account* account = [Account new];
    account.id = 10;
    account.secret = @"supersecret";

    Entry* entry = [Entry new];
    entry.name = @"Hayooo";

    RKMapperOperation* mapper = [[RKMapperOperation alloc]
                                 initWithRepresentation:@{@"account":account, @"entry":entry} mappingsDictionary:@{@"account.id": @"id", @"account.secret":@"secret", @"entry.name":@"eventName"}];
    [mapper start];
    RKMappingResult* result = mapper.mappingResult;
    NSLog(@"%@", result.dictionary.description);
}

But that crashes, can't really make something of the error.
So, how should I do this?
EDIT
I also tried this
RKObjectManager* testSimpleMap(Account* account, Entry* entry){
    RKObjectMapping* map = [RKObjectMapping requestMapping];
    [map addAttributeMappingsFromDictionary:
     @{@"account.id": @"id",
       @"account.secret": @"secret",
       @"entry.name":@"eventName"}];

    RKObjectManager* man = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://google.com"]];
    RKRequestDescriptor* requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:map objectClass:nil rootKeyPath:nil method:RKRequestMethodPOST];
    [man addRequestDescriptor:requestDescriptor];
    [man postObject:@{@"account":account, @"entry":entry} path:@"/" parameters:nil success:nil failure:nil];

    return man;
}

But we can't create requestDescriptors without a class, so that doesn't work. But I think it's useful to know what I'm aiming for. If that would work, that'd be great!

A: mappingsDictionary: should not be a dictionary of plain string keys and values. The keys should be key paths to the items to be mapped and the values should be RKMapping instances which describe how to map the data found at the key path.
Generally speaking, if you're just starting out I wouldn't use RKMapperOperation directly. I'd look at using RKObjectManager. It abstracts you away from inner details like this.
If you want to continue with what you have, check the example in the docs.

A: Creating a third object that models the relationship works, but I don't find it elegant enough.
@interface Both : NSObject
@property Account* account;
@property Entry* entry;
@end
@implementation Both @end

RKObjectManager* testRelationMap(Account* account, Entry* entry){
    /* Goal JSON:
     {
        "user":{
             "id":10,
             "secret":"supersecret",
        },
        "entry":{
            "name":"Hayooo"
        }
     }
     */

    Both* both = [Both new];
    both.account = account;
    both.entry = entry;

    RKObjectMapping* accountMap = [RKObjectMapping requestMapping];
    [accountMap addAttributeMappingsFromArray:@[@"id", @"secret"]];

    RKObjectMapping* entryMap = [RKObjectMapping requestMapping];
    [entryMap addAttributeMappingsFromArray:@[@"name"]];

    RKObjectMapping* relationMap = [RKObjectMapping requestMapping];
    [relationMap addRelationshipMappingWithSourceKeyPath:@"account" mapping:accountMap];
    [relationMap addRelationshipMappingWithSourceKeyPath:@"entry" mapping:entryMap];

    RKObjectManager* man = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://google.com"]];
    RKRequestDescriptor* requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:relationMap objectClass:[Both class] rootKeyPath:nil method:RKRequestMethodPOST];
    [man addRequestDescriptor:requestDescriptor];
    [man postObject:both path:@"/" parameters:nil success:nil failure:nil];
    return man;
}

There's a lot of code needed this way, but it's a solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to avoid warning for signed electron app for Windows? I have designed an electron app. I sign it on CI with certificate from www.digicert.com. But when users try to install it, they get a warning
"Windows protected your PC. Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk." (see the dialog with the error message).
I also tried to to create the app without signing it and the only difference between signed and unsigned apps is the name of the company in the warning (with or without the name).
How can I fix this behavior to prevent this warning from being shown to the user? Maybe using another certificate?
Could you, please give me a recipe on how to sign electron apps for Windows?

A: https://www.digicert.com/ms-smartscreen-application-reputation/

However, a warning appears if the software has been signed with a regular code signing certificate where the author or publisher has not yet established a reputation of trust. (Only Authenticode Certificates issued by a CA that is a member of the Windows Root Certificate Program can establish reputation.) As the software or its publisher gains a better reputation, the likelihood of a warning diminishes. Reputation for unsigned software is based on fingerprints while reputation based on signed software is based on the associated code signing certificate and the reputation of the CA that issued the code signing certificate.

This is something you cannot control as an application since smartscreen will evalutate based on reputation.


text:
Q: Does $\exp(-x) \sin(x)$ have infinite oscillations AND an infinite number of real roots? A Course of Pure Mathematics by G. H. Hardy states that a function oscillates if it does NOT tend to a limit or to $± \infty$. I find this definition difficult to square with $e^{-x}\sin(x)$. It has limit $0$ as $x$ tends to positive infinity and also an infinite number of roots, located at integer multiples of $π$ and as such it must have an infinite number of turning points and by extension must oscillate between positive and negative values indefinitely. I welcome comments which clarify this apparent 'contradiction'.

A: This is Hardy's definition copied from Project Gutenberg's A Course of Pure Mathematics.

62. Oscillating Functions. $\text{Definition.}$ When $ϕ(n)$ does not tend to a limit, nor to $+ ∞$, nor to $−∞$, as $n$ tends to $∞$, we say that $ϕ(n)$ oscillates as $n$ tends to $∞$.

According to this definition, the function $\,f(x)=e^{-x} \sin(x)\,$ does not
oscillate when $\,x \to \infty\,$, since the  limit at $\,+\infty\,$ exists, and is in fact $\,0\,$.
A related concept is that of oscillation of a function, and the oscillation of this $\,f(x)\,$ at $\,+\infty\,$ is $\,0\,$. Hardy's definition is equivalent to saying that a function oscillates at $\,+\infty\,$ iff  the oscillation at $\,+\infty\,$ is finite and strictly greater than zero.
It is true that $\,f(x)\,$ changes sign infinitely many times, and does so in every neighborhood of $\,+\infty\,$, but it "flatlines" and has the horizontal axis as an asymptote. Such functions are sometimes caled damped oscillations, though it would be less common to call them "oscillating functions" generically (nor does the OP quote any specific source that uses an alternative definition under which $\,f(x)\,$ would be called an "oscillating function").


text:
Q: Android ListView Populated from XML won't send data to new activity I have an array located in my strings.xml file that looks like the following.
<string-array name="array123">
<item>test1</item>
<item>test2</item>
<item>test3</item>
<item>test4</item>
<item>test5</item>
</string-array>

My listview is properly displayed on Activity 1, here is my onItemClick code
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent activityIntent = new Intent(this, Activity2.class);
String selectedItem = adapter.getSelectedItem().toString();
activityIntent.putExtra("my.package.dataToPass", selectedItem);
startActivity(activityIntent);

As soon as I tap an item from the list the screen just goes black and the application crashes. Here is my code for Activity 2
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("my.package.dataToPass");
TextView word = (TextView) findViewById(R.id.word);
word.setText(myVal);

I'm not sure why this isn't working. I'm just trying to pass the string that was selected to show as text on the 2nd activity. I've been searching for a day and a half now.
I did try
activityIntent.putExtra("my.package.dataToPass", id);

but this just seemed to pass an empty screen.
Any help would be much appreciated. Obviously I'm not passing the right data in the intent.

A: As I can see, you are implementing the Click listener (onItemClick) rather than Select listener(onItemSelected). By default when you click on a ListView item it doesn't change its state to "selected"
Plz use adapter.getItem(position) instead of adapter.getSelectedItem()
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    String selectedItem  = adapter.getItem(position).toString();
}


text:
Q: UPS is not working for heavy weight products I have Magento ver. 1.9.1.1. I have used the default UPS shipping method and my setting for it as listed below.

*

*Enabled for Checkout = yes

*UPS Type = united parcel service

*Gateway URL = http://www.ups.com/using/services/rave/qcostcgi.cgi

*Packages Request Type = divide to equal rate

*Container = customer packaging

*Destination Type = residential

*Weight Unit = LBS

*Pickup Method = customer counter

*Maximum Package Weight  = 5000

*Minimum Package Weight  = 0.1

*Calculate Handling Fee = fixed

*Handling Applied = per package

*Handling Fee = 0

*Allowed Methods = all option selected

*Free Method = none

*Free Shipping with Minimum Order Amount = disabled

*Ship to Applicable Countries = all allowed countries

*Debug = no

*Show Method if Not Applicable = no

Now I have two products A (weight : 150.0000) and B (weight : 111.0000)
When I add A to shipping cart and check "Estimate Shipping and Tax" for united states - delaware - 19702. It shows me as expected options for UPS. But when I add B after A and try "Estimate Shipping and Tax", it does not show any shipping method. When i check log it gives me:

UPSOnLine5%The maximum per package weight for the selected service
  from the selected country is 150.00 pounds.%1035%

but my product have the larger weights.

A: After spending a lot of time and testing I have the solution which ultimately Magento OOTB provides, Its just a matter for how to use it.
We can ship Bundle items separately. While creating bundle products use the following option.

Along with this, we have one more setting which is based on Clients's business logic.

The Maximum package weight will always be 150 due to UPS limitation. "Packages Request Type" has two options

*

*Divide to equal weight (one request): If total cart weight is for eg. 180lb, ups will calculate the rate for 180/2=90lb and if for eg. for 90lb UPS says it will cost $100, the final cost will be $100*2 = 200. i.e. two packages of 90lbs each.

*Use origin weight (few requests): If cart weight is 180lbs with one child product of 50lb and other of 130lbs, UPS will calculate the separate rate for 130lbs and 50lbs package by sending two requests to API and sum them up. For eg. of 130lbs package costs $100 and 50lbs package cost $60 the final shipping cost will be $100+$60=$160.
Let me know which is suitable in our case.

A: Maximum package weight for UPS is 150 LBS.
You broke it with Maximum Package Weight = 5000
I'd like to see a UPS delivery car being loaded with a forklift...
Set it back to 150 LBS and make sure your per item weights don't exceed 150 LBS if you want to ship via UPS.
Note that UPS LTS is a different service and needs a different module. They actually send out a freight truck that can be loaded with a forklift.

A: The issue is with your setting  Maximum Package Weight = 5000

The maximum per package weight is 150.00 pounds

Try by changing

Container

to Large Express Box or Customer Supplied Package


text:
Q: Use of template  in C++ when declaring classes and functions I am quite new to the topic of templates in C++. Why in the following toy example code do we have to precede the class's and each function's name with template <class T> (meaning why do we need it, at all)?
Is it possible to modify the code not to use template <class T> everywhere?
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class Stack {   private:
    vector<T> elements;

  public:
    void push(T const &);
    void pop();
    T top();
    bool empty(); };

template <class T>
void Stack<T>::push(T const &elem) {
    elements.push_back(elem); }

template <class T>
void Stack<T>::pop() {
    if (elements.empty()) {
        throw out_of_range("Stack<>::pop(): empty stack");
    } else {
        elements.pop_back();
    }
}

template <class T>
T Stack<T>::top() {
    if (empty()) {
        throw out_of_range("Stack<>::top(): empty stack");
    }
    return elements.back();
}

template <class T>
bool Stack<T>::empty() {
    return elements.empty();
}

int main() {
    try {
        Stack<int> intStack;       // Stack of ints
        Stack<string> stringStack; // Stack of strings

        // Manipulate integer stack
        intStack.push(7);
        cout << intStack.top() << endl;

        // Manipulate string stack
        stringStack.push("hello");
        cout << stringStack.top() << std::endl;
        stringStack.pop();
        stringStack.pop();
    }
    catch (exception const &ex) {
        cerr << "Exception: " << ex.what() << endl;
        return -1;
    }
}

A: You have to include template <class T> in each member definition because that is part of the name of the member.
You can define the functions within the class-template body, for only one line with template <class T>
template <class T>
class Stack {
  private:
    vector<T> elements;

  public:
    void push(T const &) {
      elements.push_back(elem); }
    void pop() {
      if (elements.empty()) {
          throw out_of_range("Stack<>::pop(): empty stack");
      } else {
          elements.pop_back();
      } }
    T top() {
      if (empty()) {
          throw out_of_range("Stack<>::top(): empty stack");
      }
      return elements.back(); }
    bool empty() {
      return elements.empty(); } };

A: C++ is a statically typed language.
Since this is the case, say I wanted a function to check the minimum or maximum of two values.
I could create a function like the following:
int max(int a, int b) { return (a > b) ? a : b; }

But this only works for int types. If I want one for a double or uint64_t or FooBarClass, I would need to create additional functions:
double max(double a, double b) { return (a > b) ? a : b; }
uint64_t max(uint64_t a, uint64_t b) { return (a > b) ? a : b; }
FooBarClass max(FooBarClass a, FooBarClass b) { return (a > b) ? a : b; }

Why in the following toy example code do we have to precede the class's and each function's name with template ?

In C++, a template is a way to introduce a concept known as "generics". With generics, you no longer need to concern your self with creating a function for each type, the type will be deduced from the template function signature.
So instead, I could write the following:
template < typename T > // the typename or class keywords are synonymous when declaring a template
T max(T a, T b) { return (a > b) ? a : b; }

The inclusion of template < typename T > to the function signature indicates to the compiler that this function is a "generic" function and must be processed accordingly.
If, on the other hand, you just had the following:
T max(T a, T b) { return (a > b) ? a : b; }

The compiler will expect T to be an explicit type (like typedef int T;).
A template can be applied to a class or function, and both at the same time:
template < typename T >
class Wrapper {
    public:
        Wrapper(const T& val) : _val(val) {}
        // ... other code

        template < typename X >
        operator X()
        {
            return static_cast<X>(this->_val);
        }

        T operator+(const T& val)
        {
            return this->_val + val;
        }

        friend std::ostream& operator<<(std::ostream& os, const Wrapper& val)
        {
            os << val._val;
            return os;
        }

    private:
        T _val;
};

int main(int argc, char* argv[])
{
    Wrapper<int> x(42);
    // template deduction will call Wrapper::operator X() with X being a double
    double d = x;
    // template deduction will call Wrapper::operator X() with X being a long
    long l = x;
    // this actually calls T operator+(const T& val) with val = 10 and T = int
    int i = x + 10;

    std::cout << "x = " << x << std::endl  // 42
              << "d = " << d << std::endl  // 42
              << "l = " << l << std::endl  // 42
              << "i = " << i << std::endl; // 52
    return 0;
}

You can also explicitly define a template type, this is known as template specialization
and is beyond the scope of this answer given your understanding of templates at the current.

Is it possible to modify the code not to use template  everywhere?

Yes and no. Yes, you can remove the template < class T > signature definition, but, as mentioned, the signature of the class/function takes on a completely different meaning.
Hope that clears up a little bit. Templates, when used properly, are a very powerful tool in C++.


text:
Q: NSCollectionView crashes when creating items My NSCollectionView crashes when calling makeItem(withIdentifier identifier: String, for indexPath: IndexPath). numberOfItemsInSection returns the correct value. If I call makeItem... in viewDidLoad rather than in itemForRepresentedObject I see an error indicating that the indexPath is out of bounds. How can this be?
The collection view loads like this:
class TagCollectionViewController: NSViewController, NSCollectionViewDataSource {

  fileprivate static let itemIdentifier = "TagItem"

  @IBOutlet var collectionView: NSCollectionView!
  fileprivate var tags = List<Tag>.init()

  override func viewDidLoad() {
    super.viewDidLoad()

    let nib = NSNib(nibNamed: "TagCollectionViewItem", bundle: nil)
    collectionView.register(nib, forItemWithIdentifier: TagCollectionViewController.itemIdentifier)

    collectionView.dataSource = self
}

(The List collection is a Realm class)
During viewWillAppear() the tags collection is populated from a ReSwift state:
override func viewWillAppear() {
  for image in mainStore.state.selectedImages {
    for tag in image.tags {
      tags.append(tag)
    }
  }

  super.viewWillAppear()
}

A: Solved it.
When I created the .xib for the item I added an NSCollectionViewItem object but didn't wire up the view to my custom view.

To recap, for anyone who gets caught out by this, the steps to creating a NSCollectionViewItem are:

*

*Create the nib and configure your views

*Add an NSCollectionViewItem object to your nib

*Wire up your view (and any other views) to the object

*Register the nib with the collectionView in your view controller


text:
Q: Crieria.Root class unable to get Local attribute which is a composite key attribute I have Entity class UniversityBasicInformation.java and UniversityBasicInformation.hbm.xml files. I want to write a criteria query. I am getting error at root.get("surveyYear"), surveyYear) in my code.
The error says that

Java.lang.illegalArgumentsException: unable to find local attribute with the given name survey year.

On Debug I identified that Composite key attributes are unable to be identified by JPA.
public class UniversityBasicInformation implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @JsonProperty
    private String aisheCode;
    @JsonProperty
    private Integer surveyYear;
    @JsonProperty
    private String state;
    @JsonProperty
    private String name;
    @JsonProperty
    private String district;
    @JsonProperty
    private String type;
}

<hibernate-mapping>
    <class name="gov.nic.aishe.read.pojo.UniversityBasicInformation" table="university_basic_information"
        schema="readonly">
        <composite-id>
            <key-property name="aisheCode" type="java.lang.String">
                <column name="aishe_code" />
            </key-property>
            <key-property name="surveyYear" type="java.lang.Integer">
                <column name="survey_year" />
            </key-property>
        </composite-id>
        <property name="state" type="java.lang.String">
            <column name="state" />
        </property>
        <property name="district" type="java.lang.String">
            <column name="district" />
        </property>
        <property name="type" type="java.lang.String">
            <column name="type" />
        </property>
    </class>

</hibernate-mapping>

public List<UniversityBasicInformation> getUniversityList(Integer surveyYear, String stateCode, String type,
        String speciality, String districtCode) {

    CriteriaBuilder builder = sessionFactory.getCurrentSession().getCriteriaBuilder();
    CriteriaQuery<UniversityBasicInformation> criteriaQuery = builder.createQuery(UniversityBasicInformation.class);
    Root<UniversityBasicInformation> root = criteriaQuery.from(UniversityBasicInformation.class);

    List<Predicate> predicates = new ArrayList<Predicate>();

    predicates.add(builder.equal(root.get("surveyYear"), surveyYear)); //line with error

    if (stateCode != null) {

        predicates.add(builder.equal(root.get("state"), stateCode));

    }

I expect that survey year parameter value to be added as predicate. But the above code is giving error as unable to find local attribute with given name [surveyYear]

A: It seems you have chosen a discouraged mapping.
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-compositeid

Unfortunately, this approach means that a persistent object is its own identifier. There is no convenient "handle" other than the object itself. You must instantiate an instance of the persistent class itself and populate its identifier properties before you can load() the persistent state associated with a composite key. We call this approach an embedded composite identifier, and discourage it for serious applications.
The persistent class must override equals() and hashCode() to implement composite identifier equality. It must also implement Serializable.

To search by entire key, you would need to override equals() and pass entire  UniversityBasicInformation to
predicates.add(builder.equal(root, anUniversityBasicInformation));

I also debugged org.hibernate.query.criteria.internal.path.AbstractFromImpl.locateManagedType() and neither id nor its parts are there in the model.
Clearly, this is not what we want.
I suggest you follow the advice from the link above and modify your mapping by using a class for your composite id.
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/components.html#components-compositeid
On top of that, are you stuck with xml mapping? Annotations are prevalent these days.


text:
Q: Referenced file contains errors I'm having a problem when I try to validate the application context for my java web application with spring and zk spring.
my applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:util="http://www.springframework.org/schema/util" xmlns:zksp="http://www.zkoss.org/2008/zkspring/core"

        xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.zkoss.org/2008/zkspring/core http://www.zkoss.org/2008/zkspring/core/zkspring-core.xsd ">

I receive the following error:
Referenced file contains errors (http://www.zkoss.org/2008/zkspring/core/zkspring-core.xsd)

The error detail stated that I should have a white space between systemid and publicid. I've added the white space, but the error remains.

work with
  Eclipse Kepler
  JDK 1.7
  zkoss framework
  spring


text:
Q: Why is this recursive selection sort not working I tried to run the code but it just gets stuck. NO error no warning nothing.Is there a better way to write a recursive selection sort?
#include <iostream>

using namespace std;

void scan(int *arr, int size){
    for(int i = 0; i < size; i++){
        cin >> arr[i];
    }
}

void print(int *arr, int size){
    for(int i = 0; i < size; i++){
        cout << arr[i] << " ";
    }
    cout << "\n";
}

void swap(int *p1, int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

void insertion(int *arr, int size){
    if(size <= 1)return;
    int i, max = size - 1;
    for(int i = 0; i < size; i++){
        if(arr[i]  > arr[max])max = i;
    }
    swap(&arr[max], &arr[i]);
    insertion(arr, size - 1);
}

int main(){
    int *arr;
    int size;
    cout << "Enter the size of the array - ";
    cin >> size;
    arr = (int*)malloc(size*sizeof(int));
    cout << "Enter the elements of the array - ";
    scan(arr, size);
    print(arr, size);
    insertion(arr, size);
    print(arr, size);
}

I feel like there is something wrong with the base case of the recursion. How do you generally solve these types of problems.

A: There was 1 small problem in your code. When you call the swap function in the insertion function you have to call it with &arr[max] and &arr[size-1], you can also use i-1, as the value of i is size here.
Code Attached for insertion function
void insertion(int *arr, int size){
    if(size <= 1)return;
    int i, maxIndex = 0;
    for(i = 0; i < size; i++){
        if(arr[i] > arr[maxIndex]) maxIndex = i;
    }

    swap(&arr[maxIndex], &arr[size-1]);
    insertion(arr, size - 1);
}

The way to debug are many, you can learn to use the gnu debugger which is gdb or use print statements to find out where your code is going wrong.


text:
Q: Code is Working Properly in NetBeans but not in Eclipse I have tried the following jsp file in both IDEs. It is working good in NetBeans, but it is not working in Eclipse. The program is to get the time from a NTP server.
Code is as follows
 <%--
Document   : GetNTP
Created on : May 21, 2013, 2:21:29 PM
Author     : Maximin
--%>
<%@page import="java.net.InetAddress"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import ="java.util.Date"%>

<%@page import="org.apache.commons.net.ntp.NTPUDPClient"%>
<%@page import="org.apache.commons.net.ntp.TimeInfo"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

<%
    String TIME_SERVER = "time.nist.gov";
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    long returnTime = timeInfo.getReturnTime();
    Date time = new Date(returnTime);
            SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
            out.println(sdf.format(time));
    %>

When i run this in eclipse I get as
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 17 in the generated java file
Only a type can be imported. org.apache.commons.net.ntp.NTPUDPClient resolves to a package

An error occurred at line: 18 in the generated java file
Only a type can be imported. org.apache.commons.net.ntp.TimeInfo resolves to a package

 An error occurred at line: 18 in the jsp file: /GetTime.jsp
NTPUDPClient cannot be resolved to a type
15:
16:
<%
17:         String TIME_SERVER = "time.nist.gov";
18:         NTPUDPClient timeClient = new NTPUDPClient();
19:         InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
20:         TimeInfo timeInfo = timeClient.getTime(inetAddress);
21:         long returnTime = timeInfo.getReturnTime();

Why is it so?
What should I do to make it run on Eclipse?

A: Worked for me:
"Right click on your project and choose Properties (it's at the bottom...probably). Deployment Assembly is one of the pages. If the jar with the NTP classes is not in WebContent/WEB-INF/lib or otherwise on the server, make sure it is on this page."
Answered by nitind


text:
Q: Liveboot: Make more RAM available I'm running Ubuntu 16.04.3 LTS with LXDE desktop environment. I'm running it off a thumbdrive as a live boot, using a startup script to install my programs and configurations into the RAM disk. I used UNetBootin to install the .ISO on the thumbdrive. There is no swap partition in use to my knowledge, nor do I want one. There is no persistent storage on the thumbdrive, nor do I want any. For persistent storage, I use a single partition hard drive that shows up in my /media/ubuntu/ area. This is on a high end laptop with 16 GB of RAM.
The problem I'm encountering is the system becomes slow/lagged, particularly the external keyboard I'm trying to use.
When I run df -m I see:
$ df -m
Filesystem     1M-blocks   Used Available Use% Mounted on
udev                7850      0      7850   0% /dev
tmpfs               1573     42      1532   3% /run
/dev/sdb1           7535   1516      6020  21% /cdrom
/dev/loop0          1429   1429         0 100% /rofs
aufs                7865   7589       277  97% /
tmpfs               7865     28      7838   1% /dev/shm
tmpfs                  5      1         5   1% /run/lock
tmpfs               7865      0      7865   0% /sys/fs/cgroup
tmpfs               7865      1      7865   1% /tmp
tmpfs               1573      1      1573   1% /run/user/999
/dev/dm-0         469324 424657     20805  96% /media/ubuntu/harddrive

I believe that 97% in use for aufs is what's causing the external keyboard lag and other system performance problems. After all, when I first boot up and prior to installing programs, the aufs in use percentage is way smaller and the external keyboard doesn't lag.
It looks like only 8 GB of RAM is being allocated to aufs. Meanwhile, look at those five tmpfs rows. The 78xx available makes it seem that 8 GB of RAM is being pointlessly dedicated to the tmpfs.
What are those tmpfs rows? Are they the same thing as a swap partition?
How can I make more of the total RAM (16 gb) available to aufs?
Sometimes I run
$ sudo su
root@ubuntu:/# sync; echo 1 > /proc/sys/vm/drop_caches
root@ubuntu:/# sync; echo 2 > /proc/sys/vm/drop_caches
root@ubuntu:/# sync; echo 3 > /proc/sys/vm/drop_caches
root@ubuntu:/# sync

And this seems to help a tiny bit. Running 'free -m' before and after running the above confirms that running the commands increases available memory. But I'm not sure what the above commands are actually doing or if/how they relate to the 'df -m' and aufs stuff.
Thanks (and in case it's relevant, I'm switching to Lubuntu soon)!


text:
Q: Convert sexagesimal to decimal I've been studying astronomy and I've encountered 3 different (sexagesimal) ways to write angles.

*

*hh mm ss  -  hours minutes and seconds

*dd '' '''' - degrees, arcminutes and arcseconds.

*+/- dd mm ss -
For example most sources give the right ascension of an object in the first format while the declination is given in the third.
Why are two coordinates that usually come together given in two different ways?
How can one convert each one of the formats in to decimal degrees?

A: Gotta love traditions.
Start with the 2nd one.  d m s to decimal degrees.
Start at the left:  60 s = 1 m    so to convert decimal minutes
dm := m + s/60  where := is the usual 'is assigned to' and dm is decimal minutes.
Repeat for decimal degrees
dd = d + dm/60
This works for declination too.
easier to calculate
dd = d + m/60 + s/3600
Right ascension is different, because it's using time as it's unit instead of degrees.  However both hours and degrees are divided into minutes and seconds, but they aren't the same size.
Since it's 24 hours around, an hour is equal to 15 degrees.  A minute of hour angle = 1/60 of 15 degrees = 1/4 degrees, and a second of hour angle =
 1/240 degree.  So if RA is given in h m s
decimal ra = 15 * h + m/4 + s/240


text:
Q: What native javascript method is capable of creating a server? I am new to nodejs. I have successfully installed it on my computer (and rebooted). I have created a hello_world.js inside My Documents directory (I'm on a windows xp computer):
console.log("hello world");
var my_http   = require( 'http' );
var my_server = my_http.createServer( ... ) ;
...

I have successfully opened a windows command prompt, cd'd to the My Documents directory, executed the .js file, and received 'hello world' output. And I have navigated my browser to the running localhost port (for my experiment: http://localhost:1337/)
But I have 2 major questions based on this:
1 - where is 'http' ... I suppose it is a module(?), but I do not find such a directory within my nodejs installation directory.
2 - how does the http method, createServer, actually create a server? Does native javascript have such a method?

A: The node.js standard library is written in Javascript and C++, and C++ modules can be loaded in js code via process.binding. Specifically for http.createServer, it's a wrapper around _http_server.Server, which invokes net.Server, which uses the C++ TCP wrapper .
See here for more details.
To answer the second question, createServer just creates and populates the control object, the actual work is in listen, which first creates a handle and this is where C++ code is actually called for the first time.

A: 1) http is a built-in node module. You can read up on the documentation for it here: https://nodejs.org/api/http.html. Node provides a lot of modules out of the box to assist w/ everyday operations (interacting w/ file systems, making HTTP requests, creating servers, working with paths, etc.)
2) Not sure what you mean by "native" JavaScript. JavaScript is just a language. I think you're really asking about the runtime environment. If you are using JavaScript in the browser, then no you can't start an HTTP server. But Node.js runs on the server, so in this environment it can do all sorts of stuff that you can't do w/ JavaScript in the browser, such as access the file system.


text:
Q: Bigcommerce custom private apps development storefront content injection blueprint and stencil I am trying to create a custom private app for my client, this app will interact in the storefront.
eg. I need to put a button on storefront product page and when that button click popup will show and the content of popup will come from my private app website.
The problem in broad is I cannot find a documentation wherein it will discuss all for eg. how to support blueprint and stencil for UI or content that I'll inject on the storefront.
By the way, I already successfully setup the hello-world-app-php-silex.
The specific problem that I am facing now is I am able to inject the content( button and bootstrap modal ) for blueprint framework, however, I cannot make it works on the stencil.
Any suggestion or tutorial link?
Thanks!

A: BigCommerce recently released the ability to programmatically inject scrpts on Stencil using the Script API here is the API documentation and guidelines on how to approach the blueprint vs stencil
https://developer.bigcommerce.com/api/v3/scripts.html
Also, you can find some examples on injecting snippets by editing theme files here:
https://stencil.bigcommerce.com/docs/checkout-injection#footer however, using the API is highly recommended. That way the theme can be kept on the upgrade path.
I hope that helps.


text:
Q: It says I've visited the site even if I haven't (local storage) Greetings denizens of stackoverflow.  I have a problem.  I am trying to program something in my portfolio where each time I visit one of my projects, "you have visited X" is logged into the console when the user returns.  For proof of concept, I tried this with my project called "train timer."  However, it says, in the console, that I have visited train timer even if I haven't.  This happens even when I clear my all my browsing data/history/whatever.  What's the deal?  Here is my code.
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Portfolio</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

      Dennis Markham

About Me

Portfolio

Contact

Solo Endeavors

Crystal Collector

Train Timer

Bomb Defuser

Austin Weather Monitor

React Photo Gallery

Javascript Roulette Wheel (WIP)

Works in Progress (Solo)

AngularJS Whiteboard (WIP)

Group Work

Cache-ual Corner

A: The localStorage object stores data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
you need to forcefully remove the localStorage like
    var visitedTrain = localStorage.getItem("trainTimer");

        if (visitedTrain === "true")
        {
          console.log("train timer visited");
          localStorage.removeItem('trainTimer');
        }

this code will work fine,
hope this solves your problem

A: Nevermind, figured it out.  I changed "true" to "visited."
    $(".thumbnail").click(function()
{

  console.log("function firing: setting " + this.id + " to true");

  localStorage.setItem(this.id, "visited");
//set visited to true
})

and
 var visitedTrain = localStorage.getItem("trainTimer");

    if (visitedTrain == "visited")
    {
      console.log("train timer visited");
    }


text:
Q: How do you Record and Playback editing events on a contenteditable div? I'm trying to find a way to write some unit-tests that can be used to write/test new wysiwyg html editors or just the default browser behavior for contenteditable divs.
I want to record the keypresses (perhaps other events too, but keypresses are the most interesting) or just write the events manually and then play them back later on a div. In the end I would use it to simulate little html editing sessions and see if you end up with the expected serialized html.
BUT, I can't get the following to invoke the default browser behaviour:
$(mydiv).trigger('keydown', {type: "keydown", keyCode: 13, which: 13});

(It doesn't insert a line-break or break up the paragraph or do anything, really.)
I have also tried things like:
$(mydiv).trigger('textInput', {type: "textInput", data: 'H', target: mydiv});

(Which should have inserted the letter H)
and I even tried to keep the original event objects around and then trigger them like this:
$(mydiv).trigger(eventObject);

(where eventObject is an actual  key event I got previuosly and then kept around)
Part of the problem is that I don't know what the minimum event object attributes are that I have to keep around and then send back later. (All of it isn't an option because you can't just dump the whole event as JSON due to all the circular references.)
Another part of the problem is I'm not even sure how to properly focus the editable
At a minimum I need to be able to create a new empty div, set contenteditable="true" and then "insert some text", place the cursor in the middle of it and "press enter" by reading and replaying commands from a log of editing events.

Here's why I need it:
The idea is to write a lot of tiny tests that can be run in any cutting edge browser (I'm only really interested in the latest versions of Chrome, Firefox, Opera and maybe IE9) to see where they differ from what's expected. It is for a survey of what the latest browsers do, not for what 10 year old browsers did.
I can then come up with some kind of checklist of where the browsers deviate from each other. This could then be used by anyone that wants to write a new wysiwyg editor, but ideally the "core" of it - the parts that don't contain or care about any interface/chrome - could be written once and shared by them all.
Individual editors handle things like inserting/removing inline elements, linking text, inserting/editing images, inserting lists and tables, changing a p to an h1 and so on. I'm only really interested in the keypress-level editing here.
Some of these tests could also be used similar to the way javascript frameworks do "feature detection" to see which bits of behavior has to be intercepted/patched so that enter and backspace always behaves the same, so that the cursor is always on the correct side of a b tag and so on.

A: You won't be able to do what you want here, I don't think. Most browsers do not allow script to fully simulate a keypress: you can fire the event but the associated browser behaviour (updating the value of an input, editing the content of a contenteditable element, moving the caret, etc.) will not happen.
Regarding documenting contenteditable in current browsers, there is an ongoing effort by WHATWG to specify various APIs around contenteditable. Currently in the works is a spec for execCommand() (there are various threads concerning this on the WHATWG mailing list, check the archives). Preceding this was some research done on current browser behaviour. There's also ongoing work on a new version of the DOM Range spec, now incorporating Selection as well. For Enter key behaviour in contenteditable elements, see this thread.


text:
Q: Write-only queue? I'm working on an application that loads untrusted assemblies via an interface. Each of those assemblies should be able to add one or more GameAction objects to a thread-safe queue used by the server.
The first iteration of design was to just pass the queue--something like this:
public interface IGameClient
{
  void HandleStateChange(IGameState gameState,
                         ref Queue<IGameAction> actionQueue);
}

But, the problem with this is that it gives an untrusted assembly access to a shared queue, allowing it to manipulate other members of the queue and discover information about other queue actions.
The second pass was:
public interface IGameClient
{
  void HandleStateChange(IGameState gameState);
  GameActionDelegate event HasNewEvent; // passes IGameAction as a parameter
}

The problem with this is that it doesn't necessarily allow for the ordering or grouping of actions.
What I'm really hoping for is to be able to pass a reference to an object that encapsulates the thread-safe queue, but only exposes Enqueue(). But, I'm afraid that an untrusted assembly could manipulate a private Queue object using reflection.
So, what's the best way to handle this?

A: Thoughts in no particular order:
1) Events do guarantee ordering (or at least, your implementation could guarantee whatever ordering you want, and the simplest implementations will preserve ordering).
2) I don't see why you'd want to pass the queue by reference in the first example of the interface. It may be worth checking that you understand parameter passing and "ref".
3) If you come up with an interface which only exposes Enqueue then the implementation presumably won't be a Queue<T>. It might contain a Queue<T>, but if you really don't trust assemblies not to mess around with your private members, you should load them in such a way that you don't grant them the relevant reflection permissions.
Another alternative might be to pass in an Action<IGameAction> which the client can call when it wants to add an item to the queue. The delegate would be created from whatever Enqueue method you've got.

A: Don't expose the queue at all--simply expose a method on a facade that allows the GameClient to submit an entry that the GameServer will place on the internal queue.

A: You could make the HandleStateChange method return an IEnumerable<IGameAction>, IList<IGameAction> or IGameAction[]:
public interface IGameClient
{
  IGameAction[] HandleStateChange(IGameState gameState);
}

Then use that return value to add actions to the queue.

A: Pass a newly-created instance of queue, and when the HandleStateChange returns, merge the stuff from your dummy queue into the real queue.


text:
Q: Configure sort order with RecordSetVal and standard controller? We have a simple implementation, utilizing a standard controller and RecordSetVal to pass selected records from a list view to a PDF output.  It appears by default the records sort by RecordName.  I don't see a way to re-order via the standard controller (preferably by the List View sort).  Any input?
To clarify, I know we can write a custom controller to reorder and pass back to the visualforce output, but I'd like to use the standard controller if there's a way to do so.
<apex:page standardController="Payment__c"
       renderAs="pdf"
       readOnly="true"
       standardStylesheets="false"
       showHeader="false"
       applyHtmlTag="false"
       applyBodyTag="false"
       docType="html-5.0"
       recordSetVar="payments">

        <apex:pageBlock >
            <apex:repeat value="{!selected}" var="p">

                            <apex:outputText value="{0,date, MM'/'d'/'yyyy}"><apex:param value="{!p.Payment_Date__c}"/></apex:outputText>

                            {!p.Organization__r.Name}

                            <apex:outputtext value="{0,number,#,###,###.00}"><apex:param value="{!p.Paid_Amount__c}"/></apex:outputtext>

                            {!p.Check_Amount_Words__c}

                        {!p.Check_Memo__c}

                            {!p.Organization__r.Type}

                            <apex:outputText value="{0,date, MM'/'d'/'yyyy}"><apex:param value="{!p.Payment_Date__c}"/></apex:outputText>

                            {!p.Organization__r.Name}

                            <apex:outputtext value="{0,number,#,###,###.00}"><apex:param value="{!p.Paid_Amount__c}"/></apex:outputtext>

                            {!p.Check_Amount_Words__c}

                            {!p.Payment_Notes__c}

                            {!p.Name}

            </apex:repeat>
        </apex:pageBlock>

</apex:page>


text:
Q: No Next and Previous button while importing project in Intellij after intellij Idea 2019.2 update I am using Intellij Idea Community edition. It has been updated recently and the current version of Intellij Idea is 2019.2 community edition. I did not see any Next and Previous button in the dialog boxes while importing any maven or gradle project. Find the screen shorts.

As you can see there are no buttons in the bottom of the dialog boxes. I want to know whether it is the default behavior in the new edition of Intellij Idea or is there any problem with my installation.

A: As per the following link, it was a regression bug.
https://youtrack.jetbrains.com/issue/IDEA-222331
Now it has been fixed. I am using Intellij Idea Ultimate Version 2019.3.2. Find below the attached screen shot below. I have redacted the licensed portion with black color. I hope that this bug may not be there in Community edition.


text:
Q: Using sed to delete all vowels How do I delete every vowel from a file?
AEIOU Example: Hi Im Brad --> H m Brd
I know deleting one character is like sed 's/a//' right? 's/a/e/i/o/u/' doesn't work.

A: What you want to do is specify a group of letters that you want to remove. This is done using [].
sed 's/[aeiouAEIOU]//g'

So for example
echo "Hi Im Brad" | sed 's/[aeiouAEIOU]//g'

Gives me
H m Brd

A: For single character deletions, you can use the tr utility:
tr -d '[aeiouAEIOU]'

A: sed 's/[aeiouAEIOU]*//g' <your file>
For more information on sed see: http://www.pement.org/sed/sed1line.txt


text:
Q: How to Select by month and year in SQLite In my SQlite table, it has DateTime field example : order_date
How to perform these tasks:

*

*Retrieve records by Month like Jan, Feb, Mar and so on in Year 2013.

*Retrieve records by Begin date and End Date with criteria like above(1)

Thanks

How to convert `DateTime` for format requires by SQLite for (1) and (2)

    DateTime  Dt = new DateTime.Today();
    Month-year ?  Year?

    Records = await db.QueryAsync("Select * From Purchase where order_date=" + "Month-Year");

In SQLite , which operator is correct : `=` or `==`?

----- Update:

using SQlite:strftime

SELECT * FROM tablename WHERE strftime('%Y', Order_Date) = '2013' AND strftime('%m', Order_Date) = '2';

1) Is there a function to get month as number from DateTime?

A: I assume you are using sqlite-net.
As such you may use parameters in your query:
//Returning all records from February 2013
Records = await db.QueryAsync<Purchase>("Select * From Purchase where order_date >= ? and order_date < ?", new DateTime(2013, 2, 1), new DateTime(2013, 3, 1));


text:
Q: AudioBufferSourceNode - start vs noteOn Is there any reason to use AudioBufferSourceNode.start(...) over AudioBufferSourceNode.noteOn(...)?

A: Yes.  start() will work in Mozilla's nascent Web Audio implementation, and will work in Safari in the future. noteOn() won't.

A: As of today NoteOn does not work in Google Chrome, so you must use start(). (2014-07-24)
(This should be a comment but I don't have the rep.)

A: My company's developers confirmed that noteOn() began to fail in browsers that use recent versions of WebKit, but that to start() is a reliable alternate.  Sorry, I don't know the specific version of WebKit, but affected browsers include:

*

*All native browsers for iOS 10.3 (and above).  This is due to Apple's requirement to use WebKit on that platform, including Safari, Chrome, Firefox, and Opera.  As an example of a non-native "browser", Puffin is really a remote-access portal to a LINUX window, so it is unaffected.  (Apple recently pulled Puffin Academy from the store, but it may be a misunderstanding of the method used, or may be a tightening of their requirements.)

*Safari 10.1 (and above) for Mac OS X 10.10 through macOS 10.12 (and above).


text:
Q: QGLWidget::makecurrent(): GetDC() failed. Invalid Window handle I have a requirement to get pictures saved off screen. I have used QGLwidget::grabframebuffer to get this done. While it works fine on MAC, it fails with an error "QGLWidget::makecurrent(): GetDC() failed. Invalid Window handle " on Windows 7. Only one opengl context gets created in the process. But i have observed that if I add QGLWidget to the Mainwindow, i am able to get the pictures saved. I need not do this on MAC to get the pictures.
I am not sure what could have gone wrong.
thanks!!

A: This is because on MacOS an OpenGL context is always attached to the root window of a multi window application. (this is not seeable with Cocoa, but it was with Agl/Cgl)
On windows you can create the context with any window (that has the flag popup, child and one other i forgot) then bind it to any window with MakeCurrent. to expect it to work fine you only need to be sure you have only one thread and one context in your whole app. the spec says otherwise, but in practice it never works. (though you may not see it in a small app, and just see rares random crash)
also, I don't know in QT how the capture of the framebuffer works, with readpixels or with the horrible GDI copy hack, if it is the latest then it is normal that it doesn't work, it can only be done on screen surfaces.


text:
Q: Why can you import a class with the same name as a nested class? Consider the following code:
import java.util.Calendar;

class Demo
{
    class Calendar {}

    public static void main (String[] args) {
      // System.out.println(Calendar.DAY_OF_WEEK);  // Would be an error.
    }
}

This code compiles fine; but if you refer to Calendar within Demo, you are referring to Demo.Calendar, not java.util.Calendar.
The import is clearly redundant; but it seems strange that it is allowed, considering you're not allowed to import a class with the same simple name as a top-level class defined in the same compilation unit (per JLS Sec 7.5.1):
import java.util.Calendar;  // error: Calendar is already defined in this compilation unit

class Calendar {}

Is there a practical reason why such an import as in the first code example would not be a compile-time error?

A: The only case I can come up with is where you have a twice (or more) -nested class with the same name as the import:
import java.util.Calendar;

class Demo {
  static class Nested {
    static class Calendar {}

    static void useNested() {
      System.out.println(Calendar.class);  // Demo.Nested.Calendar
    }
  }

  static void useImported() {
    System.out.println(Calendar.class);  // java.util.Calendar
  }

  public static void main(String[] args) {
    Nested.useNested();
    useImported();
  }
}

Ideone demo
In this case, the nested Calendar isn't automatically visible outside the scope of the Nested class, so the imported Calendar class is used outside, e.g. in the useImported method.
I wouldn't really describe this as a "practical" use, though - it's just plain confusing as to which is used in each context, and definitely worth avoiding. It still interested me that this case exists, though.

I suppose there is another similar case:
import java.util.Calendar;

class Demo {
  static void useImported() { ... }
}

class Demo2 {
  class Calendar {}

  static void useNested() { ... }
}

(where these classes are in the same compilation unit). Basically the same idea as above.

A: I suppose, if you import a class, it's visible in the global space of that compilation unit. But if you name your compilation unit or top level class the same as the import, then you are basically conflicting it with the import and hence it'll be ambiguous for JVM to know which is which. and since its compiling a class, it'll give an error for import.
Also, when it's inside another class, you are shadowing the import over there. It's just similar in the way as global/class level variables and method level variables hiding them if defined with the same name.
Hope this helps.


text:
Q: Nested Params in Spring Controllers is asking for Neting in JSP file Path. How to deal with that? So this is my controller code :
`
package org.inventorymanagement.controller;

import org.inventorymanagement.databaseservice.BorrowBookDatabaseService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BorrowPageController {

    @RequestMapping(value = "/borrow/{bookName}/{issuerName}", method = RequestMethod.GET)
    public ModelAndView searchForBookName(@PathVariable("bookName") String bookName, @PathVariable("issuerName") String issuerName) {
        ModelAndView mav = new ModelAndView("borrow.jsp");
        String rs = (String) new BorrowBookDatabaseService().borrowBookFromBookTable(bookName, issuerName);

        return mav;
    }

}

Here is the error which i am seeing on my webpage:
JSP file [/borrow/ABC/borrow.jsp] not found
ABC is my bookName.
Any suggestions how can i overcome it ?
I tried to change the path of jsp inside ABC folder and it works fine. But since ABC is generic how many folders i will made ?


text:
Q: Getting data from different tables between dates when each table has it on date modified Like to get some views from you all, regarding one scenario i'm struggling with currently. Below is a problem statement
I have Table A , B , C
A has below column
user|modified date| wokred_on A | ..some more related to user operation
B has columns
user | modified date |  worked on B | ..some other columns
C has columsn
user | modified date | worked on C| ..some other columns
these tables are not have any direct relation except then user.
we have to pull data from these tables for a user between given dates with the count op action or work he has done between a given date range?
my struggle here is these each table has it's own date modified if a date range selected which is not in other column but still i need to pull the data as user has worked on it in between dates.
can it be possible to select these dates and have the in one column so that one can put that in where clause and having outer joins to pull other records ?
Sorry for this big problem statement. any suggestions are very much appreciated
Below is a use case.just extending the assumption given by littlefoot
First, test case:
SQL> create table a (cuser varchar2(10), modified_date date,action );

varchar2 (10) )
    Table created.
SQL> create table b (
Table created.cuser varchar2(10), modified_date date,action

varchar2 (10) );
SQL> create table c (cuser varchar2(10), modified_date date,action

varchar2 (10) ));
Table created.

SQL> insert into a values ('lf', date '2018-05-01', 'issue raised');

1 row created.

SQL> insert into a values ('mc', date '2018-05-01', 'issue raised ');

1 row created.

SQL> insert into b values ('lf', date '2018-05-01',issue raised');

1 row created.

SQL> insert into b values ('lf', date '2018-05-01','issue resolved');

1 row created.

SQL> insert into c values ('if', date '2018-05-28',' issue resolved');

1 row created.

SQL> insert into c values ('mc', date '2018-05-13','issue raised');

1 row created.

SQL> insert into c values ('mc', date '2018-05-13','issue resolved');

1 row created.

SQL> alter session set nls_date_format = 'yyyy-mm-dd';

Session altered.

SQL> select * from a;

CUSER      MODIFIED_D. ACTION
---------- ----------
lf         2018-05-01     issue raised
mc         2018-05-01    issue raised

SQL> select * from b;

CUSER      MODIFIED_D    ACTION
---------- ----------.         ______________
lf         2018-05-01    issue raised
lf         2018-05-01.  issue resolve

SQL> select * from c;

CUSER      MODIFIED_D. ACTION
---------- ----------
If         2018-05-28.      issue resolve
mc         2018-05-13.    issue raised
mc         2018-05-13.    issue resolve

CUSER    DATE             CNT_ISSUE_RAISED   CNT_ISSUE_RESOLVED

------  -------           ---------------   -------------------
    if   2018-05-01             2                   1
    lf   2018-05-28             0                   1
    mc   2018-05-01             0                   1
    mc   2018-05-13             1                   1

A: This is how I understood the question.
First, test case:
SQL> create table a (cuser varchar2(10), modified_date date);

Table created.

SQL> create table b (cuser varchar2(10), modified_date date);

Table created.

SQL> create table c (cuser varchar2(10), modified_date date);

Table created.

SQL> insert into a values ('lf', date '2018-05-01');

1 row created.

SQL> insert into a values ('mc', date '2018-05-15');

1 row created.

SQL> insert into b values ('lf', date '2018-05-07');

1 row created.

SQL> insert into b values ('lf', date '2018-05-08');

1 row created.

SQL> insert into c values ('jw', date '2018-05-28');

1 row created.

SQL> insert into c values ('mc', date '2018-05-13');

1 row created.

SQL> insert into c values ('mc', date '2018-05-22');

1 row created.

SQL> alter session set nls_date_format = 'yyyy-mm-dd';

Session altered.

SQL> select * from a;

CUSER      MODIFIED_D
---------- ----------
lf         2018-05-01
mc         2018-05-15

SQL> select * from b;

CUSER      MODIFIED_D
---------- ----------
lf         2018-05-07
lf         2018-05-08

SQL> select * from c;

CUSER      MODIFIED_D
---------- ----------
jw         2018-05-28
mc         2018-05-13
mc         2018-05-22

Query which returns desired result - number of rows per each user in every table, in desired date period. As I use SQL*Plus, variables are preceded by && to avoid multiple insert requests. In a tool you use, that might be a colon (:).
SQL> select nvl(nvl(a.cuser, b.cuser), c.cuser) cuser,
  2         count(distinct a.modified_date) cnt_a,
  3         count(distinct b.modified_date) cnt_b,
  4         count(distinct c.modified_date) cnt_c
  5  from a full outer join b on a.cuser = b.cuser
  6         full outer join c on a.cuser = c.cuser
  7  where a.modified_date between &&date_from and &&date_to
  8     or b.modified_date between &&date_from and &&date_to
  9     or c.modified_date between &&date_from and &&date_to
 10  group by nvl(nvl(a.cuser, b.cuser), c.cuser)
 11  order by 1;
Enter value for date_from: '2018-05-01'
Enter value for date_to: '2018-06-01'

CUSER           CNT_A      CNT_B      CNT_C
---------- ---------- ---------- ----------
jw                  0          0          1
lf                  1          2          0
mc                  1          0          2

SQL>


text:
Q: Why won't Python recognize that PyPDF2 is installed? I'm trying to import PyPDF2 and it won't work. I installed it using pip, then tried it with pip3, it is installed. When I try to import I get the error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'PyPDF2'

I'm using Python 3.7. I found a similar issue here, doesn't seem any of the answers worked and I tried them myself to the same results.

A: If anyone else runs into this problem try using sys.path to find the site-packages directory. I copied my PyPDF2 packages into my Python37 directory and now it works.


text:
Q: Solve for $y$ in ellipse locus of points Considering the following equation:
$$
\sqrt{\left(x_{F1}-x\right)^{2}+\left(y_{F1}-y\right)^{2}}+\sqrt{\left(x_{F2}-x\right)^{2}+\left(y_{F2}-y\right)^{2}}=k
$$
With this equation being a locus of points that forms and ellipse, where:
$$
F1 = (x_{F1},y_{F1})
$$
$$
F2 = (x_{F2},y_{F2})
$$
As shown below:

Source: Wikipedia
How would this equation be arranged for two solutions of y?


text:
Q: Is it good to use STL in making new softwares? Hi I am currently working on an open source project and want to use STL in it. But I am confused that is correct to depend on STL only or it will be good to use Qt like libraries. Because I want to make it cross platform supported. Please suggest.
STL: Standard Template Library for C++

A: That is some confusion in this question.
STL is a part of Standard Library of C++; specifically covering containers and algorithms (and iterators, as a glue between the two).
Qt is cross-platform application framework which purpose is, first and foremost, to provide facilities for abstracting you from platform. It also covers some of functionality provided by STL (i.e. it provides its own containers: as I understand, mostly for historical reasons).
You can freely mix'n'match both libraries. AFAIK you can even use STL algorithms on Qt containers (meaning that Qt containers are STL compliant).
So, answering your question, it is of course good to use STL for new software: provided it is properly supported by your compiler, and you know how to use it.


text:
Q: SUMIF only where value in column is a multiple of 100 in Google Sheets I need to add values (expenses) from a column, only if the value in another column (accounts) is a multiple of 100.
We have a table where one column (A) has accounts and sub-accounts numbers (100,200,300, 303, 303.1,400, etc.) and another column (B) with expenses.
I'm looking for a formula in Google Sheets to sum all values in column B, only if the account number is a multiple of 100 (100,200,300...).
I'd appreciate any advice!

A: try:
=SUM(FILTER(B1:B, NOT(ISNUMBER(SEARCH(".", (A1:A/100))))))

or just:
=SUM(FILTER(B:B; MOD(A:A; 100)=0))

or even:
=INDEX(SUMIF(MOD(A:A; 100); 0; B:B))

works too:
=SUMPRODUCT((MOD(A:A; 100)=0)*B:B)


text:
Q: I am attempting to deploy a django project on an Ubuntu server but I keep getting a "Connection timed out" error I set the project up with a viturualhost and I have configured the apache server accordingly as far as I understand. I initially tested the server out with a basic django skeleton project which ran perfectly fine, both on the django server on port :8000 and also on the apache server with just the plain domain address. After uploading the project I configured and migrated the database and installed all requirements. I am able to use the "python manage.py runserver" command with no visible errors. Also the apache error log does not display any serious errors that could possibly be causing the problem. Is there something I'm missing?

A: The problem is the firewall (ufw). All I had to do was deactivate the firewall $ sudo ufw disable   or give apache permission to query/make requests to the server. Instructions on configuring the firewall can be found here.


text:
Q: PynamoDB Creating GSI and LSI Python Error Hello All hope you are fine
i am reaching out  for some help as I am learning and experimenting with pynamodb
Goal to create LSI and GSI
Phase 1: create index and popular with fake data
import os
import boto3
import json
from faker import Faker
import random
import pynamodb.attributes as at
import datetime
from datetime import datetime
from pynamodb.models import Model
from pynamodb.attributes import *

AWS_ACCESS_KEY = ""
AWS_SECRET_KEY = ""
AWS_REGION_NAME = "us-east-1"

faker = Faker()

class UserModel(Model):

    class Meta:
        table_name = 'table_learn'
        aws_access_key_id = AWS_ACCESS_KEY
        aws_secret_access_key = AWS_SECRET_KEY

    email = UnicodeAttribute(null=True)
    job = UnicodeAttribute(null=True)
    first_name = UnicodeAttribute(range_key=True)
    last_name = UnicodeAttribute(hash_key=True)
    company = ListAttribute()

UserModel.create_table(billing_mode='PAY_PER_REQUEST')

average = []

for i in range(1, 20):

    starttime = datetime.now()

    UserModel(email=faker.email(),
              first_name=faker.first_name(),
              last_name=faker.last_name(),
              job=faker.job(),
              company = [faker.company() for i in range(1,6)]
             ).save()

    endtime = datetime.now()

    delta = endtime-starttime

    elapsed_time = int((delta.seconds * 1000) + (delta.microseconds / 1000))

    average.append(elapsed_time)
    print("Exection Time: {} MS ".format(elapsed_time))

averagetime = sum(average)/ len(average)
print("\nAverage Time in MS: {} ".format(averagetime))

All good so far
Phase 2 Setting GSI and LSI
from pynamodb.indexes import GlobalSecondaryIndex, AllProjection
from pynamodb.attributes import NumberAttribute

class ViewIndex(GlobalSecondaryIndex):
    """
    This class represents a global secondary index
    """
    class Meta:
        aws_access_key_id = AWS_ACCESS_KEY
        aws_secret_access_key = AWS_SECRET_KEY
        projection = AllProjection()

    email = UnicodeAttribute(hash_key=True)

class UserModel(Model):

    class Meta:
        table_name = 'table_learn'
        aws_access_key_id = AWS_ACCESS_KEY
        aws_secret_access_key = AWS_SECRET_KEY

    email = UnicodeAttribute(hash_key=True)
    job = UnicodeAttribute(range_key=True)
    first_name = UnicodeAttribute()
    last_name = UnicodeAttribute()
    company = ListAttribute()
    view_index = ViewIndex()

UserModel.create_table()
Error
on DynamoDB I don't see GSI and LSI what am I doing wrong please guide if possible

As you can see up to the point of creating table and populating with data I am fine I am struggling with GSI and LSI
partition key is last name and sort key is first_name
to learn and understand concepts better I am trying to set different partition key and sort key using pynamodb but unable to do so

A: i dont know if you fixed this, but for whoever may see this post next and find themselves in the same situation. i think this example is missing the name of the index and the reference to the name from the main table. the index may also be missing an attribute of with range_key=True
from pynamodb.indexes import GlobalSecondaryIndex, AllProjection
from pynamodb.attributes import NumberAttribute

class ViewIndex(GlobalSecondaryIndex):
"""
This class represents a global secondary index
"""
    class Meta:
        index_name = "my_index_name"
        aws_access_key_id = AWS_ACCESS_KEY
        aws_secret_access_key = AWS_SECRET_KEY
        projection = AllProjection()

    email = UnicodeAttribute(hash_key=True)

class UserModel(Model):

    class Meta:
        table_name = 'table_learn'
        index = "my_index_name"
        aws_access_key_id = AWS_ACCESS_KEY
        aws_secret_access_key = AWS_SECRET_KEY

    email = UnicodeAttribute(hash_key=True)
    job = UnicodeAttribute(range_key=True)
    first_name = UnicodeAttribute()
    last_name = UnicodeAttribute()
    company = ListAttribute()
    view_index = ViewIndex()


text:
Q: glew Missing GL version c++ using SDL2 2.0.5 and glew 2.0.0 I am following the tutorial "Making Games With Bens" (https://www.youtube.com/user/makinggameswithben) on OpenGL and I get this

missing gl version

every time I try to initialize glew.
I have reinstalled glew and SDL2 many times.
I don't understand what I'm doing wrong.
I am using glew 2.0.0 and SDL2 2.0.5
headerfile:
#pragma once

#include <string>
#include <vector>

//Graphics
#include <SDL2\SDL.h>
#include <GL\glew.h>
class Display
{
public://functions:
    Display(int m_width, int m_heigth, const char title []);
    void update();
    ~Display();
private:

public://variables:
    std::vector<char> error;
    int width;
    int heigth;
private:
    //Window pointer
    SDL_Window * m_window;

};

.cpp file:
#include "Display.h"

Display::Display(int m_width, int m_heigth, const char title[])
{
    m_window = nullptr;
    width = m_width;
    heigth = m_heigth;
    //Initialize SDL
    SDL_Init(SDL_INIT_EVERYTHING);

    m_window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, m_width, m_heigth, SDL_WINDOW_OPENGL);
    //error 1:
    if (m_window = nullptr) {
        error.push_back(255);
    }
    //error 2:
    SDL_GLContext glContext = SDL_GL_CreateContext(m_window);
    if (glContext = nullptr) {
        error.push_back(254);
    }

    const GLenum GLerror = glewInit();
    //error 3:
    if (GLerror != GLEW_OK) {
        error.push_back(GLerror);
    }

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
}

void Display::update()
{
    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    SDL_GL_SwapWindow(m_window);
}

Display::~Display()
{
    delete m_window;
    SDL_Quit();
}

A: You may have to do:
glewExperimental = GL_TRUE;

right before
glewInit();

This will allow GLEW to use OpenGL features above OpenGL version 2.0.


text:
Q: Undefined reference when compiling OpenSSL I'm not sure what to do here, I ran make and got this:
make[2]: Entering directory `/tmp/openssl-1.0.1/test'
( :; LIBDEPS="${LIBDEPS:--L.. -lssl -L.. -lcrypto  -ldl}"; LDCMD="${LDCMD:-gcc}"; LDFLAGS="${LDFLAGS:--DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -fno-exceptions -Wa,--noexecstack -m64 -DL_ENDIAN -DTERMIO -O3 -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM}"; LIBPATH=`for x in $LIBDEPS; do echo $x; done | sed -e 's/^ *-L//;t' -e d | uniq`; LIBPATH=`echo $LIBPATH | sed -e 's/ /:/g'`; LD_LIBRARY_PATH=$LIBPATH:$LD_LIBRARY_PATH ${LDCMD} ${LDFLAGS} -o ${APPNAME:=rc4test} rc4test.o ${LIBDEPS} )
rc4test.o: In function `main':
rc4test.c:(.text+0x30): undefined reference to `OPENSSL_cpuid_setup'
collect2: ld returned 1 exit status
make[2]: *** [link_app.] Error 1
make[2]: Leaving directory `/tmp/openssl-1.0.1/test'
make[1]: *** [rc4test] Error 2
make[1]: Leaving directory `/tmp/openssl-1.0.1/test'
make: *** [build_tests] Error 1

I think this is a gcc thing, but I am not sure how to approach this. Should I be compiling this manually?

A: I ran into the same problem, and was able to solve it by passing adding -DOPENSSL_PIC to the config call:
./config -fPIC -DOPENSSL_PIC


text:
Q: Translating IEnumerator from seconds into minutes? I am unsure how to translate this into my script. I have a bird script that hovers over the player. I have everything set in float seconds but I want that my FadeIn() function and Ienumerator GameReset() use 1 minute instead. This will help because I want players to have some time to shoot down the bird without having the issue of the game automatically resetting in a matter of seconds.The point of my game is that if players take too long the bird will attack them causing a reset window to appear.
public class OwlEx : MonoBehaviour {

    public float waitTime = 10.0f;
    public float fadeTime = 3.0f;
    public float betweenFadesTime = 2.0f;

    // Flag to determine whether or not the player may respond.
    public bool canRespond = false;

    // Flag to determine if the player has responded within the wait time.
    public bool hasResponded = false;

    public GameObject enemy;

    void Start()
    { StartCoroutine(EnemyFadeIn(fadeTime, betweenFadesTime, waitTime)); }

    void Update() {
        if ((Input.GetKeyDown(KeyCode.S)) && (canRespond))
        { hasResponded = true; }
    }

    IEnumerator EnemyFadeIn(float timeToFade, float timeBetweenFades, float timeToWait) {
        Debug.Log("An Enemy Is Fading In");
        // Simulating Fade In Time.
        yield return new WaitForSeconds(timeToFade);
        // Fade in
         iTween.FadeTo(enemy, 1, 1);
         Invoke("SetMaterialOpaque", 1f);
        Debug.Log("An Enemy Has Appeared");

        yield return ListenForInput(timeToFade, timeBetweenFades, timeToWait);
    }

    IEnumerator EnemyFadeOut(float timeToFade, float timeBetweenFades, float timeToWait) {
        Debug.Log("An Enemy Is Fading Away");
        // Simulating Fade Out Time.
        yield return new WaitForSeconds(timeToFade);
        // Fade out
         SetMaterialTransparent();
         iTween.FadeTo(enemy, 0, 1);
        Debug.Log("An Enemy Has Departed");
        // Simulating Time Between Fades.
        yield return new WaitForSeconds(timeBetweenFades);

        yield return EnemyFadeIn(timeToFade, timeBetweenFades, timeToWait);
    }

    // Responsible for reacting to the 'S' key input.
    IEnumerator ListenForInput(float timeToFade, float timeBetweenFades, float timeToWait) {
        canRespond = true;
        Debug.Log("Press the 'S' Key to Destroy the Enemy!");
        float startTime = Time.time;

        // Check every 0.25 seconds to see if the S key was pressed.
        while (Time.time < (startTime + timeToWait)) {
            if (hasResponded) {
                Debug.Log("The 'S' Key was Pressed!");
                hasResponded = false;
                canRespond = false;
                yield return EnemyFadeOut(timeToFade, timeBetweenFades, timeToWait);
            }
            yield return new WaitForSeconds(0.25f);
        }

        Debug.Log("The 'S' Key was not Pressed!");
        canRespond = false;
        yield return ResetGame();
    }

    IEnumerator ResetGame() {
        Debug.Log("Game is Performing a Reset");
        Simulating Game Reset Time.
        yield return new WaitForSeconds(30);
        Debug.Log("Game has Restarted. End of Coroutine!");
    }
}

A: float waitTimeSeconds = 0.0f;
float waitTimeMinutes = 1.0f;
int formatMinutesFlag = 1;    //this flag is 1 if you want to add minutes
yield return new WaitForSeconds(waitTimeSeconds + formatMinutesFlag * waitTimeMinutes * 60f);

You can put this in a function if you really don't want to multiply by 60 everytime you want to use minutes instead of seconds.
Edit: Added the part where you multiply by 60. Thanks for reminding me.


text:
Q: Neo4j: matching nodes with 2 more properties in common I am working with data from a csv file which contains 4 columns of data: hotelName, hotelPool, hotelSpa, hotelGym, where hotelName is the unique name of the hotel, hotelPool lists what kind of pool the hotel has, hotelSpa lists what kind of spa the hotel has, and hotelGym lists what kind of gym the hotel has.
Sample data as follows:
Row 1 "California", "Full-size", "Full-size", "Fully-equipped"
Row 2 "Yorba", "Full-size", "None", "Full-equipped"
Row 3 "Heartbreak", "None", "Full-size", "Full-equipped"
Row 4 "Chelsea", "Full-size", "Full-size", "Fully-equipped"
I want to match these hotels if they share 2 or more features in common.
For example, California has 2 features in common with Yorba - both hotels have full-size pools and fully-equipped gyms.
California also has 2 features in common with Heartbreak - both hotels have full-sized spas and fully equipped gyms.
California also has 3 features in common with Chelsea - both hotels have full-sized pools, full-sized spas, and fully equipped gyms.
My desired output is pairs of hotels that have 2 or more features in common, as follows:
Row 1 California, Yorba, 2
Row 2 California, Heartbreak, 2
Row 3 California, Chelsea, 3
How do I match based on 2 or more features?

A: This should do it:
// get all hotels
MATCH (h:Hotel)

// create hotel pairs, avoiding duplicates
WITH COLLECT(h) AS hotels
UNWIND hotels AS h1
UNWIND hotels AS h2
WITH h1,h2
WHERE id(h1)>id(h2)

//loop through keys and count same values
WITH h1, h2,
     REDUCE(i=0, key in keys(h1)  |
            i
            + CASE WHEN h1[key] = h2[key] THEN 1 ELSE 0 END
     )  AS sameCount

// set your limit
WHERE sameCount >=3

RETURN h1.hotelName, h2.hotelName , sameCount


text:
Q: Creating an exception when pointing a domain using A record (Shopify) I am setting up a Shopify site using a custom domain.  However, I have old links on that domain that I don't want to break once I point it to Shopify.  I also have old parked domains on top of this domain that I don't want to break.
Shopify instructs you to set up an A record for the domain (so when I go to www.mydomain.com I see my Shopify store).  But I want to set up exceptions such that www.mydomain.com/my-seo-link won't show Shopify, or will allow me to forward to its replacement at Shopify.
An added complication is I also have parked domains on top of my domain that I want to remain pointing to my old server.
Is there such thing as a URI exception to an A record?

A: Put this code in your DOCUMENT_ROOT/.htaccess file of www.mydomain.com:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$ [NC]
RewriteRule ^my-seo-link http://otherdomain.com%{REQUEST_URI} [NC,R=301,L]

A: Go through your list of special URL's and use the Shopify built-in redirect mechanism to point all your old content at the new location for it on your Shopify store's domain. The DNS system is old, well understood and you need to use it in this case as you cannot have a Shopify store on a domain AND host that same domain on another server under your control. Use redirects. That is what they are they for.


text:
Q: Quotients of unipotent groups Let $U (\mathbf{R})$ be the standard unipotent subgroup of $SL(3, \mathbf{R})$. So $U(\mathbf{R})$ is the group of 3 by 3 upper triangular matrices with 1s on the diagonal. I am interested in the quotient space $U (\mathbf{R})/ U (\mathbf{Z})$. I think it is just the cube, $[0,1]^3$, but I am having difficulty writing the actual map. The only non-obvious part is the (1,3)-entry where the addition is not straightforward. Also is the generalization that one gets the $\frac{1}{2}(n^2 - n)$ dimensional cube for the standard unipotent subgroup of $SL(n, \mathbf{R})$ correct?

@ Bill
Your answer helped clear a lot of confusion but it also created a number of new questions:

*

*So basically $U(\mathbf{R})$ has three copies of $\mathbf{R}$ however they way they are knit together is not the simple direct sum. Is that right?

*If I pick an element $u \in U$ is the group generated by $u$ isomorphic to $\mathbf{G}_a$ ?

*Is the space $U (\mathbf{R})/ U (\mathbf{Z})$ compact? The Haar measure on $SL(3, \mathbf{R})$ gives a measure on $U(\mathbf{R})$. Then presumably I get a measure on $U (\mathbf{R})/ U (\mathbf{Z})$ what is the volume of the quotient with respect to this measure? Is there a place I can find these calculations?
Ultimately I am interested in the arithmetic quotient $SO(3)\backslash SL(3, \mathbf{R}) / SL(3, \mathbf{Z})$ and $U (\mathbf{R})/ U (\mathbf{Z})$ is supposed to be its 'base' and the end result should be an algebraic surface (hence a 4-dimensional real manifold I think).

A: The group $U(\mathbb Z)$ is nilpotent, but not isomorphic to $\mathbb Z^3$.
The quotient space is not the torus $T^3$ (= cube with opposite sides identified).
The fundamental domain which glues together to make the quotient can be described, but I'm not sure it's what you really want or need: there are easier ways to understand it.
The element $c $ with the 1,3 entry equal to 1 generates the center of $U(\mathbb Z)$, with quotient $\mathbb Z^2$, and it is the commutator of the other two elementary matrices $a$ and $b$.  Geometrically, the
quotient has a map to a torus $T^2$ (factoring out by your troublesome entry) with fiber (preimage of any point) a circle, but the circles form a fiber bundle that is not trivial.
You can map all this into R^3 as a group of affine transformations, and visualize
 how it works:  $c$ acts as a  vertical translation.
The element $a$ translates in the $x$ direction by one unit, but at the same time shears planes perpendicular to the x axis so the y-axis develops a slope of -1/2.  The element $b$
is similar, translating in the $y$ direction, taking vertical lines to vertical lines and shearing the $x$ axis to have slope 1/2.  Now look at what happens when you do the commutator
$a^{-1} b^{-1} a b$.  This group is also called the Heisenberg group.
alt text http://dl.dropbox.com/u/5390048/AffineGeometries.jpg
In higher dimensions, the picture is similar but more elaborate, with iterated circle bundles over previous stuff, exhibiting additional shearing.  (There is more than one reasonable way to choose coordinates, so don't be surprised if you don't get the exact same description when you work through details).
You can find pictures and descriptions in my book on Three-dimensional Geometry and Topology (among other places). It's the basic example for one of the 8 geometries for 3-manifolds.  I first learned this picture  by reading Poincare.

Addendum
In response to the added questions:
Keivan Karai and Max have addressed most of it, in comments to the question.
It's true, there are many sources to read about these things. Many people have studied the geometry of $SO(3)\backslash SL(3,\mathbb R)/SL(3,\mathbb Z)$, it's challenging to come to grips with it completely, but a vast amount is known.
You can interpret $SO(3)\backslash SL(3, \mathbb R)$ fairly concretely as the space of positive definite quadratic forms of determinant 1 on $\mathbb R^3$, and it has a natural metric in which a path of quadratic forms has arc length equal to the total strain it takes to do the associated deformations --- you can imagine an object, perhaps a ball, made of a highly viscous and inelastic material, perhaps modeling clay, that you can squeeze into different shapes that don't spring back.  You're squeezing the ball into different ellipsoid shapes via linear transformations, and keeping track of how much energy it takes. (use the $L^2$ norm of the first derivative, as measured in using the current shape).
In 3 dimensions, quadratic forms have 6 coefficients, but the condition that the determinant is 1 brings it down to  5.   To think about $SO(3)\backslash SL(3,\mathbb R)/SL(3,\mathbb Z)$, imagine a 3-torus with a flat metric, that is, $\mathbb R / \mathbb Z^3$ for some action of $\mathbb Z$.
The set of possible shapes for the torus, up to isometry is how you can interpret it.
(This is beccause $SL(3,Z)$ is the group of affine automorphisms of the torus, up to translations, so it acts on the set of Euclidean metrics on a torus with fixed basis --- in the double coset space, we're forgetting the basis).
The Heisenberg group gives the small scale geometry of the quotient when you go off to infinity in certain directions --- that is, if you have a torus with one loop $x$ of size $l_1 < \epsilon$ and another loop $y$ size $l_2 < l_1 \epsilon$, then in the moduli space for toruses, the subgroup of $SL(3,\mathbb Z)$ generated by low-energy loops is isomorphic to the Heisenberg group.  By making $\epsilon \rightarrow 0$ the geometric size of this cross-section 3-manifold ( where the shortest and second shortest lengths are held constant)
get arbitrarily small.  This is part of the picture of the space near infinity, but to get a fuller picture, you need to examine the global structure of how different behaviors at infinity connect to one another.
There's a lot more needed before you have a very good picture of what's known about
$SL(3,Z)$ or of this locally symmetric space --- a lot is known from a number of different points of view, and it's challenging to fully understand.  This isn't the place for an exposition, even if I knew all the answers (which I don't).


text:
Q: Oracle dbms_alert.signal firing once for multiple actions I have a trigger in Oracle that calls sys.dbms_alert.signal. A DevArt OracleAlerter receives these alerts in a self-hosted service.
However, I am finding that even for multiple deletes/updates/inserts the OracleAlerter is receiving an alert for just one of the records rather than one alert for all of the records.
Is there a way to view a history or log of the signals that have been fired in Oracle (11g)?
This is an example of the type of trigger that is sending the alert:
create or replace trigger MACL.ZM_SOCOMM_trigger
after delete or insert or update on MACL.SOCOMM
for each row
declare
   alertData varchar2(1000);
begin

alertData := '{"Schema":"MACL","Table":"SOCOMM","Index":"I_SOCOM_KEY","Columns":[{"COLUMN_NAME":"SOCOM_ORDREF","COLUMN_POSITION":1,"COLUMN_VALUE":"#SOCOM_ORDREF#"},{"COLUMN_NAME":"SOCOM_ORDLINE","COLUMN_POSITION":2,"COLUMN_VALUE":"#SOCOM_ORDLINE#"},{"COLUMN_NAME":"SOCOM_COMSEQ","COLUMN_POSITION":3,"COLUMN_VALUE":"#SOCOM_COMSEQ#"},{"COLUMN_NAME":"SOCOM_COMTYPE","COLUMN_POSITION":4,"COLUMN_VALUE":"#SOCOM_COMTYPE#"},{"COLUMN_NAME":"SOCOM_TEXT","COLUMN_POSITION":5,"COLUMN_VALUE":"#SOCOM_TEXT#"}],"ChangePlaceHolder":"#CHANGE#"}';

IF INSERTING OR UPDATING THEN
    alertData := replace(alertData, '#SOCOM_ORDREF#', :new.SOCOM_ORDREF);
    alertData := replace(alertData, '#SOCOM_ORDLINE#', :new.SOCOM_ORDLINE);
    alertData := replace(alertData, '#SOCOM_COMSEQ#', :new.SOCOM_COMSEQ);
    alertData := replace(alertData, '#SOCOM_COMTYPE#', :new.SOCOM_COMTYPE);
    alertData := replace(alertData, '#SOCOM_TEXT#', :new.SOCOM_TEXT);
ELSIF DELETING THEN
    alertData := replace(alertData, '#SOCOM_ORDREF#', :old.SOCOM_ORDREF);
    alertData := replace(alertData, '#SOCOM_ORDLINE#', :old.SOCOM_ORDLINE);
    alertData := replace(alertData, '#SOCOM_COMSEQ#', :old.SOCOM_COMSEQ);
    alertData := replace(alertData, '#SOCOM_COMTYPE#', :old.SOCOM_COMTYPE);
    alertData := replace(alertData, '#SOCOM_TEXT#', :old.SOCOM_TEXT);
END IF;

IF INSERTING THEN
    alertData := replace(alertData, '#CHANGE#', 'INSERT');
ELSIF DELETING THEN
    alertData := replace(alertData, '#CHANGE#', 'DELETE');
ELSE
    alertData := replace(alertData, '#CHANGE#', 'UPDATE');
END IF;

sys.dbms_alert.signal('ooalert_sync', alertData);
END;

Here is the code that I am using to subscribe to signals fired by Oracle:
    public void SetUpAlerts() => RegisterHandlers(CreateAlerter());

    private static void RegisterHandlers(OracleAlerter alerter)
    {
        alerter.Alert += AlerterOnAlert;
        alerter.Error += AlerterOnError;
        alerter.WaitTimeout += AlerterOnWaitTimeout;
        alerter.Stopped += AlerterOnStopped;

        alerts.Add(alerter);
        alerter.Start();
    }

    private OracleAlerter CreateAlerter() => new OracleAlerter
    {
        Timeout = Day,
        AlertName = "Name",
        Connection = Factory.CreateSourceConnection() as OracleConnection
    };

    private static void AlerterOnAlert(object sender, OracleAlerterAlertEventArgs args)
    {
        //handle alert
    }

EDIT
I've added a statement in the trigger that inserts some data into an audit table every time the trigger fires and it appears that the trigger is being fired the correct number of times.

A: According to the documentation:

Alerts can be signalled more often than the corresponding application wait calls. In such cases, the older alerts are discarded. The application always gets the latest alert (based on transaction commit times).

http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_alert.htm#ARPLS65178


text:
Q: Append select box options dynamically with attributes I need to append extra data to my select box options. here is my code.
Html:
<select id="questionNumber" class="form-control">
   <option>Select Number</option>
</select>

JQuery:
$.each(result.data, function (key, value) {
    $("#questionNumber").append($('<option>', {
        value: value.id,
        text: value.number
    }));
});

So i can add value and text but i want to append attributes also to this appended option
like
data-marks = value.mark

So my expected result would be like
<select id="questionNumber" class="form-control">
   <option>Select Number</option>
   <option value="170" data-mark="2">1</option>
   <option value="171" data-mark="3">2</option>
</select>

What should i do for this?
Thanks.

A: Here you go with the solution https://jsfiddle.net/u5vek2jc/

var result = {data:[
 {
   id:"5",
    number: "5"
  },
  {
   id: "89",
    number: "89"
  }
]}
$.each(result.data, function (key, value) {
    $("#questionNumber").append($('<option>', {
        value: value.id,
        text: value.number,
        'data-mark': value.id
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="questionNumber" class="form-control">
   <option>Select Number</option>
</select>

A: You can add the data attribute to the HTML you generate. Also note that you can amend the logic so that the DOM is only updated once, instead of inside each iteration. Try this:
var html = result.data.map(function(o) {
  return `<option value="${o.id}" data-mark="${o.mark}">${o.number}</option>`;
}).join('');
$("#questionNumber").append(html);

A: iterate over your data to create options, and then append it to your select element
$html='';
$.each(result.data, function (key, value) {
    html +='<option value="' + value.id + '"  data-mark="'+value.mark+'">' + value.number + '</option>';
});
$("#questionNumber").append(html);

A: This is a similar example and more complete:
var cadena_user_pais = ($(this).attr('id')).split("_");
var id_user_pais = cadena_user_pais[2];
var request = 'view_tipoNIF';
//tipo de NIF
        $.ajax({
            url: "fetch_single_users.php",
            method: "POST",
            data:{id_user_pais:id_user_pais,request:request},
            dataType: "json",
            success:function(data)
            {
                //alert('hola');
                var html='';
                $.each(data, function (key, value) {
                    html +='<option value="' + value.id + '">' + value.NIF + '</option>';
                });
                $("#select_user_tipoNIF").append(html);
            }   //success
        });