text:
Q: How to make a script in init.d run later A package installed /etc/init.d/ccpd which is a script run at start up. I would like this script to be run as very last of all my start up scripts, how can I achieve this?

A: When your computer starts up, it doesn't run the init.d scripts directly.  Instead, depending on what's called the "runlevel", it runs the scripts in /etc/rcN.d (where N is the runlevel).  You can determine the current runlevel with the runlevel command; mine returns 2 in normal operation.  That means that when the computer started up, it ran the scripts in /etc/rc2.d.  The contents of rc2.d are just symlinks to scripts in /etc/init.d, named according to whether they should be started or stopped, and the order they should be run.
Use the runlevel command to find out what runlevel your computer is at (probably 2), then look in /etc/rc2.d for a link named SNNccpd, which will be a symlink to /etc/init.d/ccpd, and rename it to S99zzzccpd - or whatever it takes to get it to sort after the other entries - that will cause it to run last.
There's more information about init.d scripts and runlevels at https://www.linux.com/news/enterprise/systems-management/8116-an-introduction-to-services-runlevels-and-rcd-scripts

A: Rather than putting it as a service which always keeps running, what you can do remove it as a service from /etc/init.d
and make a script and put it in /root/bin or /usr/local/bin
Inside that script,
#!/bin/bash sleep 300
#call your service and run it in background
/usr/bin/ccpd &

the startup will continue and your stuff will run after 5 minutes
Now the last step is to make your script run on startup,
either add your script to /etc/fstab or to profile


text:
Q: HTML, CSS and Javascript very cool border rotating glowing effects So i came accross the following template but due to the fact they have base64 encrypted their javascript / page elements for god only knows what reason it makes seeing the source code very difficult.
http://yootheme.com/demo/themes/joomla/2010/planet/index.php?option=com_content&view=article&id=44&Itemid=53&preset=default
But on that page the header bar with the class "header-bg" seems to have the background-position constantly changing most likely via the use of javascript and i like the design and effect of the colors so i am curious if someone can help me or fiddle to me a demo of how they are doing this.
I love the way the border effect is constantly rotating around in different variations of colors like that. (Not sure if anyone else finds that beautiful)

A: They use a background image, and they animate background-position using JS.
Here I use CSS animations instead:

@keyframes bg {
  from {
    background-position: 0 0;
  }
  to {
    background-position: 1500px 0;
  }
}
.header-bg {
  border-radius: 15px; /* outerRadius */
  padding: 3px;        /* separation */
  animation: bg 10s infinite linear;
  background: url("data:image/jpeg;base64,[encoded data, 15092 characters]") repeat scroll 0px 0px transparent;
}
.header-inner {
  background: #fff;
  border-radius: 12px;  /* outerRadius - separation */
  padding: 5px;
}

Foo bar

Also note that a gradient could be used instead of that image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Session is not open when connecting to autobahn js I'm having trouble while developing chat-like feature to my socket server.
First let me give you a little bit of my code:
document.conn = new ab.Session('ws://127.0.0.1:8090',
    function () {
        console.log('AB:Connected!');
        conn.subscribe('room_1', function (topic, data) {
            console.log('New message published to room "' + topic + '" : ' + data.content + ' by:' );
            console.log(data);
        });
    },
    function () {
        console.warn('WebSocket connection closed');
    },
    {'skipSubprotocolCheck': true}
);

Currently it's attached to document just to try it out, the error I'm getting is as follows:
"Session not open"

I'm a bit confused about this error and it's origin, should I somehow define the connection?

A: do you start your socket server through cmd.exe ?
you need to use this command to start the server:
php c://wamp64/www/yourproject/bin/push-server.php


text:
Q: c# call object by unique property I have a class Referrals. When you create an object in the class, it checks that the input strings are unique (and therefore never allows duplicate objects). But when I find that input string str1 is equal to that of a previously created object, instead of creating a new object or just returning false, i want to change a property of the already created object. But i can't figure out how to do this, as the method has no way of knowing the name of the object. But I know something unique about it! I feel like this must be enough to somehow call it, and do what I need to do.
Any ideas?
THANKS!
Here is the class:
public class Referral
{
    public class Referral
    {
        public string URL;
        public Dictionary<string, int> Keywords = new Dictionary<string, int>();

        private static Dictionary<string, string> URLs = new Dictionary<string, string>();
        private int HowManyURLs;
        private bool UniqueURL;
        private bool UniqueKeyword;

        public Referral(string MyURL, string MyKeyword, int MyOccurrences)   //Constructor
        {
    if (HowManyURLs == 0)
    {
        URL = MyURL;
        Keywords.Add(MyKeyword, MyOccurrences);
        URLs.Add(MyURL, MyKeyword);
        HowManyURLs++;
    }

    else
    {
        // RESET FLAGS
        UniqueURL = true;
        UniqueKeyword = true;

        for ( int i = 0; i < HowManyURLs; i++ )
        {
        if ( URLs.ContainsKey( MyURL ) )
        {
            // TRIP URL FLAG
            UniqueURL = false;

            // NOW CHECK KEYWORDS OF URL << THIS IS WHAT I CAN'T DO!
            if ( URLs.ContainsKey( MyKeyword ) )
            {
            // TRIP KEYWORD FLAG
            UniqueKeyword = false;

             // ADD TO OCCURRENCES
    //      Referral[MyURL].Occurrences += MyOccurrences;
            }
        }
        }

    // IF BOTH FLAGS TRUE
    if  ( UniqueURL == true && UniqueKeyword == true )
    {
        URL = MyURL;
        Keywords.Add(MyKeyword, MyOccurrences);
        URLs.Add(MyURL, MyKeyword);
        HowManyURLs++;
    }

    }

        }
    }

A: Why don't you create a List of Referral objects outside of the Referral object itself? That way you can check the List to see if the object with your criteria already exists. If so, update that object. If not, create a new one and add it to the list.
Either that or use a static list, also declared outside of the Referrals class.
I'm not 100% sure where you're going with this, so hopefully one of those approaches will work for you.

A: Try using the Dictionary.TryGetValue method?
I didn't quite understand what you're attempting to do with your code, and it's a bit late.

A: You need to create a controller class that will maintain a collection of referral objects in order to achieve the prerequisite checking and updating of the object.
Something like:
public class Referrals
{
    private List<Referral> refs;

    public class Referrals()
    {
        this.refs = new List<Referral>();
    }

    public Referral Add(string MyURL, string MyKeyword)
    {
       var ref = this.refs.Find(delegate(Referral r) { return r.URL == MyURL; });
       if (ref != null)
       {
           if (ref.Keyword == MyKeyword)
           {
               ref.IncrementOccurrences();
           }
       }
       else
       {
           ref = new Referral(MyURL, MyKeyword);
           this.refs.Add(ref);
       }
       return ref;
    }
}

And I would change your Referral class to not take in Occurrences as a variable. This should be handled privately to the object:
public class Referral
{
   private string url;
   private string keyword;
   private int occurrences;

   public Referral(string MyURL, string MyKeyword)
   {
      this.url = MyURL;
      this.keyword = MyKeyword;
      this.occurrences = 1;
   }

   public int Occurrences { get { return this.occurrences; } }
   public string URL { get { return this.url; } }
   public string Keyword { get { return this.keyword; } }

   public void IncrementOccurrencies()
   {
      this.occurrences++;
   }

}


text:
Q: Generate table of content using itextsharp What I am doing is to generate a pdf booklet from database. I need go generate a content table with page numbers. E.g there are two chapters with page number like:
=============================
Content table
Chapter 1 ----- 3
Chapter 2 ----- 17
=============================
The text "Chapter 1 ----- " is normal paragraph. But the page number "3" has to be produced using PdfTemplate because it can only be known later. But the pdfTemplate is absolutely positioned. How can I know where to position the PdfTemplate? Am I right on this ? How could I figure this out or should I use other methods?

A: I've extracted a bit of code to get you on your way.. This code allows you to place text anywhere on a page using an x and y. You may actually want to use iTextSharp's built in paragraph and margin support, but this will be useful, just needs converting to C#
Dim stamper As PdfStamper
Dim templateReader As PdfReader = New PdfReader(yourFileName)
Dim currentPage As PdfImportedPage = stamper.GetImportedPage(templateReader, 1)
stamper.InsertPage(1, PageSize.A4)
Dim cb As PdfContentByte = stamper.GetOverContent(1)
cb.AddTemplate(currentPage, 0, 0)

Look this next bit with each element you want to add..
cb.BeginText()
cb.SetFontAndSize(bf, 12)
cb.SetColorFill(color) 'create a color object to represent the colour you want
cb.ShowTextAligned(1, "Content Table", x, y, 0) 'pass in the x & y of the element
cb.EndText()


text:
Q: Lambda calculus Beta reduction When applying Beta reduction does the function also affect on the $\lambda$ term? (If same value)
For example

$\lambda$ z.$\lambda$ z (z z) t

What is the correct reduction?
$\lambda$z (t t) or
$\lambda$t (t t)

A: The beta contraction of $(\lambda x . M)\, N$ is defined as $[N/x]\, M$, and recall that the substitution is done by replacing every free instance of $x$ by $N$.
Explicitly, $(\lambda z. (\lambda z. zz))t \triangleright_\beta [t/z]\,(\lambda z. zz)$, but as there is no free occurence of $z$ no substitution is performed.


text:
Q: equivalent of ruby `block_given?` in crystal Ruby has this method called the block_given in it so that we can check to see if a block is passed and process accordingly if given. Is there an equivalent method in crystal?

A: Crystal does not have it for a moment. But you can have similar behavior using method overloading:
def foo
  foo {}
end

def foo
  yield
end

foo { }
foo

A: If you absolutely must know whether a block was given, you can do something like this:
def foo(block : (String ->)? = nil)
  if block
    block.call("Block given")
  else
    puts "No block given"
  end
end

def foo(&block : String ->)
  foo(block)
end

foo { |s| puts s  }
foo

(For more information on Proc syntax, see https://crystal-lang.org/reference/syntax_and_semantics/type_grammar.html#proc)


text:
Q: How can I add events to angularjs when filters execute? I have a list of tasks and each task has an associated address. I am putting markers on a map when the page loads so our team gets a visual representation of where the tasks should occur. We also have some extensive filtering on the page. How can I update the map markers anytime the filtered data changes?
<tr ng-repeat="detail in filteredDetails = (details|filterByStatus:page.statusFilter|filterDetailByDate:page.dateFilterFrom+'.'+page.dateFilterThrough|filter:{ColorStatus: page.colorFilter}|filter:{MilestoneIdTaskId: page.milestoneTaskFilter}|filter:{CustomerId: page.storeFilter}|filter:{RepId: page.techFilter}|filter:page.detailFilter)">
</tr>

Basically, anytime the filters execute and the table data is refreshed I want to call my code that puts the markers on the map and pass in the filteredDetails as the parameter.

A: Just write filter that you add at the end and inside you run your refresh:
ng-repeat="detail in filteredDetails = (details|...|filter:page.detailFilter|refresh)"

.filter('refresh', function() {
  return function(input) {
      //refresh the map. input will be filteredDetails
  });
});


text: Q: How to override some methods inside of the installed plugin I am using django import-export and I am trying to override the forms.py to include additional options. I know in order to override django admin templates I need to create an admin folder inside of the templates/admin/base.html. The question is how would I do that inside for the plugin Forms.py


text:
Q: 'ECONNREFUSED' on http request I have a Ionic app that has worked fine to date, but suddenly I get this error when I make an http request. (By running just 'ionic serve', without any platform). I guess it has to do with matters of versions and the like.

Error: connect ECONNREFUSED 127.0.0.1:8561
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)

The server works fine and responds to requests from Postman.
This is the packages details:

*

*ionic -v 6.17.0

*cordova -v 10.0.0

Package.json:
"dependencies": {
"@angular/cdk": "^6.3.1",
"@angular/common": "^5.0.0",
"@angular/compiler": "^5.0.0",
"@angular/compiler-cli": "^5.0.0",
"@angular/core": "^5.0.0",
"@angular/forms": "^5.0.0",
"@angular/http": "^5.0.0",
"@angular/material": "^6.3.1",
"@angular/platform-browser": "^5.0.0",
"@angular/platform-browser-dynamic": "^5.0.0",
"@ionic-native/app-version": "^4.9.0",
"@ionic-native/core": "^4.9.0",
"@ionic-native/diagnostic": "^4.9.0",
"@ionic-native/downloader": "^4.20.0",
"@ionic-native/estimote-beacons": "^4.9.0",
"@ionic-native/ibeacon": "^4.9.0",
"@ionic-native/keyboard": "^4.9.0",
"@ionic-native/push": "^4.9.0",
"@ng-idle/core": "^2.0.0-beta.15",
"@ng-idle/keepalive": "^2.0.0-beta.15",
"android-versions": "^1.4.0",
"angular2-moment": "^1.9.0",
"connect": "^3.6.3",
"cordova-android": "8.1.0",
"cordova-plugin-app-version": "^0.1.9",
"cordova-plugin-ble": "^2.0.1",
"cordova-plugin-camera": "^4.0.0",
"cordova-plugin-console": "^1.0.7",
"cordova-plugin-device": "^1.1.7",
"cordova-plugin-geolocation": "^4.0.2",
"cordova-plugin-ibeacon": "^3.6.1",
"cordova-plugin-splashscreen": "^6.0.0",
"cordova-plugin-statusbar": "^2.1.3",
"cordova-plugin-whitelist": "^1.3.3",
"cordova-plugin-wkwebviewxhrfix": "^0.1.0",
"ion-datepicker": "^2.7.7",
"ion2-calendar": "^2.1.7",
"ion2-code-calendar": "0.0.5",
"ionic-angular": "^3.9.2",
"ionic-native": "2.4.1",
"ionic-plugin-keyboard": "^2.2.1",
"ionicons": "3.0.0",
"lodash": "^4.17.4",
"lodash.assign": "^4.2.0",
"lodash.clonedeep": "^4.5.0",
"moment": "^2.29.0",
"ngx-webstorage": "^2.0.0",
"numeral": "^2.0.6",
"phonegap-plugin-push": "^2.3.0",
"promise-polyfill": "6.0.2",
"raven-js": "^3.17.0",
"rxjs": "5.5.2",
"sharp": "^0.23.3",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.18"
},
"devDependencies": {
"@ahovakimyan/cordova-plugin-wkwebviewxhrfix": "git+https://github.com/AraHovakimyan/cordova-
plugin-wkwebviewxhrfix.git",
"@ionic/app-scripts": "3.2.4",
"@ionic/lab": "1.0.24",
"@types/lodash": "4.14.55",
"cordova-browser": "^6.0.0",
"cordova-ios": "^6.1.1",
"cordova-plugin-androidx-adapter": "^1.1.3",
"cordova-plugin-datepicker": "^0.9.3",
"cordova-plugin-estimote": "git+https://github.com/evothings/phonegap-estimotebeacons.git",
"cordova.plugins.diagnostic": "^6.0.2",
"integrator-cordova-plugin-downloader": "^1.1.0",
"node-sass": "^4.14.1",
"typescript": "~2.4.2",
"web": "0.0.2"
},
"cordova": {
"plugins": {
  "cordova-plugin-device": {},
  "cordova-plugin-statusbar": {},
  "ionic-plugin-keyboard": {},
  "cordova-plugin-console": {},
  "cordova-plugin-ble": {},
  "cordova-plugin-whitelist": {},
  "cordova-plugin-app-version": {},
  "cordova-plugin-splashscreen": {},
  "cordova-plugin-estimote": {},
  "cordova-plugin-geolocation": {},
  "cordova.plugins.diagnostic": {
    "ANDROIDX_VERSION": "1.+"
  },
  "cordova-plugin-datepicker": {},
  "cordova-plugin-wkwebviewxhrfix": {},
  "cordova-plugin-camera": {},
  "cordova-plugin-androidx-adapter": {},
  "integrator-cordova-plugin-downloader": {}
},
"dependencies": {
  "@angular/common": "^5.0.0",
  "@angular/compiler": "^5.0.0",
  "@angular/compiler-cli": "^5.0.0",
  "@angular/core": "^5.0.0",
  "@angular/forms": "^5.0.0",
  "@angular/http": "^5.0.0",
  "@angular/platform-browser": "^5.0.0",
  "@angular/platform-browser-dynamic": "^5.0.0",
  "@ionic-native/core": "^3.14.0",
  "@ionic-native/estimote-beacons": "^3.12.1",
  "@ionic-native/push": "^4.0.1",
  "angular2-moment": "^1.3.0",
  "com.unarin.cordova.beacon": "^3.4.0",
  "connect": "^3.6.3",
  "cordova-plugin-camera": "2.4.1",
  "cordova-plugin-console": "1.0.7",
  "cordova-plugin-crosswalk-webview": "2.3.0",
  "cordova-plugin-device": "1.1.6",
  "cordova-plugin-estimote": "git+https://github.com/evothings/phonegap-estimotebeacons.git",
  "cordova-plugin-geolocation": "2.4.3",
  "cordova-plugin-ibeacon": "3.4.0",
  "cordova-plugin-splashscreen": "6.0.0",
  "cordova-plugin-statusbar": "2.1.3",
  "cordova-plugin-whitelist": "1.2.2",
  "ionic-angular": "3.6.0",
  "ionic-native": "2.4.1",
  "ionic-plugin-keyboard": "2.2.1",
  "ionicons": "3.0.0",
  "lodash": "^4.17.4",
  "moment": "^2.17.1",
  "numeral": "^2.0.6",
  "promise-polyfill": "6.0.2",
  "rxjs": "5.1.1",
  "sw-toolbox": "3.4.0",
  "zone.js": "0.8.11"
},
"devDependencies": {
  "@ionic/app-scripts": "^3.1.10",
  "@types/lodash": "4.14.55",
  "typescript": "^2.3.3"
},
"cordova": {
  "plugins": {
    "cordova-plugin-device": {},
    "cordova-plugin-splashscreen": {},
    "cordova-plugin-statusbar": {},
    "cordova-plugin-whitelist": {},
    "ionic-plugin-keyboard": {},
    "com.unarin.cordova.beacon": {},
    "cordova-plugin-estimote": {},
    "cordova-plugin-geolocation": {},
    "phonegap-plugin-push": {},
    "cordova-plugin-crosswalk-webview": {
      "XWALK_VERSION": "23+",
      "XWALK_LITEVERSION": "xwalk_core_library_canary:17+",
      "XWALK_COMMANDLINE": "--disable-pull-to-refresh-effect",
      "XWALK_MODE": "embedded",
      "XWALK_MULTIPLEAPK": "true"
    },
    "cordova-plugin-camera": {},
    "cordova-plugin-console": {}
  },
  "platforms": [
    "ios"
  ]
},
"platforms": [
  "android",
  "browser"
]
}

A: Solved by downgrade ionic to ionic@3.17.0-alpha.3137c766

A: I also face the same issue. I resolve the issue by adding http:// in the third-party API, If it does not work for them try to include https:// instat of http://


text:
Q: can't pip install a branch I want to install this branch https://github.com/pathpy/pathpy/tree/plot which is a few commits ahead because I need some specific functions here. I am not sure how to pip install this branch and work with functions from there.
I tried pip install git+https://github.com/pathpy/pathpy/tree/plot but I get this error:

WARNING: Discarding git+https://github.com/pathpy/pathpy/tree/plot. Command errored out with exit status 128: git clone -q https://github.com/pathpy/pathpy/tree/plot /private/var/folders/x9/qk9fwl9d6076z564bqhwmfj00000gn/T/pip-req-build-6r0fvozu Check the logs for full command output.
ERROR: Command errored out with exit status 128: git clone -q https://github.com/pathpy/pathpy/tree/plot /private/var/folders/x9/qk9fwl9d6076z564bqhwmfj00000gn/T/pip-req-build-6r0fvozu Check the logs for full command output.

How should I solve this problem?


text:
Q: $\forall\epsilon>0, \exists N\in\Bbb N$ such that $\forall n>m\ge N, a_n-a_m<\epsilon$. Prove that $a_n$ converges to a real limit or to $-\infty$ Assume $(a_n)_{n=1}^\infty$ has the following property: For all $\epsilon>0$ exists some $N\in\Bbb N$ such that for every $n>m\ge N$, $a_n-a_m<\epsilon$. We want to prove that $a_n$ converges to a real limit or to $-\infty$.
This condition implies that $a_n$ is bounded above.
So, I tried to show what happens if it's bounded below or unbounded below.
When bounded below, by Bolzano-Weierstrass $a_n$ has some convergent subsequence, $a_{n_k} \rightarrow L$, so for all $k\ge K$ for some $K\in \Bbb N$, $|a_{n_k}-L|<\epsilon \iff -\epsilon<a_{n_k}-L<\epsilon$ .
I tried to use this to prove the convergence of the entire sequence but it didn't work -  I tried to take some $n>n_k>max(N, n_K)$, $a_n-L=a_n-a_{n_k}+a_{n_k}-L <2\epsilon$, but now I can't get the left inequality right. This makes me question my entire process. Maybe I should've gone about this a different way?

A: Your approach is fine.
If $(a_n)_{n\in\mathbb N}$ is undounded below, Take $M<0$. The inequality $a_n<M-1$ holds infinitely often and there is a $N\in\mathbb N$ such that $$n>m\geqslant N\implies a_n-a_m<1.$$Therefore, if $n\gg1$, $a_n<(M-1)+1=M$. This proves that $\lim_{n\to\infty}a_n=-\infty$.
Otherwise, let $L=\liminf_na_n$. Take $\varepsilon>0$. Then the inequality $|a_n-L|<\frac\varepsilon2$ hold infinitely often and $a_n>L-\frac\varepsilon2$ if $n\gg1$. Now, take $N\in\mathbb N$ such that$$n>m\geqslant N\implies a_n-a_m<\frac\varepsilon2.$$Then, if $n\gg1$, $|L-a_n|<\varepsilon$.


text:
Q: C++ return different objects i have a big problem.. I wonna select the Storage Service via a wrapper class. The returning value must be an object within the storage service class. I pasted my current approach. But my mindset didn't worked so far.
Error:

error: inconsistent deduction for auto return type: 'SQL*' and then 'REDIS*'     return new REDIS();

The big wish is to have an interface class which defines the struct and some "driver classes" which contains all necessary operations for the target storage service.
I hope you have another approach, how I can solve this problem..
    #include <iostream>

class StorageTemplate {
    public:
        virtual bool UserhasSurName() = 0;
        virtual bool UserhasGivenName() = 0;
};

class SQL: public StorageTemplate {
    public:
        bool UserhasSurName() {
            //A SQL QUERY
            return true;
        }
        bool UserhasGivenName() {
            //AN ANOTHER SQL QUERY
            return true;
        }
};

class REDIS: public StorageTemplate {
    public:
        bool UserhasSurName() {
            //A REDIS CALL
            return false;
        }
        bool UserhasGivenName() {
            //A REDIS CALL
            return false;
        }
};

class controller {
    public:
        auto test(int select) {
            if( select == 1)
            {
                return new SQL();
            } else {
                return new REDIS();
            }
        }
};

int main(int argc, char const *argv[])
{
    controller cont;
    auto schnitzel = cont.test(1);
    auto mitzel = cont.test(2);
    std::cout << schnitzel->UserhasSurName() << std::endl;
    std::cout << mitzel->UserhasSurName() << std::endl;
}

A: The problem you are facing is the following: Consider your function
auto test(int select) {
    if (select == 1) {
        return new SQL();
    } else {
        return new REDIS();
    }
}

If you trying to evaluate test(1) this expands to
auto test(int select) {
    if (true) {
        return new SQL();
    } else {
        return new REDIS();
    }
}

which results in a type error!
I show you three workarounds for your problem:
1. Function template and if constexpr
Make test a function template and check for the correct type using the C++17 feature if constexpr:
template<typename T>
auto test() {
    if constexpr(std::is_same<T, SQL>::value) {
        return new SQL();
    } else {
        return new REDIS();
    }
}

Use it in main() like this:
int main(){
    controller cont;
    auto schnitzel = cont.test<SQL>();
    auto mitzel = cont.test<REDIS>();
    std::cout << schnitzel->UserhasSurName() << std::endl;
    std::cout << mitzel->UserhasSurName() << std::endl;
}

2. Function template and std::unique_ptr
If you want to avoid using the if constexpr you can simply return an instance of std::unique_ptr instead of a raw pointer. This is the preferred way to do:
template<typename T>
auto test() {
    return std::unique_ptr<T>(new T);
}

Alternatively you can just return std::make_unique<T>().
3. Returning an instance of the base class
This is is most obvious solution to avoid the type error: Just return an instance of the base class. As above a solution using smart pointers is preferred here:
std::unique_ptr<StorageTemplate> test(const int select) {
    if (select == 1) {
        return std::make_unique<SQL>();
    } else {
        return std::make_unique<REDIS>();
    }
}

If you really want to avoid using smart pointers just use raw ones like this:
StorageTemplate* test(const int select) {
    if (select == 1) {
        return new SQL();
    } else {
        return new REDIS();
    }
}

A: in this code
auto test(int select) {
    if( select == 1)
    {
        return new SQL();
    } else {
        return new REDIS();
    }

auto can't be deduced because it only match to exact type. so even if SQL and REDIS inherite from StorageTemplate, StorageTemplate won't be deduced. you need to spécifie the type
StorageTemplate* test(int select) {
    if( select == 1)
    {
        return new SQL();
    } else {
        return new REDIS();
    }

A: Error return Auto in test(),it's return two different types. Change by StorageTemplate*
class controller {
    public:
        StorageTemplate* test(int select) {
            if( select == 1)
            {
                return new SQL();
            } else {
                return new REDIS();
            }
        }
};


text:
Q: How to account for errors in the ajax calls when using alternative promises I've developed the code below (also available in this codepen http://codepen.io/PiotrBerebecki/pen/QNVEbP) when building an app that will provide weather data depending on user's location coordinates.
User's location will be delivered by the getCoordinatesMethod1() function. However if this fails, the location should be delivered by the getCoordinatesMethod2() function.
How can I add the getCoordinatesMethod2() to the the promises chain (at the bottom) so that it only is used when getCoordinatesMethod1() fails to deliver the location?
Also, in future in order to make the app more robust I may add further methods to fetch location data so the chain logic should be able to accommodate that as well.
// The first method to get user location coordinates.
function getCoordinatesMethod1() {
  return $.ajax('http://wwww.example.com/coordinates-method-1.json');
}

// The second method to get user location coordinates.
// This should only be used if method 1 fails to deliver coordinates.
function getCoordinatesMethod2() {
  return $.ajax('http://wwww.example.com/coordinates-method-2.json');
}

// Function which provides weather data depending on user coordinates.
function getCurrentWeather(latitude, longitude) {
  return $.ajax('http://www.example.com/lat=' + latitude + '&lon=' + longitude + 'weather.json');
}

// Promises chain
getUserCoordinates1().then(function(locationData) {
  return getCurrentWeather(locationData);
  }).then(function(weatherData) {
    return showCurrentWeather(weatherData);
  })

A: You can create a function that calls the first method and, if the returns promise rejects, then calls the second method:
function getCoordinateBoth() {
   return getCoordinatesMethod1().then(null, getCoordinatesMethod2);
}

If there are actually arguments passed to these functions, then you can pass those arguments on like this:
function getCoordinateBoth(/* args here */) {
   var args = Array.prototype.slice.call(arguments);
   return getCoordinatesMethod1.apply(null, args).then(null, function() {
       return getCoordinatesMethod2.apply(null, args)
   });
}

You could even just have these functions in an array so it is infinitely extensible:
// Put list of functions to be call as a chain until one succeeds
// You can just add more functions here as long as each returns a promise
//    and expects the same arguments
var getCoordFunctions = [getCoordinatesMethod1, getCoordinateMethod2, getCoordinateMethod3];

function getCoordinateChain(/* args here */) {
   var args = Array.prototype.slice.call(arguments);
   var fnArray = getCoordFunctions.slice(0);
   var firstFn = fnArray.shift();
   fnArray.reduce(function(p, fn) {
        return p.then(null, function() {
            return fn.apply(null, args);
        });
   }, firstFn.apply(null, arguments));
}

You could even make this a generic promise chain function:
function chainUntilResolve(array /* other args here */) {
   var args = Array.prototype.slice.call(arguments);
   // toss first arg
   args.shift();
   // make a copy of array of functions
   var fnArray = array.slice(0);
   // remove first function from the array
   var firstFn = fnArray.shift();
   fnArray.reduce(function(p, fn) {
        return p.then(null, function() {
            return fn.apply(null, args);
        });
   }, firstFn.apply(null, arguments));
}

var getCoordFunctions = [getCoordinatesMethod1, getCoordinateMethod2, getCoordinateMethod3];

chainUntilResolve(getCoordFunctions, arg1, arg2).then(function(data) {
    // process data here
}, function(err) {
    // error here
});


text:
Q: inout verilog protocol I2C I'm creating the I2C protocol in verilog to read data from a sensor (BMP180), AS you know, the sensor sends me a bit of ack recognition. How do I use the inout i2c_sda port to send and how do I receive.
As delivery and receipt i2c_sda the same line, if my variable is declared of type inout.
module stepPrueba(
    input wire      clk1,
    input wire  reset,
     input wire     start,
    inout           i2c_sda,
    inout           i2c_scl,
     output wire    ready,
     output reg led1,
     output reg led2
    );

    reg i2c_scl_out;
    assign i2c_scl1= (i2c_scl_out == 1'b0) ? 1'b0 : 1'bz;
     wire i2c_scl_in = i2c_scl;

     assign i2c_scl = (i2c_scl_enable == 0) ? i2c_scl1 : clk1;
    reg clk;

     assign clk1 = (clk == 1)? 1'bz:1'b0;

    reg i2c_sda_out;
    assign i2c_sda = (i2c_sda_out == 1'b0) ? 1'b0 : 1'bz;
    wire i2c_sda_in = i2c_sda ;

     reg    [6:0] addr;
     reg    [7:0] data;
     reg enable; //(read=1, write=0)
    reg datas;
     reg enable2; //(read=1, write = 0)
     reg [7:0] state;
     reg [7:0] count;
     reg i2c_scl_enable = 0;
     reg [6:0] saved_addr;
     reg [7:0] saved_data;

//goal es escribir al dispositivo direccion 0X55, 0Xaa
    localparam STATE_IDLE = 0;
    localparam STATE_START = 1;
    localparam STATE_ADDR =2;
    localparam STATE_RW = 3;
    localparam STATE_WACK = 4;
    localparam STATE_DATA = 5;
    localparam STATE_WACK2 = 6;
    localparam STATE_STOP = 7;

always@(posedge clk)
    begin
      //enable2 <= 0; //i2c_scl==zetas & c_lectura=z;
      if(reset == 1)
         begin
           i2c_scl_out<=1;
           i2c_scl_enable <= 0;
         end
        else
          begin
             if((state == STATE_IDLE) || (state == STATE_START) )
              begin
                //i2c_scl_enable <= 0; //dats == 1 --> ztas == z
                 i2c_scl_out<=1;
               i2c_scl_enable <= 0;
              end
            else
              begin
                i2c_scl_enable <= 1; // dats==clk;
                 clk<=clk1;
             end
         end
    end

always@(posedge clk)
    begin
       if(reset == 1)
          begin
            led1 <=0;
            led2 <=0;
            state <=0;
             i2c_sda_out <= 1;// i2c_sda ==z;
            addr <= 7'b1110111; // direccion del sensor
            count <= 8'd0;
            data <= 8'b11110100; //direccion interna PRESION
         end
       else //reset ==0
          begin

            case (state)

             STATE_IDLE:
                begin //idle
                   //datas <= 1;  //zetas==z
                    i2c_scl_out<=1;
                 i2c_scl_enable <= 0;

                    i2c_sda_out <= 1;
                   if(start)
                     begin
                        state <= STATE_START;
                        saved_addr <= addr;
                        saved_data <= data;

                 // reg i2c_scl_out;
              // assign i2c_scl1= (i2c_scl_out == 1'b0) ? 1'b0 : 1'bz;
               // wire i2c_scl_in = i2c_scl;
               // assign i2c_scl = (i2c_scl_enable == 0) ? i2c_scl1 : ~clk;

                     end
                   else
                     begin
                       state <= STATE_IDLE;
                     end
                end

            STATE_START:
               begin // start
                  //enable <= 0; // lectura==z; --> i2c_sda==zetas
                  i2c_sda_out <= 0;
                  //datas <= 0; // zetas==0
                  state<= STATE_ADDR;
                  count <= 6;
               end

            STATE_ADDR:
               begin //msb addres bit
                  //enable <= 0; // lectura==z; --> i2c_sda==zetas
                  i2c_sda_out <= saved_addr[count]; // datas ==0 --> zetas==0 || datas==1 --> zetas==z
                  if (count == 0)
                    begin
                       state <= STATE_RW;
                     end
                  else
                    begin
                       count <= count - 1;
                     end
               end

            STATE_RW:
               begin
                  //enable <= 0; //enable==0 --> i2c_sda==zetas
                  i2c_sda_out <= 0;//datas <= 0;
                  state <= STATE_WACK;
               end

            STATE_WACK:
               begin
                  //enable <= 1; //enable==1 lee  i2c_sda==z & lectura==i2c_sda

                   //enable <= 0;
                   //if(APA)
                  if(i2c_sda_in==1)
                    begin
                       state <= STATE_IDLE;
                    end
                  else
                    begin
                   state <= STATE_DATA;
                       led1 <= 1;
                   end
                  count <= 7;
               end

            STATE_DATA:
               begin
                  //enable <= 0;
                  i2c_sda_out <= saved_data[count];
                  if(count ==0)
                    begin
                      state <= STATE_WACK2;
                    end
                  else
                    begin
                      count <= count - 1;
                end
               end

            STATE_WACK2:
               begin
                  //enable <= 1;
                  if(i2c_sda_in ==1)
                    begin
                       state <= STATE_IDLE;
                     end
                  else
                    begin
                       state <= STATE_STOP;
                       led2 <= 1;
                     end
               end

            STATE_STOP:
               begin
                  //enable <= 0;
                  i2c_sda_out <= 0;
                  state <= STATE_IDLE;
               end
       endcase
   end
end
endmodule

A: If you have a module pin defined as
inout wire pin

then you can access it like so
wire pin_input = pin;
assign pin = pin_oe ? pin_output : 1'bz;

this should infer a tristate buffer.
However, I would be careful when doing this, as if you infer a tristate buffer too early, it can limit what you can do with the module.  For example, it would be possible to connect multiple internal I2C components together, such as allowing multiple masters inside the FPGA access to the same pins.  However, tristate signals cannot be routed inside the FPGA, so if you implement the tristate inside the I2C master module, this becomes impossible.  Instead, what you might consider is implementing each pin as three module pins: input, output, and output enable/tristate.  This allows multiple modules to be connected with an emulated tristate bus, and allows them to share one set of tristate buffers to the actual I/O pin on the chip.
For a good example of how this works, see the comments in https://github.com/alexforencich/verilog-i2c/blob/master/rtl/i2c_master.v .


text:
Q: Inductive proof that if there is an injection $\mathbb{N_m} \rightarrow \mathbb{N}_n$ then $m\le n$ The statement to prove is:

If there exists an injection $\mathbb{N_m} \rightarrow \mathbb{N}_n$ then  $m\le n$

The solution says to prove by induction on $n$.
I just need help on the inductive step:
$P(k): \forall m \in \mathbb{Z}^+(\exists \text{ injection } \mathbb{N}_m\rightarrow \mathbb{N}k) \Rightarrow m \le k$
$P(k+1): \forall m \in \mathbb{Z}^+(\exists \text{ injection } \mathbb{N}_m\rightarrow \mathbb{N}_{k+1}) \Rightarrow m \le k+1$
This can be summarized as:

Given:

*

*$\forall m \in \mathbb{Z}^+(\exists \text{ injection } \mathbb{N}_m\rightarrow >\mathbb{N}k) \Rightarrow m \le k$,

*$m_1\in \mathbb{Z}^+$, and

*injection $f:\mathbb{N}_{m_1}\rightarrow \mathbb{N}_{k+1}$

  We need to show that this implies:

*

*$m_1 \le k+1$

Case 1
Suppose that $f(i) < k+1 $ for all $i\in \mathbb{N_m}$. Then we can restrict the codomain and define a function $f_1:\mathbb{N}_{m_1}\rightarrow\mathbb{N}_k$ by $f_1(i)=f(i)$. The function $f_1$ is also an injection and so, by inductive hypothesis, $m_1\le k$ and so certainly $m_1\le k+1$ as required.
Case 2
Suppose that $k+1$ is a value of $f$, say $f(i_0)=k+1$ where $i_0\in \mathbb{N}_{m_1}$. In this case we can define an injection $g:\mathbb{N}_{{m_1}-1}\rightarrow \mathbb{N}_{m_1}$ by:
$g(i) = \left\{ \begin{align} i & \text {, for }   i<i_0 \\
i+1 & \text{, for }  i \ge i_0
\end{align}\right.$
Then, we can define $f_1=f \circ g: \mathbb{N}_{{m_1}-1} \rightarrow \mathbb{N}_k$, which is an injection too. So, by the inductive hypothesis, $m_1-1 \le k$, which means $m_1 \le k+1$, as required.
Questions

*

*Given an injection $f:\mathbb{N}_{m_1} \rightarrow \mathbb{N}_{k+1}$. why do we need to break it into the two cases? Do the cases cover all possibilities of $f$ being an injection from $N_\mathbb{m_1}$ to $\mathbb{N_{k+1}}$?

*It seems the strategy of this is to show that given an injection $f:\mathbb{N}_{m_1} \rightarrow \mathbb{N}_{k+1}$, this implies an injection $f:\mathbb{N}_{x} \rightarrow \mathbb{N}_{k}$, where $x$ a function of $m_1$, which we can then use the induction hypothesis to eventually conclude that $m_1<k+1$, as required. Is my understanding of this proof correct?

*My attempt:
Given an injection $f:\mathbb{N}_{m_1} \rightarrow \mathbb{N}_{k+1}$, I will immediately call the induction hypothesis to conclude that $m_1\le k+1$. What is wrong with this answer? Is it because the codomain is different (given injection is $\mathbb{N}_{k+1}$ vs induction hypothesis is $\mathbb{N}_k$)that this kind of reasoning is wrong?

*Suppose we need to prove:

For all positive integers $n$, we have the inequality $n\le 2^n$

Then for the inductive step, the inductive hypothesis is $k\le 2^k$ and we need to prove that this implies $k+1 \le 2^{k+1}$.
How would the proof for this inductive step look like if the kind of error in point 3 is repeated here?
EDIT:
$\mathbb{N}_m = \{1,2,\dots, m\}$

A: *

*It is a matter of doing things in an orderly manner.  Yes, this covers all cases: either the image is contained in $[k]$, or it maps to $k+1$.

*Induction is made over $k$; not $m$. Careful.

*This is wrong. Induction is being made over $k$, and your induction hypothesis is that if $[m]\to [k]$ is an injection, $m\leqslant k$. You don't know anything about $k+1$.

*You're assuming what you want to prove. You would simply say "by induction, $k+1\leqslant 2^{k+1}$; instead of, by induction $k+1\leqslant 2^k+1\leqslant 2^k+2^k=2^{k+1}$.
We may assume $m>1$. Assume the claim proven for every $k\leqslant n$, that is, we have already proven $$P(k)=\text{ if there is an injection }[m]\to [k],m\leqslant k$$ Suppose that we have an injection $[m]\to [n]$. Then $f(1)=j$ for some $j\in [n]$, and we may assume by reordering that $f(1)=1$. Deleting $1$ from each set, we get an injection $[m-1]\to [n-1]$. By induction, $m-1\leqslant n-1$, so $m\leqslant n$.


text:
Q: Find out till where a regex satisfies a sentence I have some sentence and a regular expression. Is it possible to find out till where in the regex my sentence satisfies. For example consider my sentence as MMMV and regex as M+V?T*Z+. Now regex till M+V? satisfies the sentences and the remaining part of regex is T*Z+ which should be my output.
My approach right now is to break the regex in individual parts and store that in a list and then match by concatenating first n parts till sentence matches. For example if my regex is M+V?T*Z+, then my list is ['M+', 'V?', 'T*', 'Z+']. I then match my string in loop first by M+, second by M+V? and so on till complete match is found and then take the remaining list as output. Below is the code
            re_exp = ['M+', 'V?', 'T*', 'Z+']
            for n in range(len(re_exp)):
                re_expression = ''.join(re_exp[:n+1])
                if re.match(r'{0}$'.format(re_expression), sentence_language):
                    return re_exp[n+1:]

Is there a better approach to achieve this may be by using some parsing library etc.

A: Assuming that your regex is rather simple, with no groups, backreferences, lookaheads, etc., e.g. as in your case, following the pattern \w[+*?]?, you can first split it up into parts, as you already do. But then instead of iteratively joining the parts and matching them against the entire string, you can test each part individually by slicing away the already matched parts.
def match(pattern, string):
    res = pat = ""
    for p in re.findall(r"\w[+*?]?", pattern):
        m = re.match(p, string)
        if m:
            g = m.group()
            string = string[len(g):]
            res, pat = res + g, pat + p
        else:
            break
    return pat, res

Example:
>>> for s in "MMMV", "MMVVTTZ", "MTTZZZ", "MVZZZ", "MVTZX":
>>>     print(*match("M+V?T*Z+", s))
...
M+V?T* MMMV
M+V?T* MMV
M+V?T*Z+ MTTZZZ
M+V?T*Z+ MVZZZ
M+V?T*Z+ MVTZ

Note, however, that in the worst case of having a string of length n and a pattern of n parts, each matching just a single character, this will still have O(n²) for repeatedly slicing the string.
Also, this may fail if two consecutive parts are about the same character, e.g. a?a+b (which should be equivalent to a+b) will not match ab but only aab as the single a is already "consumed" by the a?.
You could get the complexity down to O(n) by writing your own very simple regex matcher for that very reduced sort of regex, but in the average case that might not be worth it, or even slower.

A: You can use () to enclose groups in regex. For example: M+V?(T*Z+), the output you want is stored in the first group of the regex.
I know the question says python, but here you can see the regex in action:

const regex = /M+V?(T*Z+)/;
const str = `MMMVTZ`;
let m = regex.exec(str);

console.log(m[1]);


text:
Q: Prove or give counter example: for every real number $y$ there exists a real number $x$ such that $e^{3x} + y = y^2 +1$ I started like this and am not sure if I'm on the right path.
Let $y$ be an arbitrary real number. Let $x=0.$
So we get
$$\begin{aligned} e^{3\cdot 0}=&\; y^2-y+1\\
               1 =&\; y^2-y+1\\
               0 =&\; y^2-y\\
               0 =&\; y(y-1)
\end{aligned}$$
and now I'm stuck, I tried contradiction, and it didn't work. So I just don't know where to go from here. Any help would be amazing.

A: Let's see: Is it possible thar $y^2-y+1\le 0$? Since that polynomial has positive leading coefficient, to be negative it has to cross the X-axis, this is, have real roots; but $\sqrt{(-1)^2-4·1·1}=\sqrt{-3}\notin \Bbb R$, so the polynomial is always positive.
Since $\lim_{x\to-\infty}e^{3x}=0$ and $\lim_{x\to\infty}e^{3x}=+\infty$, $e^{3x}$ has to take any positive value in between, since it is a continuous function (Rolle's theorem).
Then for every $y\in\Bbb R$ we have $y^2-y+1>0$, so there has to be some $x\in\Bbb R$ such that $e^{3x}$ takes that value.

A: We have $e^{3x}> 0$ for all $x\in\mathbb R$ so if we can find a $y$ such that $y^2-y+1\leq0$ we get a contradiction.
But $y^2-y+1=(y-\frac{1}{2})^2+\frac{3}{4}>0$ for all $y\in\mathbb R$. Thus the statement is true. In other words for any $y\in\mathbb R$ take $x=\frac{1}{3}\ln(y^2-y+1)$ which is a real number, then $e^{3x} + y = y^2 +1$ are required.

A: $$y^2-y+1-e^{3x}=0$$
the equation is quadratic in y, use the quadratic equation:
$$y=\frac{1+\sqrt{e^{3x}-3}}{2}, \frac{1-\sqrt{e^{3x}-3}}{2}$$
since the range of $e^{3x}-3$ spans the positive real numbers, the combined range of the two equations spans the real numbers.


text:
Q: Keep screen on when application is running I am working on PhoneGap application. I want the screen to be shown when my application is in the foreground. But screen goes to lock due to inactivity.
I tried using flag_screen_on in mainactivity file. It's not working. I tried using wakelock too. It didn't work too.
Can you please suggest any other ways to keep the screen on when the application is opened. Thanks for your response.

A: Yes, There is a plugin created by the EddyVerbruggen. You can include this within your project. Documentation is pretty simple for same.

A: Added these lines of code in MainActivity.java. Here is the code snippet
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


text:
Q: Undifined Index: Password even thought I have used isset Please wait before putting that this question has already been ask because from what I've been seeing I tried all the technics showed in most answers and it hasn't worked. Please, I've been on this error for multiple days and tried everything let's try to find a fix together! If you need any additional code or detail just ask in the comment. Thanks
This Error Comes Up:

Here is my login.php:
<?php

if (isset($_POST['email']) || isset($_POST['password']))
{
    require_once 'connect.php';
    $email = $mysqli->escape_string($_POST['email']);
    $password = $mysqli->escape_string($_POST['password']);
    $result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

    if ($result->num_rows == 0){
        echo "Did not find any user with this email.";
        exit();
    }
    else {
        $user = $result->fetch_assoc();
        //LINE 16//if (password_verify($password, $user['password'])){**
            $_SESSION['id'] = $user['id'];
            $_SESSION['email'] = $user['email'];
            echo "Success.";
        }else{
            echo "Wrong Password";
            die();
    }
}
}

?>

Here is my login_page.php:
<?php require_once 'header.php' ?>

Login

     Or Register

    <form action="login.php" method="post">
        <input type="text" name="email" placeholder="Email">

        <input type="password" name="password" placeholder="Password">

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

<?php require_once 'footer.php' ?>


text:
Q: Copy sheet without creating new instances of named ranges? I'm using the following code to copy a sheet.  I also have a few named ranges that are scoped to the Workbook.  The problem is, when I do the copy, it creates duplicates of all the named ranges with a scope of the new sheet.  Everything works of course but I could potentially have 20+ sheets.  I don't need 80 named ranges that are mostly duplicates.  How can I avoid this?
Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
End Sub

And the Name Manager after a copy:

A: Here is my answer:
Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
    deleteNames 'Check the sub
End Sub

Sub deleteNames()
    Dim theName As Name
    For Each theName In Names
        If TypeOf theName.Parent Is Worksheet Then
            theName.Delete
        End If
    Next
End Sub

This way you will delete all the names with the scope "worksheet" and keep the "workbook" names
Edit#2
After read the comments here is the update passing the sheet to loop only the "newSheet"
Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
    deleteNames newSheet
End Sub

Sub deleteNames(sht As Worksheet)
    Dim theName As Name
    For Each theName In Names
        If (TypeOf theName.Parent Is Worksheet) And (sht.Name = theName.Parent.Name) Then
            theName.Delete
        End If
    Next
End Sub


text:
Q: How to pass signal as parameter to a method in python? My main process spawns a new process, this new process needs to terminate if SIGTERM/SIGKILL signal is sent to it. I am new to python and I don't know how to pass this signal as argument to the function.
My code is:
import os
import random
import time
import sys
import multiprocessing as mp
import psutil
import signal

def info(title):
    print (title)
    print ('module name:', __name__)
    if hasattr(os, 'getppid'):
        print ('parent process:', os.getppid())
    print ('process id:', os.getpid())

def foo(q,num):
    info('function foo')
    if type(num) is int:
       num*=2
       q.put(num)
    elif type(num) is Signal:
        print ("Terminated")
        time.sleep(10)
        os.kill(os.getpgid(pid), num)
    else :
       sys.exit("error")

def receive_signal(signum, stack):
    print 'Received:', signum

if __name__ == '__main__':
    info ("main")
    #mp.set_default('spawn')
    number = random.randint(0,100)
    print ("Initial number: ",number)
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,number))
    p.start()
    print ("Final Number: ",(q.get()))
    foo(q,signal.signal(signal.SIGTERM,recieve_signal))
    p.join()

At this moment I am struck at signal passing to function foo(q,signal.signal(signal.SIGTERM,recieve_signal))
Any help is much appreciated

A: As per documentation, signal.signal(...) only registers a signal, but it doesn't return any value and None gets passed to your foo() function:
foo(q,signal.signal(signal.SIGTERM,recieve_signal))

On the other hand, the second parameter to signal.signal() is a callback that is invoked when a signal of a specific type is caught (signal.SIGTERM in your case). You have already defined such handler, it's the receive_signal() function and its first parameter is the signal number. You can pass this to your foo() function by simply calling it:
def receive_signal(signum, stack):
    print 'Received:', signum
    foo(q, signum)   # NOTE: q is a module-level variable here


text:
Q: Why Was the Quick Find/Filter Removed From Synaptic? Synaptic used to have a textbox that you could use immediately when the app opened to find exactly the package you want.  Now it's been removed, and you can only use the Search (which buries you with useless results ... for most queries at least).
I found an article explaining how to re-enable it: Enable Quick Filter Search Box in Synaptic Package Manager, but what I can't understand is why on earth they removed it in the first place?
It's just bizarre for any software to make itself worse seemingly for no reason, and it's especially bizarre in a popular open source tool (with no corporate interests to blame for making things worse for the user).

A: The quick find feature was always reliant on the Xapian indexes, provided by the apt-xapian-index package. What changed wasn't Synaptic's behaviour, but rather the presence of apt-xapian-index by default.
Some of the reasons are given in the bug which caused Synaptic's dependency on Xapian to be demoted (from a recommendation, installed by default along with Synaptic, to a suggestion): maintaining the Xapian index caused performance issues (in 2011). Other packages such as aptitude also demoted their dependency, albeit later, in 2014.


text:
Q: Python Password Program I'm a beginner programmer and thought it would be cool to create a program to loop through "all" possible passwords.
On a scale of 1-10, how efficient would you rate the following "hacking program?" Is there any way to make the following code more efficient? Any algorithms or tricks that you may know of?
I've considered moving 'e' and more common letters to the beginning of my character array since those letters are used more commonly.
import sys

password = raw_input("Enter a password: ")

characters = []
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
number = ["1","2","3","4","5","6","7","8","9","0"]
symbol = ["!","@","#","$","%","^","&","*","(",")","_","+","-","="]

#Creates array with most keyboard characters
for i in range(len(lower)):
    characters.append(lower[i])
for i in range(len(upper)):
    characters.append(upper[i])
for i in range(len(number)):
    characters.append(number[i])
for i in range(len(symbol)):
    characters.append(symbol[i])

found = False

#For 1 character passwords
for a in range(len(characters)):
    if (characters[a] == password):
        print (characters[a])
        found = True
if (found):
    sys.exit()

#For 2 character passwords
for a in range(len(characters)):
    for b in range(len(characters)):
        if (characters[a] + characters[b] == password):
            print (characters[a] + characters[b])
            found = True
if (found):
    sys.exit()

for a in range(len(characters)):
    for b in range(len(characters)):
        for c in range(len(characters)):
            if (characters[a] + characters[b] + characters[c] == password):
                print (characters[a] + characters[b] + characters[c])
                found = True
if (found):
    sys.exit()

for a in range(len(characters)):
    for b in range(len(characters)):
        for c in range(len(characters)):
            for d in range(len(characters)):
                if (characters[a] + characters[b] + characters[c] + characters[d] == password):
                    print (characters[a] + characters[b] + characters[c] + characters[d])
                    found = True
if (found):
    sys.exit()

for a in range(len(characters)):
    for b in range(len(characters)):
        for c in range(len(characters)):
            for d in range(len(characters)):
                for e in range(len(characters)):
                    if (characters[a] + characters[b] + characters[c] + characters[d] + characters[e] == password):
                        print (characters[a] + characters[b] + characters[c] + characters[d] + characters[e])
                        found = True
if (found):
    sys.exit()

A: First of all, you didn't have to type all those symbols
>>> import string
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.digits
'0123456789'
>>>

so you can do:
lower = string.lowercase

and so forth
This can go away:
#Creates array with most keyboard characters
for i in range(len(lower)):
    characters.append(lower[i])
for i in range(len(upper)):
    characters.append(upper[i])
for i in range(len(number)):
    characters.append(number[i])
for i in range(len(symbol)):
    characters.append(symbol[i])

and be replaced with:
characters = "".join(upper, lower, number, symbol)

This can be simplified:
#For 1 character passwords
for a in range(len(characters)):
    if (characters[a] == password):
        print (characters[a])
        found = True
if (found):
    sys.exit()

to:
for a in characters:
    print a
    sys.exit()

The multi-character checks will need to loop, but try  writing the loops like I showed in the single character code above

A: In this regard, it is mandatory to mention itertools.
This answer doesn't provide an answer to "this is why your programming is efficient or not", but it's a reminder that if you quickly want a setup / script with which you can bruteforce something, there's a nice lib.
import itertools
import string

for guess in itertools.product(string.lowercase, repeat=10):
     password = ''.join(guess) #put the array elements together
     print password

itertools.product gives you all possible combinations (cartesian cross product) for a given array of elements, in this case, the lowercase alpahabet and you have the code that generates all passwords of arbitrary length for you in effectively 3 lines of code.
Now go rewrite that repeat=10 into a variable expression and do a for loop from 1 to whatever password length you'd like.

A: The most efficient code would be
password = raw_input("Enter a password: ")
guess = password
print guess

:)
Alright jokes aside, your solution is a simple brute force attack to find the password and if we have no additional information about the password (besides what the legal alphabet is) then a brute force attack is the best possible attack (in terms of algorithmic complexity).
But your code has scope for improvements in implementation.
Instead of
for i in range(len(lower)):
  characters.append(lower[i])
for i in range(len(upper)):
  characters.append(upper[i])
for i in range(len(number)):
  characters.append(number[i])
for i in range(len(symbol)):
  characters.append(symbol[i])

Do this
characters = lower + upper + number + symbol

And instead of having so many cases to handle what the password could be, let's use some Math to make things much much simpler to implement :)
Note that if the size of that characters list is n, and if the length of the password is l, then using some basic Discrete Math/Combinatorics, there are n^l possible combinations that we can make using the given alphabet set. We can simply map each and every combination of characters to a single number that is expressed in base n. eg If n = 2 and the alphabet comprises of just 'a' and 'b', then the number string 10 in base 2 will correspond to the string "ba". Similalry the string 00100 will coresspond to "aabaa"
So our task reduces to generating all possible strings.
This can be done via recursion (which has a little bit of overhead but it reduces the load on implementation)
def recurse(s, l, n):
    if n == l:
        if s == password: return True
        return False:
    for c in characters:
        if recurse(s + c, l, n+1) == True: return True:
    return False

 recurse("", len(password), 0)


text:
Q: How can one define a set of formulas inductively, without some base propositions being defined first? In some contexts (i.e. coalgebraic logic/coalgebraic modal logic) I see people commonly define (coalgebraic) languages (indeed sets of formulas) without considering any atomic propositions (or base formulas, in other words) first. I have never seen like this before this.
How is that even possible? is it common in other branches of logic?
Following you can see a glance from the paper "Expressive logics for coalgebras via terminal sequence induction" by someone expert of the field. Please don't be ignorant to the question just because it is about coalgebras and you have never seen them; this question doesn't seem to have much to do with that: you van even consider the boolean part not the modality, if you don't want the story coalgebraic.

**For those who are curious, $\Lambda$ is a set of predicate liftings for the signature functor.
Thanks.


text:
Q: Finding Records with Specific dateTime Difference in MySQL I have an audit Trail table where I store the records with time taken for each transaction
Ex:
DateTime                          ReferenceID           Status
2012-08-29 18:54:22      abc
2012-08-29 18:54:28      abc                               Success
2012-08-29 18:54:32      abcd
2012-08-29 18:54:48      abcd                                Success
I want to find out all the records that took more than say 10 seconds.
My output should look like
ReferenceID        TimeTaken
abcd                          16
Thanks
Soni

A: You can do a self join on the table from the records with blank Status to the corresponding Success record and calculate the difference between them. This query is assuming you only have the two records for each ReferenceID, if there may be more you will have to do some further filtering.
select d1.ReferenceID,
  TimeStampDiff(SECOND, d1.Dttm, d2.Dttm) TimeTaken
from data d1
left join data d2 on d2.ReferenceID = d1.ReferenceID
  and d2.Status = 'Success'
where d1.Status = ''
  and TimeStampDiff(SECOND, d1.Dttm, d2.Dttm) > 10

SQL Fiddle


text:
Q: loop through model in mvc razor code behind I am working on MVC4 App, and I am stuck at one point, I tried using google to help me, but without success. This might be more simple then I think, but coming from web forms and shifting to mvc is "painful" sometime.
I am trying to loop through the model I have and get the values stored in that model. I tried few approaches but I am getting an error everytime. This is what I have:
var modelAgentFilter = from s in _aa.Agents
                       where s.COUNTER == Convert.ToInt32(AgentID)
                       select s;
if (modelAgentFilter != null)
{
    ViewBag.FirstName = // Get FirstName object here
}

Thanks in advance for your comments.
Laziale
EDIT:
I did include for loop like this:
   if (modelAgentFilter != null)
                {
                    foreach (var property in modelAgentFilter)
                    {
                        string test = property.ADDRESS;
                    }
                }

But when the compiler will reach the foreach step I am getting this error: "LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression."
I can get to the properties of the var model using that foreach look but as soon as the compiler will try to loop the model that error pops up.
Thanks again

A: LINQ to Entities does not recognize any methods. You can't use even ToString() in LINQ expression. You need first convert your value and than add it in LINQ.
In your example you need to do something like following:
var _agentID = int.Parse(AgentID);

var modelAgentFilter = from s in _aa.Agents
                       where s.COUNTER == _agentID
                       select s;


text:
Q: libsvm svmpredict method output model file I use libsvm svmpredict method for classifying the images on Matlab.
I need svmpredict method's output model file that has extension with ".model". But I cannot create it. My usage is that,
model = svmtrain(train_label_set_libsvmformat, train_data_set_libsvmformat, '-t 2 -c 0.3 -g 0.01');
[predict_label, accuracy, prob_values] = svmpredict(test_label_set_libsvmformat, test_data_set_libsvmformat, model, 'output.model');

I wait for creating this file "output.model", but it doesn't exist.
Is there anything that is wrong for me?

A: From https://sites.google.com/site/kittipat/libsvm_matlab
% Train the SVM
model = svmtrain(trainLabel, trainData, '-c 1 -g 0.07 -b 1');
% Use the SVM model to classify the data
[predict_label, accuracy, prob_values] = svmpredict(testLabel, testData, model, '-b 1'); % run the SVM model on the test data

The last argument of svmpredict is not a filename, but the options you want to pass to svmpredict. If you want to save a model to a file, this usually is done when training the model in svmtrain. If you use the command line version of svm-train, the model-file is an additional parameter.
From what I make of the source code of libsvm for MATLAB, the model you get from executing the svmtrain command is just a scalar in MATLAB, so there is no built-in way to obtain a model-file.
If you want a model-file, you have to use the command line version of libsvm.


text:
Q: Update all Chart.js instances in order to apply changed defaults? Situation:
I'm currently integrating a dynamic dark theme feature and need to change the defaults of Chart.js on a change of the theme. It looks something like this (highly simplified):
function changeTheme(darkTheme = false) {
  if (darkTheme) {
    document.body.classList.add('dark-theme');
    Chart.defaults.global.defaultFontColor = 'white';
  } else {
    document.body.classList.remove('dark-theme');
    Chart.defaults.global.defaultFontColor = 'black';
  }
}

Problem:
The existing charts on the page don't immediately apply the changed default settings. Only on an update they do (e.g. on tooltip, change of data, resize of canvas).
I can manually update a chart by calling the instance method .update() of Chart. But I don't have access to all existing chart objects (no access to scope of the scripts creating them) and I didn't found a way to get them globally.

Question:

*

*Is there a way to force an update on all charts without their Chart instances?

*or: Is there a way to get all the chart instances to then update them all?

*or: Is this an XY Problem and there is a way to fix this I'm not thinking about?

I would already be satisfied with an answer to one of the above questions.

Example to reproduce the problem:
Show and run the code snippet. Hit the "toggleDarkTheme" button and click on "# of Votes" or something else to trigger an update.

// set function for theme
function changeTheme(darkTheme = false) {
  if (darkTheme) {
    document.body.classList.add('dark-theme');
    Chart.defaults.global.defaultFontColor = 'white';
  } else {
    document.body.classList.remove('dark-theme');
    Chart.defaults.global.defaultFontColor = 'black';
  }
}
changeTheme(false);

// button to toggle theme
let darkThemeActive = false;
document.getElementById('toggleDarkTheme').addEventListener('click', ()=>{
  darkThemeActive = !darkThemeActive;
  changeTheme(darkThemeActive);
});

/* example chart, pretend like you dont have access to this scope ;) */
{
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)',
                  'rgba(153, 102, 255, 0.2)',
                  'rgba(255, 159, 64, 0.2)'
              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)',
                  'rgba(153, 102, 255, 1)',
                  'rgba(255, 159, 64, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {
          responsive: true
      }
  });
  document.getElementById('triggerManualUpdate').addEventListener('click', ()=>{
    myChart.update();
  });
}
button {
  background-color: #eee;
  color: rgba(0,0,0,0.87);
  border: none;
  border-radius: 3px;
  padding: 0.5rem;
}

.dark-theme {
  background-color: #212121;
  color: white;
}

.dark-theme button {
  background-color: #212121;
  color: white;
}

  <button id="toggleDarkTheme">toggleDarkTheme</button>
  <button id="triggerManualUpdate">triggerManualUpdate</button>

<canvas id="myChart" width="400" height="400"></canvas>

A: You can loop through chart instances dynamically using the Chart.instances object.  For example:
Chart.helpers.each(Chart.instances, function(instance){
  instance.chart.update();
});

I've modified your example below to update all charts in the toggle function.  You'll notice that the font color now changes with toggle.

// set function for theme
function changeTheme(darkTheme = false) {
  if (darkTheme) {
    document.body.classList.add('dark-theme');
    Chart.defaults.global.defaultFontColor = 'white';
  } else {
    document.body.classList.remove('dark-theme');
    Chart.defaults.global.defaultFontColor = 'black';
  }

  // Force updates to all charts
  Chart.helpers.each(Chart.instances, function(instance){
    instance.chart.update();
  });
}
changeTheme(false);

// button to toggle theme
let darkThemeActive = false;
document.getElementById('toggleDarkTheme').addEventListener('click', ()=>{
  darkThemeActive = !darkThemeActive;
  changeTheme(darkThemeActive);
});

/* example chart, pretend like you dont have access to this scope ;) */
{
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)',
                  'rgba(153, 102, 255, 0.2)',
                  'rgba(255, 159, 64, 0.2)'
              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)',
                  'rgba(153, 102, 255, 1)',
                  'rgba(255, 159, 64, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {
          responsive: true
      }
  });
}
button {
  background-color: #eee;
  color: rgba(0,0,0,0.87);
  border: none;
  border-radius: 3px;
  padding: 0.5rem;
}

.dark-theme {
  background-color: #212121;
  color: white;
}

.dark-theme button {
  background-color: #212121;
  color: white;
}

  <button id="toggleDarkTheme">toggleDarkTheme</button>

<canvas id="myChart" width="400" height="400"></canvas>


text:
Q: Laravel 4 Redirects aren't working I am attempting to use return Redirect::route('home'); in my UserController, but it doesn't appear to work (displays a blank page). I've tried naming the route, but to no avail.
<?php

class UserController extends BaseController {

    public $restful = true;

    public function get_new()
    {
           return View::make('users.new')
                ->with('title', 'Rentaholics - Register');
    }

    public function post_create() {
        $validation = Users::validate(Input::all());

        if($validation -> passes()){
            Users::create(array(
                'username'=>Input::get('username'),
                'password'=>Hash::make(Input::get('password')),
                'email'=>Input::get('email')
            ));

            return Redirect::to_route('home')->with('message', 'Thanks for Registering!');
        }else{
                 return Redirect::to('register')->with_errors($validation)->with_input();
        }
    }
}


text:
Q: LLVM IR temporaries use I'm trying to find out whether LLVM IR temporaries can be used outside a loop in which they were defined. For that, I compiled the following simple C code:
while (*s == 'a')
{
    c = *s++;
}
*s = c;

and like I suspected, the final write outside the loop (*s = c) is done
with another temporary (%tmp5) than the one read to inside the loop (%tmp4)
while.body:      ; preds = %while.cond
  %tmp3 = load i8*, i8** %s.addr, align 8
  %incdec.ptr = getelementptr inbounds i8, i8* %tmp3, i32 1
  store i8* %incdec.ptr, i8** %s.addr, align 8
  %tmp4 = load i8, i8* %tmp3, align 1
  store i8 %tmp4, i8* %c, align 1
  br label %while.cond

while.end:       ; preds = %while.cond
  %tmp5 = load i8, i8* %c, align 1
  %tmp6 = load i8*, i8** %s.addr, align 8
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  ; store i8 %tmp4, i8* %tmp6, align 1 ;
  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  store i8 %tmp5, i8* %tmp6, align 1

When I edit the *.ll file and manually replace %tmp5 with %tmp4,
then llvm-as is unhappy:
$ llvm-as modified.ll
Instruction does not dominate all uses!
%tmp4 = load i8, i8* %tmp3, align 1
store i8 %tmp4, i8* %tmp6, align 1

Is there any example where a temporary will be defined
inside a loop and used outside of it? Thanks!

A: LLVM doesn't really have temporaries, it uses SSA. That's short for static single assignment, and the key word here is single. Everything is a value and the value must always be assigned once.
Anything can use any value which necessarily has been assigned by the time it's used. "Dominates" means "provably comes before" in the error message you got, ie. LLVM sees that the input string is "b", the code will jump straight from while.cond to while.end, past while.body.
When you do use values from within loop after the end of the loop, things can get a little confusing. You may need to think hard and close the Slack and Facebook tabs. But LLVM doesn't mind.

A: The while.end basic block has only while.cond block as its predecessor. Thus, you can't access variables defined in while.body. It is like you want to access a variable defined in one branch from another:
if(...)
   int x = ...;
else
   print(x);

Instead, declare whatever variables you need in loop entry block and then use it from both while.body and while.end.


text:
Q: How to revert to default google search from google.com/cse? I have a problem with Google search in both Chrome and Firefox, when I type a search query, it will search at http://www.google.com/cse? rather than at https://www.google.com/#q= or at https://www.google.com/search?
I've read about a similar problem and the solution here, but they don't offer the solution for Linux/Ubuntu.
as the commentator say, I'd like to explain my problem more clearly.
Someone say it happened because I've install some add ons in my browser.
Actually, when I type some words at my browsers (both) address bar, It will search by http://www.google.com/cse?. But I want it search under https://www.google.com/search? (default).

A: Since I don't use chrome this is only a partial answer.
You can change the keyword.URL preference to your wishes, using the about:config page, as laid out in the comments. Simply change the url according to your wishes. If you're on Firefox 23 or later this preference has been removed meaning that the search bar and the location bar will use the same search provider. You can read more about the consolidation of Firefox search preferences on this Bugzilla page.
What does that mean for you? Firefox 23 ignores the keyword.URL parameter. That means that it will automatically use the search engine that you have configured in the search bar in the location bar as well.
With this move Mozilla wants you to use keywords. You can assign keywords by clicking on the down arrow next to the current search engine icon and select Manage Search Engines. For instance, you can assign g to Google. If you want to do a Google search in your location bar, simply type g your search terms here and you're using Google.

A: I've found the answer at last..
try to disable add on were registered on Start up Applications... on Ubuntu
it works for me.
NOTE:
as addition solution,
do this in terminal
locate chrome.json
it will return a path
sudo nano [the path]
in my condition, it will return /etc/chromium-browser/policies/managed/chrome.json
then, change the content with this
{
  "DefaultSearchProviderEnabled": true,
  "DefaultSearchProviderInstantURL": "http://www.google.com/search?q={searchTerms}",
  "DefaultSearchProviderKeyword": "google.com",
  "DefaultSearchProviderName": "Google",
  "DefaultSearchProviderSearchURL": "http://www.google.com/search?q={searchTerms}",
  "DefaultSearchProviderSuggestURL": "http://www.google.com/search?q={searchTerms}"
}

Hope Helps..
Best Regards,
Ahmad

A: cd /etc/opt/chrome/policies/managed/
I removed file «chrome.json» in that directory and now my default search engine's Google again :)

A: In Chrome go to Settings > Manage Search Engines and see if you have the one you're looking for, then set it as default.
If you don't, then add it. Set whatever name and keyword you want and add this to the URL form:
http://www.google.com/#sclient=psy&hl=en&site=&source=hp&q=%s


text:
Q: RGeo convex hull of list of points RGeo has convex hull method available, but no documentation at all in this matter.
Given set of Points, how to I find their convex hull?

A: Good question. Turns out there is a geometry type called "MultiPoint" that works for this. I made a simple example to test it out and it appears to work well.
f = RGeo::Geos.factory(:srid => 3361, :buffer_resolution => 8) #my typical local rectilinear projection factory with my default settings.
coords = [[1,1], [2,2], [1,3]]
points = []
coords.each {|x,y| points << f.point(x,y)}

f.multi_point(points).convex_hull


text:
Q: Issue with error validation and page action? Hi guys I'm new to coding and loving every minute of it :)
So the following code is in my registration.php file.  I want to make it so that when the user fills everything BEFORE it will direct them to my invoice.php file after pressing the register button.  If they are missing some requirements, go back to the registration form and (hopefully after I get this figured out, put some sticky forms so they don't have to type in whatever text was validated)  Also, getting an error "
Notice: Undefined index: submit in C:\xampp\htdocs\assignment_2\registration.php on line 9" on my validation at the top of my PHP code, not too sure what I'm suppose to put there. :( As always, any help is greatly appreciated!

            New User Registration

<?php
if($_POST["submit"]=="login")
    {
        if(preg_match("/^[0-9a-zA-Z_]{5,}$/", $_POST["user"]) === 0)
          $errUser = '
User must be bigger that 5 chars and contain only digits, letters and underscore
';
        // Password must be strong
        //if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["pass"]) === 0)
        if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["pass"]) === 0)
          $errPass = '
Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit
';
    // Email mask
        if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) === 0)
          $errEmail = '
Email must comply with this mask: chars(.chars)@chars(.chars).chars(2-4)
';

    }

  ?>
        <form action="invoice.php" method="post">

                        Username
                        :
                        <td <input name="user" type="text" size="16" value="<?php echo $_POST["user"]; ?>">
          <?php  if(isset($errUser)) echo $errUser; ?>

                        Password
                        :
                        <input name="pass" type="password" size="16" value="<?php echo $_POST["pass"]; ?>">
          <?php  if(isset($errPass)) echo $errPass; ?>

                        Email
                        :
                        <input name="email" type="text" size="50" value="<?php echo $_POST["email"]; ?>">
          <?php  if(isset($errEmail)) echo $errEmail; ?>

                <input type='submit' name='register' value='Register'>

        </form>

A: The problem here is one that many programmers that are new to PHP run into. See, $_POST is an array that includes all parameters that have been submitted with the POST request the script was requested with. But what if there were none, or the script was requested using GET? You got it: it's empty.
In your case, submit doesn't seem to be present in the POST data. In that case you most likely want to just display the form, so the user can enter the data and submit the form (which will set that value). SO you have to check FIRST if "submit" is there.
Second: Your submit button is called "register", and it's value (which is not really necessary, but alright) is "Register". So if the form is submitted, the data that is sent is register=Register&<other fields>. Therefore you have to check for the presence  of "register", not "submit"
if (isset($_POST['register']) && $_POST['register']) {
    // evaluate
}

A: you don't have check any var is set so you can see more  php error
i change more check, you can try

            New User Registration

        <?php

      $errEmail    = "";
      $errUser     = "";
      $errPass     = "";

      //not too sure what this if statement suppose to be.
      if(isset($_POST["register"])){//1. no '{' 2. the post is not ckeck 'type', is 'name'

        // Email mask
        if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) === 0)
          $errEmail = '
Email must comply with this mask: chars(.chars)@chars(.chars).chars(2-4)
';
        // User must be digits and letters
        if(preg_match("/^[0-9a-zA-Z_]{5,}$/", $_POST["user"]) === 0)
          $errUser = '
User must be bigger that 5 chars and contain only digits, letters and underscore
';
        // Password must be strong
        //if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["pass"]) === 0)
        if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["pass"]) === 0)
          $errPass = '
Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit
';
      }
  ?>
        <form method="post">

                        Username
                        :
                        <input name="user" type="text" size="16" value="<?php echo (isset($_POST["user"]))?$_POST["user"]:'';/*3.no check the var is set?*/ ?>">
          <?php  if(isset($errUser) and $errUser !='') echo $errUser; ?>

                        Password
                        :
                        <input name="pass" type="password" size="16" value="<?php echo (isset($_POST["pass"]))?$_POST["pass"]:''; ?>">
          <?php  if(isset($errPass) and $errPass !='') echo $errPass; ?>

                        Email
                        :
                        <input name="email" type="text" size="50" value="<?php echo (isset($_POST["email"]))?$_POST["email"]:''; ?>">
          <?php  if(isset($errEmail) and $errEmail !='') echo $errEmail; ?>

                <input type='submit' name='register' value='Register'>

        </form>


text:
Q: tfs git, retrieving old ssis version from tfs git We had an unusual circumstance and we may need to get some prior versions of ssis packages back from tfs git.   Is there a way to do that?   With microsoft only tfs I would see old versions.   With VS 2017 Enterprise and a fairly current TFS GIT all we get is a file manager to view the branch and make changes.  I was thinking, with branches, there might not be a way to access versions that were created outside that branch.   But in this case the version of the package when the branch was created would be adequate.   Is there a way to retrieve old versions of SSIS packages with TFS GIT?

A: You can retrieve the old version in the commit history from the View History in the Actions menu on Visual studio.

Then select a commit history and right click, select New Branch to retrieve the old version into a new branch.

You can also use git commands to roll back to an old commit.
run git hist to list the commits history. And select the commit you want to retrieve.
run git checkout -b new-branch-name <commit-hash> to checkout the old version into a new branch.
See this thread for more information.


text:
Q: DynamoDB - Get all items which overlap a search time interval My application manages bookings of a user. These bookings are composed by a start_date and end_date, and their current partition in dynamodb is the following:
PK                  SK              DATA
USER#1#BOOKINGS     BOOKING#1       {s: '20190601', e: '20190801'}

[GOAL] I would query all reservations which overlap a search time interval as the following:

I tried to find a solution for this issue but I found only a way to query all items inside a search time interval, which solves only this problem:

I decided to make an implementation of it to try to make some change to solve my problem but I didn't found a solution, following you can find my implementation of "query inside interval" (this is not a dynamodb implementation, but I will replace isBetween function with BETWEEN operand):

import { zip } from 'lodash';

const bookings = [
  { s: '20190601', e: '20190801', i: '' },
  { s: '20180702', e: '20190102', i: '' }
];

const search_start = '20190602'.split('');
const search_end   = '20190630'.split('');

// s:20190601 e:20190801 -> i:2200119900680011
for (const b of bookings) {
  b['i'] = zip(b.s.split(''), b.e.split(''))
    .reduce((p, c) => p + c.join(''), '');
}

// (start_search: 20190502, end_search: 20190905) => 22001199005
const start_clause: string[] = [];
for (let i = 0; i < search_start.length; i += 1) {
  if (search_start[i] === search_end[i]) {
    start_clause.push(search_start[i] + search_end[i]);
  } else {
    start_clause.push(search_start[i]);
    break;
  }
}
const s_index = start_clause.join('');

// (end_search: 20190905, start_search: 20190502) => 22001199009
const end_clause: string[] = [];
for (let i = 0; i < search_end.length; i += 1) {
  if (search_end[i] === search_start[i]) {
    end_clause.push(search_end[i] + search_start[i]);
  } else {
    end_clause.push(search_end[i]);
    break;
  }
}
const e_index = (parseInt(end_clause.join('')) + 1).toString();

const isBetween = (s: string, e: string, v: string) => {
  const sorted = [s,e,v].sort();
  console.info(`sorted: ${sorted}`)
  return sorted[1] === v;
}

const filtered_bookings = bookings
  .filter(b => isBetween(s_index, e_index, b.i));

console.info(`filtered_bookings: ${JSON.stringify(filtered_bookings)}`)

A: There's not going to be a beautiful and simple yet generic answer.
Probably the best approach is to pre-define your time period size (days, hours, minutes, seconds, whatever) and use the value of that as the PK so for each day (or hour or whatever) you have in that item collection a list of the items touching that day with the sort key of the start time (so you can do the inequality there) and you can use a filter on the end time attribute.
If your chosen time period is days and you need to query across a week then you'll issue seven queries. So pick a time unit that's around the same size as your selected time periods.
Remember you need to put all items touching that day (or whatever) into the day collection. If an item spans a week it needs to be inserted 7 times.

A: Disclaimer: This is a very use-case-specific and non-general approach I took when trying to solve the same problem; it picks up on @hunterhacker 's approach.
Observations from my use case:

*

*The data I'm dealing with is financial/stock data, which spans back roughly 50 years in the past up to 150 years into the future.

*I have many thousands of items per year, and I would like to avoid pulling in all 200 years of information

*The vast majority of the items I want to query spans a time that fits within a year (ie. most items don't go from 30-Dec-2001 to 02-Jan-2002, but rather from 05-Mar-2005 to 10-Mar-2005)

Based on the above, I decided to add an LSI and save the relevant year for every item whose start-to-end time is within a single year.  The items that straddle a year (or more) I set that LSI with 0.
The querying looks like:
if query_straddles_year:
   # This doesn't happen often in my use case
   result = query_all_and_filter_after()
else:
   # Most cases end up here (looking for a single day, for instance)
   year_constrained_result = query_using_lsi_for_that_year()
   result_on_straddling_bins = query_using_lsi_marked_with_0() # <-- this is to get any of the indexes that do straddle a year
   filter_and_combine(year_constrained_result, result_on_straddling_bins)


text:
Q: Python, can't get results using Xpath of Chrome when scraping titles on this website I learned some simple skills to scrap websites and wanted to apply them to a very small project. Here I want to get every title of all the listed results from this website. I believe I gave the right Xpaths and I am able to get other text information (like the text before searching box). But I got '[]' blank results each time when I tried to scrap information in the body container (I tried many kinds of Xpaths too, so I think the problem is less likely to be caused by this) .
result = requests.get("https://www.hotel.info/Search?lng=EN&LACCode=L172544%7CTHA&hs_f_locationnr=172544&hs_destination=Bangkok+Metropolitan+Region%2C+Thailand&HotelMasterID=&ChainID=&hs_arrival=&hs_departure=&h_persons_total=1&hs_rooms=1&hs_roomType=2&cpn=5&location=Bangkok+Metropolitan+Region%2C+Thailand", allow_redirects=False)
selector = etree.HTML(result.text)
result.status_code
  200
title1 = selector.xpath('.//*[@id="L132761"]/@title')
print(title1)
  []
title2 = selector.xpath('.//*[@id="L132761"]/@title/text()')
print(title2)
  []
title3 = selector.xpath('.//*[@id="L132761"]/@href')
print(title3)
  []

The screenshot of DevTool on Chrome is here. So for this first item I want to get is "Pullman Bangkok Hotel G".
I guess it's because this part is not "pure" text? I cannot select these words by mouse on the website. But I don't have any idea of how to scrap this kind of information. And after I click the title and go to its website, I was able to scrap the text inside this child link.
New Edit: The "result.text[:1000]" returns results starts with:
'\r\n<!DOCTYPE html>\r\n<!--[if IE 8 ]><html class="ie ie8" lang="EN"><![endif]-->\r\n<!--[if IE 9 ]><html class="ie9" lang="EN"><![endif]-->\r\n<!--[if (gt IE 9)|!(IE)]><!-->\r\n<!--<![endif]-->\r\n<head>\r\n\t<meta name="viewport" content="width=device-width, initial-scale=1.0">\r\n\t<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />\r\n\t<title>HOTEL INFO | Hotels Bangkok Metropolitan Region, Thailand</title>\r\n\t<meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={});  So is it the case that this part is generated by javascript?
I hope I've explain the issue clear. Please tell me how to solve this problem or give me any suggestion you can think of.
Thank you!

A: requests.get gets plain html.
I believe the content you are trying to access is generated by javascript, which requests doesn't execute.
You could verify it by printing result.text and seeing what requests.get is returning.
If that's the case you may try using something like Selenium.


text:
Q: Multiple occurances of delimeters within a HTML template I am facing a problem that I can't get my head around. I thought I would turn to the experts once again to shine some light.
I have a HTML template and within the template I have delimiters like:
[has_image]
The image is
[/has_image]
These delimiters may have multiple occurances within the template and below is what I am trying to achieve:

*

*Find all occurances of these delimiters and replace the content between these delimiters with an image source or replace it empty if image doesn't exist but still keep the value/content of the remaining template.

Below is my code that works only for one occurance but struggling to accomplish it for multiple occurances.
function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
    $occurances = substr_count($template_body, $start_tag);
    $x = 1;

    while($x <= $occurances) {
        $start = strpos($template_body, $start_tag);
        $stop = strpos($template_body, $end_tag);

        $template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);
        $x++;
    }

    return $template_body;
}

$template_body will have HTML code with delimiters

replace_text_template($template_body, "[has_image]", "[/has_image]");

Whether I remove the while loop it still works for a single delimiter.

A: I have managed to solve the problem. If anybody finds this useful please feel free to use the code. However, if anyone finds a better way please do share it.
function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
    $occurances = substr_count($template_body, $start_tag);
    $x = 1;

    while($x <= $occurances) {
        $start = strpos($template_body, $start_tag);
        $stop = strpos($template_body, $end_tag);
        $template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);
        $template_body = str_replace($start_tag.''.$end_tag, '', $template_body); // replace the tags so on next loop the position will be correct
        $x++;
    }

    return $template_body;
}

A: function replace_text_template($template_body, $start_tag, $replacement = '') {
    return preg_replace_callback("~\[".preg_quote($start_tag)."\].*?\[\/".preg_quote($start_tag)."\]~i", function ($matches) use ($replacement) {
        if(preg_match('~<img.*?src="([^"]+)"~i', $matches[0], $match)) {
            if (is_array(getimagesize($match[1]))) return $match[1];
        }
        return $replacement;
    }, $template_body);
}

$template_body = <<<EOL
text
[has_image]
The image is
[/has_image]

abc [has_image]
The image is
[/has_image]xyz
EOL;

echo replace_text_template($template_body, "has_image", "replacement");

Returns:
text
replacement

abc http://blog.stackoverflow.com/wp-content/themes/se-company/images/logo.pngxyz


text:
Q: How come Sam is alive at all? At the very final scene of the second season of Game of Thrones, something weird happens.

 Sam notices a White Walker along with an army of wights, all heading his way. Since he can't run, he hides. But when we see the White Walker, it seems that he and Sam look at each other.

 And for some reason, the White Walker doesn't kill Sam. And even if he didn't really see him. It was my impression that they could sense humans in their vicinity. Surely Sam would have set these internal alarms of the icy CGI warrior.

So how is Sam alive at all??

A: If you are walking along a forest path and you see a gnat on a tree, you don't make the effort to go over and kill it.
The whitewalker is the same. He saw Sam, evaluated the situation and saw him as basically nothing. less than a threat. So puny, pitiful and pathetic that he didn't even bother to gesture to have one of his underlings go over and slay him.

A: It may be the white walker didn't see the sam. When the white walker calling His army to attack and White walker must be far away behind the stone to see the Sam and his is looking only his army.