Q: Is there a function to select a group of hours from different days? I'm looking for a way to select in Amazon Athena a selection of hours for different days.
I have a table with visitors to a specific location for every half hour, I now want to know the visitors during opening hours for a store, for the period of a month.
I now used this but doing it day by day is quite a job.
Was trying to split datetime with Datepart but didn't get it working properly.
SELECT visitors, datetime
FROM corrected_scanners_per_half_hour
WHERE datetime
    BETWEEN CAST('2020-05-25 08:30:00' AS timestamp)
        AND CAST('2020-05-25 17:30:00' AS timestamp) ;

A: Here you go
select visitors, date(datetime)
from corrected_scanners_per_half_hour
where date_format(datetime, '%H:%i') between '08:30' and '17:30'


Q: Adding CURL as static library to a C++ CMake project I have a problem with adding CURL library to CMake project. In my CMakeList.txt I have the following lines for adding CURL:
    #option(CURL_STATICLIB "Set to ON to build libcurl with static linking."  ON)
if(WIN32)
    add_definitions("-DCURL_STATICLIB")
endif()
option(LIBCURL_ENABLE "Enable or disable the requirement of libcurl" ON)

if(LIBCURL_ENABLE)
    find_path(LCURL_INCLUDE_DIR
        NAMES
            curl.h
        PATHS
            /usr/include/curl
            ENV "PROGRAMFILES(X86)"
            ENV "LIBCURL_ROOT"
        PATH_SUFFIXES
            include)

    find_library(LCURL
        NAMES
            libcurl.a
            libcurl.lib
        PATHS
            /usr/lib/x86_64-linux-gnu
            /usr
        PATH_SUFFIXES
            lib
            lib/x86_64-linux-gnu)
    if(LCURL STREQUAL "LCURL-NOTFOUND")
        message(FATAL_ERROR "libcurl NOT found: use `-DLIBCURL_ENABLE=OFF` to build without libcurl support")
    else()
        set(LIBS ${LIBS} ${LCURL})
        include_directories(AFTER ${LCURL_INCLUDE_DIR})
    endif()
else()
    add_definitions("-DCONF_NO_LIBCURL")
endif()
...

if(LIBCURL_ENABLE)
    target_link_libraries(app ${ZLIB_LIBRARIES} ${LCURL})
endif()

Everything is okay on Windows. But on Linux, I got this message from the make install command:
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libcurl.a(libcurl_la-content_encoding.o): undefined reference to symbol 'inflateInit2_'
/usr/lib/x86_64-linux-gnu/libz.so: error adding symbols: DSO missing from command line

A: The compilation was resolved with the following replacement.
#option(CURL_STATICLIB "Set to ON to build libcurl with static linking."  ON)
if(WIN32)
    add_definitions("-DCURL_STATICLIB")
endif()
set(CURL_LIBRARY "-lcurl")
find_package(CURL REQUIRED)
include_directories(${CURL_INCLUDE_DIR})

if(LIBCURL_ENABLE)
    target_link_libraries(app ${CURL_LIBRARIES})
endif()


Q: Convert string date to Datetime C# How can I convert 1-2-2016 to Datetime format dd-MMM-yyyy
For Example :
The output of 1-2-2016 should be 1-Feb-2016
I've tried the following code but it's returing 2-Jan-2016.
 Updated_Value = Convert.ToDateTime(Updated_Value).ToString("dd-MMM-yyyy");

The Data in Update_Value variable is coming from database whose datatype is varchar.
Kindly Help me to resolve this .
Thanks in advance .

A: Try this:
DateTime dt;
DateTime.TryParseExact(Updated_Value, "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

var newdate = dt.ToString("d-MMM-yyyy");


Q: Visitor pattern. Is void* an acceptable return type for a completely abstract interface? I have an AST, represented in the usual way (a tree of nodes of an abstract type). I have several uses cases for traversing this tree (an optimizer, which returns another AST; IR code generation, which returns a llvm::Value*; and a debug analyzer, which simply outputs to stdout and returns nothing).
A visitor feels like the right way to go here, but the differing return types through each use case of the visitor make it hard to see how to implement an interface for this. I considered this:
class Visitor;

class ASTNode {
public:
  virtual void accept(Visitor *visitor);
};

class Visitor {
public:
  virtual void visit(CallNode *node) = 0;
  virtual void visit(BinExprNode *node) = 0;
  // etc
};

Because of the lack of return value, each Visitor implementation would need to build up internal state and provide a result() method with a suitable return type. That is complex, however, since each call to visit() needs some context around the expression being visited (i.e. the call standing alone, or is it being used as part of a binary expression?). It makes it tricky for things like binary expression code generation to collect return values from visiting the nodes of the operands (I could do it with an internal temporary state variable or some such, but it feels over-engineered) and hard to reason about (the state keeps changing).
class OptimizingVisitor : public Visitor {
  ASTNode *m_result;
public:
  ASTNode *result() {
    return m_result;
  }

  void setResult(ASTNode *node) {
    m_result = node;
  }

  void visit(CallNode *node) {
    node->left()->accept(this);
    ASTNode *optimizedL = result();
    node->right()->accept(this);
    ASTNode *optimizedR = result();
    setResult(new CallNode(optimizedL, optimizedR));
  }

  // ... snip ...
};

I could make it even more complex to avoid the "state keeps changing" issue by passing in a new visitor for each node. It just feels like this problem warrants a more functional solution.
Really, I'd like to write the above much more simply and easier to read:
class OptimizingVisitor : public Visitor {
public:
  ASTNode* visit(CallNode *node) {
    ASTNode *optimizedL = node->left()->accept(this);
    ASTNode *optimizedR = node->right()->accept(this);
    return new CallNode(optimizedL, optimizedR);
  }

  // ... snip ...
};

Of course now I've changed the return type, so it doesn't fit my Visitor contract. Far from defining completely separate interfaces for each possible implementation of a a Visitor and making the AST aware of those visitor types, it seems the only really logical thing to use is a void*. Does this sort of API warrant the use of void*? Is there a better way to do this?

A: If I get this right, I might have something useful. Referring to your sample at https://gist.github.com/d11wtq/9575063, you cannot have
class ASTNode {
public:
   template <class T>
   virtual T accept(Visitor<T> *visitor);
};

because there are no template virtual functions. However, you may have a generic class
template <class D, class T>
struct host {
   virtual T accept(Visitor<T> * visitor);
   // I guess, { return visitor->visit(static_cast <D*>(this)); }
};

and a collection
template <class D, class... T>
struct hosts : host <D, T>... { };

so that, when the set of possible return types is limited, you can say e.g.
class ASTNode : public hosts <ASTNode, T1, T2, T3> {
public:
   // ...
};

Now you have three different Visitor contracts of return types T1,T2,T3.

A: Maybe this is helpful.
Using return type covariance to make accept() calls type-safe:
class Visitor;

class ASTNode
{
public:
    virtual ASTNode* accept(Visitor* visitor);
};

class CallNode;
class BinaryExpressionNode;

class Visitor
{
public:
    virtual CallNode* visit(CallNode* node) = 0;
    virtual BinaryExpressionNode* visit(BinaryExpressionNode* node) = 0;
};

Implementations:
class CallNode : public ASTNode
{
public:
    CallNode(BinaryExpressionNode* left, BinaryExpressionNode* right);

    // return type covariance
    CallNode* accept(Visitor* visitor) override
    {
        return visitor->visit(this);
    }

    BinaryExpressionNode* left();
    BinaryExpressionNode* right();
};

class BinaryExpressionNode : public ASTNode
{
public:
    BinaryExpressionNode* accept(Visitor* visitor) override
    {
        return visitor->visit(this);
    }
}

class OptimizingVisitor : public Visitor
{
public:
    CallNode* visit(CallNode* node) override
    {
        // return type covariance will make this operation type-safe:
        BinaryExpressionNode* left = node->left()->accept(this);
        auto right = node->right()->accept(this);
        return new CallNode(left, right);
    }

    BinaryExpressionNode* visit(BinaryExpressionNode* node) override
    {
        return new BinaryExpressionNode(node);
    }
};


Q: Intellij Accessing file from hadoop cluster As part of my intellij environment set up I need to connect to a remote hadoop cluster and access the files in my local spark code.
Is there any way to connect to hadoop remote environment without creating hadoop local instance?
A connection code snippet would be the ideal answer.

A: If you have a keytab file to authenticate to the cluster, this is one way I've done it:
val conf: Configuration: = new Configuration()
conf.set("hadoop.security.authentication", "Kerberos")
UserGroupInformation.setConfiguration(conf)
UserGroupInformation.loginUserFromKeytab("user-name", "path/to/keytab/on/local/machine")
FileSystem.get(conf)

I believe to do this, you might also need some configuration xml docs. Namely core-site.xml, hdfs-site.xml, and mapred-site.xml. These are somewhere usually under /etc/hadoop/conf/.
You would put those under a directory in your program and mark it as Resources directory in IntelliJ.


Q: help understanding this reverse polarity protection circuit Going through LT4363 evaluation kit DC2062A-B (schematic here), I came across a reverse protection circuitry that protects downstream components from reverse transients and reverse DC voltage:

In short, this circuit protects the downstream components by shorting the negative voltage when present at INPUt to DGATE and thus turning off Q2. when the voltage at INPUT is positive, Dgate gets biased via D2.
from DC2062A demo manual:

The DC2062A features reverse protection circuitry that protects
  downstream components from reverse transients of up to –150V. This
  number is limited by the BVDSS of Q2. The reverse protection circuitry
  also protects against reverse DC voltage of up to –30V.

My questions are:

*

*Why is the reverse DC voltage protection limited to only -30V? I simulated the circuit at input -100V and couldn't find what components are stressed or damaged at this voltage. So where did the number (-30V) come from? Am I missing something here? I want to know this as I would like to make the circuit block negative voltages upto -100V.

*A similar circuit is implemented in LTC4366 DEMO circuit DC1850A-A but with a -100V reverse DC voltage protection:

What are the pros/cons of using zener diode and capacitor in the first circuit over using the simpler solution of the second circuit? I'm guessing that the capacitor is used as a tank help turn off the mosfet Q2 quicker when the input voltage is suddenly switched from a posotive voltage to a negative one. I'm not sure.

A: the -100V is a 5A inductive pulse, whereas DC survival spec is only -30V +50V.
The reason for this -30V is in case a alternator charged 24V vehicle is used to jumper cable another with the cables reversed. (momentarily)
The 2nd simple circuit is missing parts and will not survive all the test conditions for  ISO-16750-2 tests 1 thru 5b .  Keep this date in mind when reviewing solution documents.
For more details, consult with ISO-16750-2 or the older (2010) ISO7637-2 test levels on each pulse and Steady state conditions.  THere are different classes III and IV with pulse levels up to -600V for 24V system.


Q: jQuery loading other html pages, but how to revert to original content So i have done this small piece of jQuery code to load html files into a DIV but I'm struggling to work out how i can for example place a back button on the loaded content and once clicked will revert to the original content any ideas?
Ideally i would like to use a ajax effect when loading the content with a throbber but reading up online loasd is the best way?
$('.load-page').on("click", function() {
  var href = $(this).attr("href");
  $('#in-the-news').load(href);
  return false
});

link:
link

html:

original content

A: You have to cache the original content into another object when the user presses the link, and then take it back when the user press the original link.
somethin like this (untested)
$('.load-page').on("click", function() {
  var href = $(this).attr("href");
  if ($('#hidden-cache').html() == ''){
      $('#hidden-cache').html($('#in-the-news').html());
  }
  $('#in-the-news').load(href);
  return false
});

$('.original-page').on("click", function() {
  $('#in-the-news').html($('#hidden-cache').html());
  return false
});

original content


Q: AEM: How common component injected in multiple components can have dynamic value I have a common component which is injected in multiple components via data-sly-resource.
componentA

componentB

In some-common-component.html a "class" need to be added to the div which will be dynamic and specific to the component it is injected from. For example, when this component is added in componentA
the html wuld be:

and when added in componentB it would be

How can I achieve this? How would I know who is injecting this component or it possible to send extra parameters from the parent component which I can access from some-common-component.html

A: For this use case it’s probably best to use HTL templates:
<sly data-sly-use.common="common.html" data-sly-call="${common.myTemplate @ buttonClass='myClassA'}"></sly>

A: You can make use of requestAttributes (refer here)
Component A (passing the value):
Sightly :

<sly data-sly-use.compA = "com.mysite.core.models.CompA"/>

Sling Model :
package com.realogy.sir.core.models;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CompA {

    public Map<String, Object> attribute = new HashMap<>();

    @PostConstruct
    protected void init() {
        attribute.put("attributeVal", "componenta");
    }
}

Component B (passing the value):
Sightly :

<sly data-sly-use.compB = "com.mysite.core.models.CompB"/>

Sling Model :
package com.realogy.sir.core.models;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CompB {

    public Map<String, Object> attribute = new HashMap<>();

    @PostConstruct
    protected void init() {
        attribute.put("attributeVal", "componentb");
   }
}

Common Component (consuming the value):
Sightly :

<sly data-sly-use.commonComp= "com.mysite.core.models.CommonComp"/>

Sling Model:
package com.mysite.core.models;

import javax.inject.Inject;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CommonComp {

    @Inject @Optional @Default(values="component")
    private String attributeVal;

    public String getAttributeVal() {
        return attributeVal;
    }

}


Q: How to reset a variable after 3 seconds in Android? I am trying to create a Service. In this Service I ahve this variable:
String command="Go"

I want to design a function that does this:

Within 3 seconds, the command will return value "Go"
If the time is bigger than 3 seconds, the command will be reset to "".

My current solution is using a Thread. Do you think it is a safe and good solution?
public String command;

public String getValue(){
    command="GO";
    try {
        Thread.sleep(3000);
        command="";
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return command;
}

A: As you are doing it at MainThread the app will not response to user and it's the worst thing can happen! I suggest you to use RXJava and be aware of blocking UI Thread!
Observable.just(comment)
            .delay(3, TimeUnit.SECONDS)
            /*for doing at background*/
            .subscribeOn(Schedulers.io())
            /*for responsing at maint thread*/
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    comment = "";
                    // and other stuffs you wand after resetting the val
                }
            });

A: A good approach(based on you having a thread already) would be this:
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>3000) {

    //reset your variable

    //Allow this to repeat:
    startTime = System.nanoTime();
}

In order to initialize, do startTime = System.nanoTime(); where you would initialize the activity.
Now this method has a big drawback: You have to use it with a thread. It cannot be used alone as a listener if you want it to update after 3 seconds and not after 3 seconds on a button press.
Using a thread is a good idea if you want something done repeatedly, but beware of background memory hogging. You may want to create an async thread

A: A better approach would be to use handlers and postDelayed instead of Thread.sleep().
postDelayed puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper.
Thread.sleep() blocks the thread.
final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do stuff every 3000 ms
        handler.postDelayed(this, 3000);
      }
    }, 1500);


Q: Custom Wix Burn bootstrapper doesn't detect MSI install state I'm creating a custom wizard-style bootstrapper based on Wix/Burn (3.6 release version). I've based in on the Wix 3.6 bootstrapper code.
The problem is that I cannot get the bootstrapper to detect the install state of my setup.msi that is part of the bundle.
As I understand it, all that's required is to call Engine.Detect(), where Engine is an instance of the Wix Engine from the Bootstrapper Application. At that point I should be able to look in Bootstrapper.Command.Action to see what the required launch action is.
My bundle contains two items: .NET 4 (web install) and my setup.msi.
I suspect that I'm missing a step to determine whether I should put my wizard into maintenance mode vs. install mode.

A: First, to determine if the package is being detected or not you can check the log files in the temp directory of the current user. It will tell you whether or not the package has been detected.
Now to determine whether or not to go into maintenance mode vs. install mode, you can check the package state by subscribing to the DetectPackageComplete event. In the example below, my UI uses two properties, InstallEnabled and UninstallEnabled to determine what "mode" to present to the user.
private void OnDetectPackageComplete(object sender, DetectPackageCompleteEventArgs e)
    {
        if (e.PackageId == "DummyInstallationPackageId")
        {
            if (e.State == PackageState.Absent)
                InstallEnabled = true;
            else if (e.State == PackageState.Present)
                UninstallEnabled = true;
        }
    }

The code sample above is from my blog post on the minimum pieces needed to create a Custom WiX Managed Bootstrapper Application.

A: An easy way to determine if your Bundle is already installed is to use the WixBundleInstalled variable. That will be set to non-zero after your Bundle is successfully installed.
Additionally, in WiX v3.7+ the OnDetectBegin callback now tells you if the bundle is installed so you don't have to query the variable normally.
These changes were made to make it easier to detect maintenance mode to avoid the completely reasonable solution that @BryanJ suggested.


Q: Runing a program appears to not work I do not know what the problem is or what happened but when I want to run a program compiled with g++ not working.
I starts like this:
gabi@gabi-work:~/Desktop/comp$ ./a.out

and receive this:
1gabi@gabi-work:~/Desktop/comp$

the problem is?

A: No this is not an error. The script runs and give the output which is "1".  It is added to the same line the Terminal sees, and not making a new line after output through, so it seems like it isn't running.
All you have to do is to add a new line character which is mostly the \n at the end of the output so that you print a new line to the end of the output, so you don't have this behavior.


Q: /etc/sysctl.conf doesn't persist after reboot In a mission to reduce frequent memory flushes to filesystem, I added the following two lines to /etc/syctl.conf.
vm.dirty_background_ratio = 50
vm.dirty_ratio = 80

I then ran, sudo sysctl -p and the changes were in effect right way. Upon a system reboot, however, I still see old values for dirty_ratio and dirty_background_ratio.
new-sys-admin@ThinkPad:~$ sysctl -n vm.dirty_background_ratio
10
new-sys-admin@ThinkPad:~$ sysctl -n vm.dirty_ratio
5

I'm running Ubuntu 12.04.3 LTS 3.2.0-52-generic-pae. After looking at a couple of posts:

*

*Ubuntu way to run sysctl -p on each boot?

*Ubuntu 12.04, why service procps start doesn't start procps?
it looks like the upstart job, /etc/init.d/procps is supposed to run on system boot and reload /etc/sysctl.d/* and /etc/sysctl.conf contents via /etc/init/procup.conf but it doesn't seem like it does.
On the next reboot, I ran service procps start and the changes were in effect. I'm wondering how to make procps run consistently on boot time and if I am missing an additional step in making these changes persistent.
EDIT 1
Also tried having these values in /etc/sysctl.d/10-local.conf as per Bill's suggestion.
new-sys-admin@ThinkPad:~$ cat /etc/sysctl.d/10-local.conf
vm.dirty_background_ratio = 50
vm.dirty_ratio = 80

Upon restart, the values are reverted back.

A: The answer from Gsus above also solved my problem.
/usr/lib/pm-utils/power.d/laptop-mode writes values dirty_ratio=10 dirty_background_ratio=5 writeback_centisecs=500 after sysctl processed the files in /etc/sysctl.d.
But I'm feeling not so comfortable with commenting out a line in a pm script.
Because I am running on a desktop system and being aware that I don't need the dirty_* changes from above, I tried moving /usr/lib/pm-utils/power.d/laptop-mode to another location. The pm utils didn't complain.
So a possiblity would be to divert the file, so that an update of the package won't recreate it.
sudo dpkg-divert --add --rename --divert /usr/lib/pm-utils/power.d/laptop-mode /usr/lib/pm-utils/laptop-mode.diverted

sudo mv /usr/lib/pm-utils/power.d/laptop-mode /usr/lib/pm-utils/laptop-mode.diverted

You should only do this if you want to adapt the parameters dirty_ratio dirty_background_ratio writeback_centisecs manually.
For the power management utils it would be clearer when they created a file in /etc/sysctl.d to better understand what is going on.

A: In /usr/lib/pm-utils/power.d/laptop-mode, comment out the following line in function laptop_mode_ac():
write_values 0 10 5 500

There the values changes to:
dirty_ratio = 10
vm.dirty_background_ratio = 5

then reboot, the values of sysctl must persist.

A: Place your commands in a file under /etc/sysctl.d.  Something like 10-local.conf containing:
vm.dirty_background_ratio = 50
vm.dirty_ratio = 80

If the file stays in place it should be run each time you reboot.


Q: Plotting population density map in R with geom_point I'm working on a simple population density plot of Canada. I have data for population based on postal code and latitude/longitude here
I want to improve the plot to show color change as the density of points increases. This is the code I have:
library(maptools)
library(gdata)
library(RColorBrewer)
library(classInt)
library(maps)
library(ggplot2)
library(ggmap)

Canada <- get_map(location="Canada", zoom=3, maptype="terrain")

ggmap(Canada, extent="normal") + geom_point(data=PopDensity, aes(x=LONG,y=LAT,size=POPULATION),
alpha = 0.3)+scale_size_continuous(range=c(1,6))

which produces a plot like

What I'd really like is a way to keep the data points the same size, but instead of making the points transparent, changing the color as a function of point density.

A: You have to calculate the densities first, then assign the values to the points so you can map that aesthetic:
library(ggplot2)
library(ggthemes)
library(scales)
library(ggmap)
library(MASS)
library(sp)
library(viridis)

pop <- read.csv("~/Dropbox/PopulationDensity.csv", header=TRUE, stringsAsFactors=FALSE)

# get density polygons
dens <- contourLines(
    kde2d(pop$LONG, pop$LAT,
          lims=c(expand_range(range(pop$LONG), add=0.5),
                 expand_range(range(pop$LAT), add=0.5))))

# this will be the color aesthetic mapping
pop$Density <- 0

# density levels go from lowest to highest, so iterate over the
# list of polygons (which are in level order), figure out which
# points are in that polygon and assign the level to them

for (i in 1:length(dens)) {
  tmp <- point.in.polygon(pop$LONG, pop$LAT, dens[[i]]$x, dens[[i]]$y)
  pop$Density[which(tmp==1)] <- dens[[i]]$level
}

Canada <- get_map(location="Canada", zoom=3, maptype="terrain")

gg <- ggmap(Canada, extent="normal")
gg <- gg + geom_point(data=pop, aes(x=LONG, y=LAT, color=Density))
gg <- gg + scale_color_viridis()
gg <- gg + theme_map()
gg <- gg + theme(legend.position="none")
gg


Q: How to open a file and remove certain characters based on args passed from command line So I have a function which will essentially run and generate a report and save it with args.current_date filename. The issue I am having is to remove the extension .json from the filename being saved which really is not readable. Since I am passing dict as args, I cannot use the strip() method in order to do this. So far my function is follows :
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--current-date", action="store", required=False)
parser.add_argument("-p", "--previous-date", action="store", required=False)
args = parser.parse_args()

def custom_report(file_names, previous_data , current_data):
    reporting = open('reports/' + args.current_date+ "-report.txt", "w")
    reporting.write("This is the comparison report between the directories" " " + args.current_date +
                    " " "and" " " + args.previous_date + "\n\n")
    for item in file_names:
        reporting.write(item + compare(previous_data.get(item), current_data.get(item)) + "\n")
    reporting.close()

It has saved the file as '2019-01-13.json-report.txt'. I want to be able to get rid of the '.json' aspect and leave it as '2019-01-13-report.txt'

A: To remove a file name extension, you can use os.path.splitext function:
>>> import os
>>> name = '2019-01-13.json'
>>> os.path.splitext(name)
('2019-01-13', '.json')
>>> os.path.splitext(name)[0]
'2019-01-13'


Q: SCM choice for a new user? Real easy one here guys. Best justification gets the win.
I'm a computer science student at a school you've heard of, and have been programming for several years now (about 8), so I've written a fair few lines of code. But since I've never really been distributing - source or binaries - nor doing team developing (though I'm sure I will!), I've never needed to learn source code management systems. I have a tremendously boring hierarchy of folders along the lines of src/project_name or src/class_code/hw_or_project_name and if I need to send the code to a friend or for grading, it's just a tarball away.
A few things have changed in recent years, as my projects have gotten bigger. My Mac, with Time Machine, now does hourly backups - this has saved me a fair few times, most recently when I made major changes over SSH... then saved and closed the stale copy in my editor a few hours later.
But, out of a sort of professional interest - along with an overwhelming sense that it could be useful - I've decided to learn SCMS. Now, I have plenty of experience as a source code 'consumer' - git clone, svn checkout, cvs co, that sort of thing - but none as a maintainer, committer, or updater.
My question to you is: what should I learn? Now, a bunch of you are screaming "why one? you'll use many!" but I'd like to learn the basics of SCM, and get in the habits of actually using it, on the most straightforward system. There are a number of concepts I'd do well to internalize - branches, tags, merging, collaboration, etc - before I really need them.
To be clear, I'm no Linus Torvalds. I will be mantaining one, or perhaps a few branches. On my dozens of files, I don't mind if some operations take a few hundred ms more on one system than on others.
Now what do I have? I do have a webhost. They offer Subversion hosting a click away, or I could store other repositories there no problem. For reasons I can't explain, I'm rather partial to Subversion. But that's exactly why I'm reluctant to just jump in. I know Mercurial, Git, and so forth are the hot new things, being distributed, but I'm not sure why this is a benefit. In fact, I'm not quite sure how it could work.
So, what should I start with? Subversion or Git? Mercurial or CVS? Visual Source Safe or Perforce? (that last pair was a joke) And why one over the other?
Thanks for your time, and if this in the wrong section I apologize.
EDIT Thanks all! I appreciate your comments. Given the choice between Git and Hg, I'd probably go with Git - any disagreement? Second, why not Subversion? It seems to be the consensus (not just here) that it's old or otherwise obsolete. Why's that?
EDIT 2 So after reading all the responses and doing some more reading, I've decided to go with Git. "Answer" goes to the best justification, as stated above. Git seems to be more popular than Mercurial, even if it is a bit less clean. I'm pushing changes to my webserver, where I have viewgit installed, and it's working great. The impetus for storing a copy on my webserver is that I'd like to be working from several of my machines, and I expect them to get out of sync. I also expect to have the several working copies out of sync with each other and my server, and I now understand that Subversion is pretty weak at that. There's a lot I'm still trying to work out, but I've got it set up now so that I can pull/clone from http and push over ssh (next step is to set up Gitosis). To a newbie looking to do what I'm doing - you'll find that your "push" commands will work the first time, but any "cloned" copies won't track the changes you make. Git considers this a safety feature... I only slightly understand why, but it has to do with merging. The trick is to use this post-update hook on the server to merge the newly-pushed copy into the server's working copy.

A: The Mercurial over subversion case is pretty convincingly made in the first section at http://hginit.com/
Git and Mercurial can each read and write one another's repos over the wire now, so it really comes down to whichever interface you prefer.

A: One thing's for sure, don't start with CVS.

A: I've been using Mercurial and enjoy it very much.  You can get a free Bitbucket account and start storing your repos in the cloud.  It's also being used on some codeplex projects if you ever have the desire/opportunity to work on an OSS project that's on codeplex.
The basic gist I have found/heard is Mercurial is a little easier to work with but not as powerful as Git.  However, both are excellent choices.
There's a really good free video on tekpub for Mercurial and Codeplex.  It takes you through all the basics.
As already mentioned the http://hginit.com link is another good resource.  It's also made by the same team who made FogBugz & Kiln.  Kiln is an integrated environment for Mercurial and FogBugz with extras like code review.
I was using SVN on my local box to store my personal work but no more.  With Bitbucket & Mercurial I won't have to worry about my local box dying and making sure I had everything backed up....
Bottom line is you can't go wrong with either Hg or Git but I would go with Hg unless you needed some of the advanced features which sounds like you don't.
Learning SVN isn't necessarily bad as there are a lot of Organizations using it but I would really concentrate on Distributed VCS instead.  They really are the future. :-)

A:
Given the choice between Git and Hg, I'd probably go with Git - any disagreement?

Warning, I'm a mercurial fanboy.
Git is not bad, but it has some quirks you have to know when you use it:

*

*You can push into a non-bare git repo, but this will screw up the working copy there (It moves the branch HEAD to the pushed revision, but does not update the working copy. When you are not aware of this push, the next commit will undo the changes which were pushed into the repo, mixed with the changes you just introduced.). In hg a push to a non-bare repo just add the new history to the repo, and you get a new head on your next commit, which you then can merge with the pushed head.

*You can't easily switch between a bare and a non-bare repo (you can make a hg repo bare with hg up -r null, and get a working copy with hg up [some-revision] from a bare one).

*When you check out an older revision by a tag, remote branch name or commit-hash you get a detached head (I really like the title of that question). This means commits there are on no branch, and can get removed by the garbage collector. In hg a commit on an old state create a permanently stored anonymous head (You get a warning on the commit).

*When you come from SVN you have to know that git revert and svn revert do completely different things.

*Git has all features enabled, also the ones which can cause data loss (rebase, reset). In hg these features are there, but must be enabled prior use.

*git tag makes local tags by default, when you want a globally visible tag you need git tag -a or git tag -s. On the opposite hg tag creates a global visible tag, local tags are created with hg tag -l.

Some things many don't like about mercurial:

*

*Branches are stored permanent in the project history, for git-like local branches bookmarks can be  used

*There are no git-like remote tracking branches (although bookmarks can be shared, and recently there's been work on them to work more like git's branch labels)

*Creating a tag creates a new commit in the project history (technically git does it the same way, but is much better at hiding this commit)

*You have to enable features that modify history, or are experimental (hg comes pre-packed with many, ... but they are disabled by default). This is why many think that mercurial has less features than git.

*There is no git rebase -i equivalent packaged with mercurial, you have to get the third-party histedit extension yourself.

Second, why not Subversion? It seems to be the consensus (not just here) that it's old or otherwise obsolete. Why's that?

Svn has no clue what a branch or a tag is, it only know copies. Branches and tags are simulated by having the convention that a svn repo contains a trunk/, branches/ and tags/ folder, but for svn they are only folders.
Merging was a pain in svn, because older versions (prior svn 1.5) dit not track the merge history. Since svn1.5 subversion can track merge history, but I don't know if the merging part is better now.
Another thing is that in svn every file and folder has it's own version number. In git and hg there is one version for the entire directory structure. This means that in svn you can check out an old revision an one file, and svn will say that there are no local changes in your working copy. When you check out an old revision of one file in git or hg, both tools will say your working copy is dirty, because the tree is not equal to their stored tree. With subversion you can get a Frankenstein version of your sources, without even knowing it.
A minor nastiness in svn is that it places a .svn folder in every checked out folder (I heard rumors that they want to change this behavior in 1.7), where the clean reference files for the checked out ones live. This makes tools like grep -r foo not only list the real source files, but also files from these .svn folders.
Svn has an advantage when you have big or unrelated projects, since you can check out only subtrees of a repository, while in git and hg you can get only the whole tree at once. Also does svn support locking, which is an interesting feature if you have files which can't easily be merged.
Keyword substitution is also supported by svn, but I wouldn't call this a feature.

A: I'd pick mercurial.

*

*The set of commands are limited so there's not a lot to remember.

*http://www.hginit.com

*Mercurial's hg serve command lets you setup a repo server for small operations in 5 seconds.

*Cross platform

*You can use it locally, without branches and be quite successful until you want to get deeper into the advanced stuff.

A: Being a newbie myself , I've used git and found it remarkably easy to use and intuitive, while the others have been a bit too overwhelming.Coupled with GitHub it makes for a wonderful little tool for source control,sharing and backing up code.

A: The best open-source choice is GIT. Check Git documentation. you Would also find lots of tutos over internet (youtube, and some developers blogs). A must not do is (start using CVS or Subsversion). Well at least is my personal opinion.

A: Use git and github

Once upon a time, cvs almost completely replaced its competition and ruled the world of version control.
Then it was itself replaced by svn.
And now, svn is being replaced by git.
Git is more complex than svn, so there might still be reasons to pick svn for a new project.
But its days are numbered. Git, Mercurial, and some proprietary systems are clearly the future of the VCS world.
Both git and svn can be used in a cvs-like checkout/pull/commit mode, so the bottomless pit of complexity (it's a lifestyle) that is git won't affect you unless you jump in the deep end.


Q: is it possible to give margin-left css/scss dynamically to its Childs element on the basics of position (nth + 2px) I have a form which show Package Hierarchy, Package Input depend on package type so is it possible to give margin-left dynamically by css/sass to its Childs element on the basics of position
enter code here

     child one

     child two

     child one

     child two

     child three

child may differ by type so feel unsuitable to give static :nth-child() css

A: You can do this with sass. You just need to take maximum amount of Childs into $elements.

     child one

     child two

     child three


Q: Python recursive function to dump a tree in Excel I have a very simple directed traversal graph structure in a Django models.py file that translates into the following two Python classes :
class Node(models.Model):
    position = models.IntegerField() # from 1 to 3
    name = models.CharField(max_length=255)
    value = models.FloatField(default=0.0)

class Edge(models.Model):
    source = models.ForeignKey("Node", related_name="__to")
    destination = models.ForeignKey("Node", related_name="__from")
    weight = models.FloatField(default=0.0)

I need to dump the content of that tree into an Excel file. Writing to the Excel document is easy thanks to xlwt - I can write to any cell using a simple write(x, y, content) function - but I what I'm having difficulties with right now is to go through the entire tree (recursively) and fetching each possible path to write in the Excel file.
Considering I have 3 nodes (A1, A2, A3) in the first position that are each one linked to one node (B1) in the second position which is finally linked to 1 node (C1) in third position, I would need to go through all possible paths and translate that into the following structure in Excel ( is for your understanding but it's actually a separate cell in Excel) :
Node A1 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3
Node A2 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3
Node A3 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3

In the aforementioned example, I have 5 instances of Node, and 5 instances of Edge.
In any idea on how I could do that?
Thanks!
J

A: Strictly speaking, this is a directed graph traversal not a directed tree.
A simple algorithm, that ignores the edges but based on position, and gives the expect output is:
>>> positions = [Node.objects.filter(position=i) for i in range(1,3+1)]
>>> import itertools
>>> list(itertools.product(positions))

[(<Node: A1>, <Node: B1>, <Node: C1>),
 (<Node: A2>, <Node: B1>, <Node: C1>),
 (<Node: A3>, <Node: B1>, <Node: C1>)]


Q: Is there any protocol that all Swift SIMD float types conform to? Most of the Swift SIMD float types have +-*/ operators, so we can just calculator the sum like below:

import simd

float2(2.0) + float2(2.0) // float2(4.0, 4.0)
float4(2.0) + float4(2.0) // float4(4.0, 4.0, 4.0, 4.0)

Now, Lets say I have a generic function that takes a pair of float2, float3 or float4 as arguments and returns the sum of them:

func calculateSum<T: SomeProtocolCoversThoseFloats>(a: T, b: T) -> {
    return a + b
}

Is there any protocol that functions like this "SomeProtocolCoversThoseFloats" or is there any way that I can create such a protocol?

A: David is going the right direction, such a protocol doesn't exist (simd is from C and C doesn't have protocols, no surprise), but you can just declare one yourself. To make it so you can use +-*/, you have to add them to the protocol:
import simd

protocol ArithmeticType {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
}

extension float4 : ArithmeticType {}
extension float3 : ArithmeticType {}
extension float2 : ArithmeticType {}

func sum<T: ArithmeticType>(a: T, b: T) -> T {
    return a + b
}

You can also extend Double, Float, Int, etc. if you need to

A: If there isn't (and there doesn't appear to be), it's easy enough to add your own:
protocol SimdFloat {}

extension float2 : SimdFloat {}
extension float3 : SimdFloat {}
extension float4 : SimdFloat {}

This doesn't really directly solve your problem, however as it doesn't declare that two SimdFloat's implement +.


Q: Open simple JQM dialog from codebehind I'm using the dialog script for JQM 1.0 below.
It Works fine, but I want to open it from asp.net codebehind
on page_load. How could I accomplish that?
Something like, but I can't make it work:
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "open", "opendialog", True)

// The JS:

Open Dialog

A: Assuming the JavaScript in your example is already in the HTML, in your code behind just use
RegisterStartupScript (http://msdn.microsoft.com/en-us/library/bb310408.aspx) to fire the button click:
  Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
  sb.Append("")

  If (Not ClientScript.IsStartupScriptRegistered("open")) Then
        ClientScript.RegisterStartupScript(Me.GetType(), "open", sb.ToString())
  End If

Here is a discussion onRegisterStartupScript vs RegisterClientScriptBlock: Difference between RegisterStartupScript and RegisterClientScriptBlock?


Q: Using MAYA 3D Model in a .Net application If I want to render a 3D model created by Maya and do some animation with it in a .net application what should be my choice of platform - plain WPF or XNA?

A: XNA is an interesting platform, but I have noticed it having some performance issues when loading in models.  I have not used WPF to do this, but XNA does also require installing of its framework, to run the application.  I suggest you avoid it, for the hurdles you must jump to get what you want out of it.  DirectX libraries are a good way to accomplish this, there are thousands of examples of this being used out there. Very Good,Good, Ok
You can also use a .X exporter for Maya to import your models. Something like this DirectX Maya Exporter


Q: Frege's argument for the existence of abstract mathematical objects I have some trouble understanding Freges argument in particular as presented here, https://stanford.library.sydney.edu.au/entries/platonism-mathematics/#FreArgForExi
In particular the first premise i.e
"The singular terms of the language of mathematics purport to refer to mathematical objects, and its first-order quantifiers purport to range over such objects"
If we refer to our language how is then the object that we introduce independent of us as the "intelligent" agents, which Platonism suggests it should be?

A: You would do better to actually read Frege's writing and then decide if an explanation that admits to misrepresentation should even be given credence.
First of all, Frege's definition of zero is obtained by an application of ths principle of indiscernibility for non-existents from negative free logic. So, it is not even correct to compare it with the semantics of first-order logic. If, in Frege's account, a singular term does not denote, the formula containing it is simply false. In particular, reflexive identity statements can be false.
Frege's reasoning is in no way reflected in the claims of the link. He contrasts his extensional view of logic with the intensional logicians of his day. Here, extension and intension refer to the converse orders of the Aristotelian term hierarchy. Logic as inherited from Leibniz inverted this order, and, a focus on syntactic structure with the rise of formalism meant that logic had been moving away from Aristotelian notions of substance. Frege objected to formalism. Moreover, when he retracted his logicism, he chose to advocate for a geometric foundation for all of mathematics.
Frege's notion of truth depended upon the distinction between a concept (intensional) and the extension of a concept (extensional)(importantly, note the definite article in "the extension of a concept"). The importance of singular terms is grounded in Aristotle's distinction between "primary substance" and "secondary substance". Only individuals are primary substances. Species and genera are secondary substances.
With exception for his zero object, Frege's account of number was metaphysical. Truth was to be substantiated by the existents -- that is, primary substances -- which would "fall under a concept".  Defined as a class whose only possible members could be fictional or self-contradictory, the zero object could be declared meaningful even if it was not substantive. In turn, it could be proven to be unique. Consequently, it became the ground for showing that the class of individuals is not vacuous. From that point, Frege used the inclusive disjunction to implement the logicist successor function.
This last item, namely the use of inclusive disjunction, had been one of Russell's criticsms of formalism. Other than claiming the "obviousness" of succession, as Skolem had done, formalism has no justification for its account.
It is important to acknowledge the role of definite description in Frege's account. Imparting singularity, the definite article conveys that extensions of concepts are well-construed individuals. Russell offered an alternate interpretation because Frege's semantics would identify non-existents with one another. Yet, the principle of indiscernibility of non-existents is widely accepted as a well-formedness condition today.
Look at how Moschovakis deals with undefined terms in his paper on formal recursion theory. Less explicitly, Shoenfield describes a relation admitting undefined terms ss arguments in his account of recursion theory. And the purpose of that relation is to identify non-existents with one another just as Frege's semantics had done.
On the other hand, the interpretation of Russell's paradox, as a problem to be addressed through the limitation of size, undermined the idea that definite description could actually govern the nature of sigularity. One cannot form Fregean number classes in Zermelo-Fraenkel set theory.
Meanwhile, definite descriptions rely upon a grammatical form of the principle of identity of indiscernibles. Historical views of the intensional logicians holding that singularity ought be understood in relation to proper names began to be reasserted. In addition, Hilbert and Bernays showed how definite  descriptions could be eliminated under a common presupposition concerning the syntactic structure of definitions (to my knowledge, only Padoa correctly portrays the "non-creativity" as an assumption that can be rejected). So, the Fregean tactic has suffered a great deal of disrepute.
Then again, the homotopy type theory advocates claim to be rediscovering Frege.
If you look into these matters carefully enough, you will find that these people have been doing little more than arguing in circles for centuries. Max Black wrote a paper in which the antagonist against the principle of identity of indiscernibles uses spatial intuition to describe a symmetric universe. Kant used spatial intuition as the basis for his criticism in "Critique of Pure Reason". And, Strawson uses spatial intuition to differentiate between the qualitative identity one obtains from logic and numerical identity one obtains from geometric arrangements.
Good luck with your studies.

A: First comment : here "platonic" must be understood in a broad sense, because Plato asserted the "real" existence of non-sensible objects : the Forms (or Ideas).
Frege has been defined a "platonist" because he asserted that numbers are real non-sensible objects, i.e. abstract objects.
Having said that, "singular terms" are "names" for numbers : zero, one, two, etc. According to Frege, they are real names, denoting objects : the natural numbers.
Thus, the quantifier of a formula like $∀n(n ≥ 0)$ must be interpreted - using the now standard semantics for first-order languge - as ranging over a domain of objects. These objects are the numbers.
But Plato's Forms are more than "abstract objects" :

These Forms are the essences of various objects: they are that without which a thing would not be the kind of thing it is.
A Form is aspatial (transcendent to space) and atemporal (transcendent to time). They are non-physical, but they are not in the mind. Forms are extra-mental (i.e. real in the strictest sense of the word).
The Forms are perfect and unchanging representations of objects and qualities. For example the Form of beauty or the Form of a triangle.

Some of these characteristics of platonic Forms can be predicated also of numbers, but not all of them.

A: You are welcome.
Let me try to give you something more immediate to your question.
When we begin our studies of "mathematical logic" we have a naive appreciation for the nature of truth that is conflated with our personal beliefs. We talk of "truth" and "falsity", we represent "truth" and "falsity", we formulate a logical algebra with which we investigate proof structure, and we find that we must differentiate between material consequence and logical consequence precisely because of our interest in a logical algebra to be used in a logical calculus.
Where have we actually discussed what we mean by truth?
There are a multiplicity of theories of truth. The two which are most relevant here are the correspondence theory and the coherence theory.  A majority of philosophers will discount the coherence theory because it can only have a relationship with material reality by sheer luck.
There are also conceptions of truth. Tarski proposed the semantic conception of truth. The analytic conception of truth probably originates with Kant. It holds that the truth of a statement depends upon the meaning of its words. There is also an epistemic conception of truth. This is closely related to the typical mathematical practice of proving that a definition is non-vacuous. When it involves singular terms, it also involves a uniqueness proof.
You are questioning how one surmises existence of an object by merely using a singular term purporting to denote it. By virtue of its quantifier rules, first-order logic is a logic with existential import. If you accept the logic, you are bound to its presupposition. Free logics are different in this regard, and, Frege's use of the indiscernibility of non-existents had been intended as a well-formedness condition providing for the substantive denotation of his terms.
Now, all instances of reflexive identity are true in an analytic conception of truth. It is assumed that the two occurrences of syntactically identical symbols have uniform denotation (if they denote at all). This is why formalists find the possibility of a false reflexive identity statement confusing. Yet, a semantic conception of truth insists upon the substantive denotation of singular terms in true statements.
Tyler Burge, for one, has held that Tarski's semantic conception of truth clearly justifies the idea of false reflexive identity statements under a correspondence theory of truth.  Within mathematical contexts, examine the transitivity axiom from Tarski's cylindric algebras. It has the effect of binding identity statements with the existential quantifier. In particular, reflexive identity statements only hold for existents.
Philosophers and symbolic logicians will have a problem with Tarski's axiom from cylindric algebra. It would, in effect, be an existence predicate and philosophers are taught to reject such things. Symbolic logicians will object to the fact that it has an infinite expansion relative to self substitutions into the definiens.  But, again, in mathematical contexts, this seems closely related to the model-theoretic investigation of identity in the presence of apartness done by Statman and van Dalen and the proof-theoretic investigation of the same by Borretti and Negri.
Writing before the more modern developments of free logics and cylindric algebras, Abraham Robinson wrote the paper, "On Constrained Denotation." Its principal motivation had been the description of a language given through the formulation of definite descriptions. One simply cannot use a model-theoretic identity relation because the identity relation is essentially constructed as terms are introduced. From this, one may surmise that an epistemic conception of truth is a constructive methodology. Using ideas from free logic makes the epistemic conception more understandable. But the first-order logician who insists upon an extra-logical stipulation of the domain will find it unpalatable.
Now we can compare the correspondence theory and the coherence theory.
Our naive intuition is correspondence. In a sealed room with one chair we say "the chair", using the definite article referentially. In a restaurant we might invoke the ostensive language act of pointing to a table while uttering "that table." But if we apply a correspondence theory of truth to mathematical objects, we seem committed to the existence of mathematical objects without any ability to produce such an existent. To a large extent, we reach this point because of commonly held beliefs concerning a relationship between mathematics and material reality.
This is why I began by pointing out how we begin our studies with the conflation of truth with belief.
Kant had probably been the first to propose a coherence theory of truth, although there had been no vocabulary to express it as such at the time. He had not been trying to delineate "mathematics". He had been responding to Hume's modern account of skepticism. The argument applies to any correspondence theory of truth intended to make claims about material reality.  By relegating mathematics to "intuition" Kant had been trying to provide a basis for "objective knowledge" in contrast with claims of "absolute knowledge" (correspondence with material reality).
Not surprisingly, philosophers -- especially analytic philosophers  -- took issue with this. Frege's logical studies arise in this context. Hence one sees the motivation behind his emphasis on truth and his emphasis on extensionality.
Ultimately, these are waters you must navigate for yourself. I find the argument that mathematical objects exist because science is useful to be analogous with the argument that God exists because prayer has efficacy. To be skeptical of the latter without being skeptical of the former is incoherent in my view.


Q: Login script registers in database but I can't login (PHP &MYSQL in easy steps, Mike Mcgrath) The script has 5 pages.  Registration, Login, Login tools,Login action and Home. PHPMYADMIN registers the registration form but the login page keeps saying "enter your email" even though it is entered and matching the registered user in the database. Can anyone see what is wrong. This script is copied from the book cited above.(I will post the script for the three function pages)
/////////////////////////////////////////login.php  (page1)////////////////////////////////////////

if (isset($errors) &&!empty($errors))
{
echo'
oops! there was a problem:
';
foreach ($errors as $msg)
{
echo"-$msg
";
}
echo'please try again or Register
';
}
?>

Login

<form action ="login_action.php" method ="POST">

EMAIL ADDRESS:<input type="text" name="email">

password<input type="password" name ="pwd">

<input type="submit" value ="login">

</form>
<?php include ('includes/footer.html');?>

//////////////////////////////////login-action.php  (page2)/////////////////////////////////////

require ('../connect_db.php');
require('login_tools.php');

list($check, $data)=
validate($dbc, $_POST['email'] ,$_POST['pass']);

if($check)
{
session_start();

$_SESSION['user_id']=$data['user_id'];
$_SESSION['first_name']=$data['first_name'];
$_SESSION['last_name']=$data['last_name'];

load('home.php');
}
else{$errors =$data;}

mysqli_close($dbc);

}
include('login.php');

?>

//////////////////////////////login_tools.php  (page3)/////////////////////////////////////////

function load($page='login.php')
{
#statements to be inserted here.

$url ='http://' . $_SERVER['HTTP_HOST']. dirname($_SERVER['PHP_SELF']);

$url = rtrim($url,'/\\');
$url .= '/'.$page;

header("Location:$home.php");
exit();
}

function validate($dbc, $email = '', $pwd = '')
{
#statements to be added here

$errors=array();
if(empty($email))
{$errors[] ="Enter your email address";}
else
{ $e = mysqli_real_escape_string($dbc, trim($email));}

if (empty($pwd))
{ $errors[]= "enter your password.";}
else
{$p = mysqli_real_escape_string($dbc, trim($pwd));}

if (empty($errors))
{
$q = "SELECT user_id, first_name, last_name
FROM users
WHERE email = '$e'
AND pass = SHA1('$p')";

$r= mysqli_query($dbc,$q);

if(mysqli_num_rows($r) == 1)
{
$row=mysqli_fetch_array($r,MYSQLI_ASSOC);
return array(true,$row);
}
else
{$errors[]='email address and passwprd not found';}
}
return array(false,$errors);
}
?>

/////////////////////////////////////////////////////////////////////////////////////////////////


Q: Запрет ввода символов в Linux консоле на C++ как можно запретить ввод букв внутри терминала? Жмем клавишу, программа сразу отрабатывает, понимает, что это буква и ничего не происходит. Жмем на цифру, появляется в строке ввода цифра.

A: Придумал только так... Выглядит страшно, но работает так как хотел. Есть ошибка когда число слишком большое.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;

int RotateNumber(int number) {
   std::ostringstream output_stream;
   int result;
   output_stream << number;
   std::string str_number = output_stream.str();
   std::reverse(str_number.begin(),str_number.end());
   std::istringstream input_stream(str_number, std::istringstream::in);
   input_stream >> result;
   return result;
}
int main()
{
   char c;
   int temp;
   int tempp = 1;
   int end = 0;
   struct termios tty, savetty;
while (true){
   fflush(stdout);
   tcgetattr(0, &tty);
   savetty = tty;
   tty.c_lflag &= ~(ISIG | ICANON);
   tty.c_cc[VMIN] = 1;
   tcsetattr(0, TCSAFLUSH, &tty);
   read(0, &c, 1);
   tcsetattr(0, TCSANOW, &savetty);
   if ( c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9')
   {
        temp = c - '0';
        end += temp * tempp;
        tempp *= 10;
   }
   else
   {
        system("clear");
        cout << RotateNumber(end);
   }
}
   return 0;
}


Q: FirebaseApp is not initialized on real devices Please advice, I'm trying to add push notifications in PCL Xamarin.Forms.
On emulator Genymotion it's work fine but on real devices i have an error:
Default FirebaseApp is not initialized.Make shure to call FirebaseApp.initializeApp(Context)
google-services.json is present in Android project with GoogleServicesJson BuildAction
My MainActivity:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            internal static MainActivity Instance { get; private set; }
            internal static FirebaseInstanceId FirebaseInstance { get; private set; }

            public static int CurrentUserId { get; set; }
            protected override async void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;

                VideoViewRenderer.Init();
                global::Xamarin.Forms.Forms.Init(this, bundle);
                string dbPath = FileAccessHelper.GetLocalFilePath("LocalDataBase.db");

                LoadApplication(new App());

                Xamarin.Forms.Application.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
                UserDialogs.Init(this);
                CachedImageRenderer.Init();

            //on real devices it return  null
                var app = Firebase.FirebaseApp.InitializeApp(this.ApplicationContext);

                Instance = this;
            }

A: Problem solved after downgrade NuGet package version Xamarin.Firebase.Messaging and Xamarin.GooglePlayServices.Base to 42.1001.0

A: My solution was the other way round, I did not have Xamarin.Firebase.Messaging installed at first. But after installing it from Nuget, it works.


Q: Insert faker data via knex I want to insert data via knex using a for look to create an object to insert data.
I tried the following:
const faker = require('faker');
const dataLength = 10
const obj = []

exports.seed = function (knex, Promise) {
  // Deletes ALL existing entries
  return knex('posts').del()
    .then(function () {
      //create entries
      for (var index = 0; index < dataLength; index++) {
        obj[index] = {
          title: faker.lorem.sentence(),
          description: faker.lorem.paragraph(),
          createdAt: faker.date.recent(),
          updatedAt: faker.date.recent(),
          deletedAt: faker.date.recent(),
          deleted: faker.random.boolean(),
          tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"])
        }
        knex('posts').insert([,
          obj[index]
        ]);
      }
      // Inserts seed entries
      return
    });
};

My problem is that no data get saved to the db.
Any suggestions what I am doing wrong here?

A: Your call to knex.insert() returns a promise. You need to include this promise in the promise chain by returning it inside the handler you pass to the then method. By returning a promise inside the then handler, you are effectively telling it to wait for that promise to resolve. Because you are returning nothing (specifically, undefined), your seed function deletes the posts but does not need to know it has to wait for any other operations to finish before completing.
In the future, if you had multiple promises to return, you could use Promise.all() to return all of them:
exports.seed = function (knex, Promise) {
  return knex('posts').del()
    .then(function () {
      return Promise.all([
        knex('bar').insert(),
        knex('foo').insert(),
      ])
    })
};

Then your promise chain would wait for all the promises inside Promise.all() to resolve before continuing.
In this particular case, however, there's no need to call knex.insert() multiple times because it can accept an array of objects instead of a single object:
exports.seed = function (knex, Promise) {
  return knex('posts').del()
    .then(function () {
      const posts = []
      for (let index = 0; index < dataLength; index++) {
        posts.push({
          title: faker.lorem.sentence(),
          description: faker.lorem.paragraph(),
          createdAt: faker.date.recent(),
          updatedAt: faker.date.recent(),
          deletedAt: faker.date.recent(),
          deleted: faker.random.boolean(),
          tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"])
        })
      }
      return knex('posts').insert(posts)
    });
};


Q: Python version shipping with Mac OS X Snow Leopard? I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")
Thanks!

A: bot:nasuni jesse$ python
Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Probably the biggest reason I went and upgraded this morning, it's not 2.6.2, but it's close enough.

A: Python 2.6.1
(according to the web)
Really good to know :)

A: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html

A: It ships with both python 2.6.1 and 2.5.4.

$ python2.5
Python 2.5.4 (r254:67916, Jul  7 2009, 23:51:24)
$ python
Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)

A: You can get an installer for 2.6.2 from python.org, no reason to go without.


Q: Extrema of $f(x,y) = xy\sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}$ From Demidovich

Find the extrema of the function of $z = xy \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}$

What I've done so far:
I've make $z_{x}'= 0$ and $z_{y}' = 0$, wich gives me:
$$\frac{\partial z}{\partial x} = y \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}} - \frac{yx}{a^2 \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}} = 0$$
$$\frac{\partial z}{\partial y} = x \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}} - \frac{yx}{b^2 \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}} = 0$$
And I've tried to simplify, and I got:
$$\frac{y a^2 (1 - \frac{x^2}{a^2} - \frac{y^2}{b^2} ) - xy}{a^2 \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}} = 0$$
$$\frac{x b^2 (1 - \frac{x^2}{a^2} - \frac{y^2}{b^2} ) - xy}{b^2 \sqrt{1 - \frac{x^2}{a^2} - \frac{y^2}{b^2}}} = 0$$
Now the problem is, some cubic terms appear and I don't know how to solve this and find the critical points to proceed with the exercise. Of course the denominator cannot be zero, so my system is composed only by the numerators.
I'm pretty sure I'm doing something wrong, 'cause this seems too much trouble for an introductory exercise (it's one of the firsts in the chapter)

A: I suppose that $a,b>0$ are given parameters. The given function is then defined in the region
$$
R = \left\{\ (x,y)\ :\ \frac {x^2}{a^2}+ \frac {y^2}{b^2}\le 1\ \right\}\ .
$$
The four quadrants $I, II, \dots$ are cutting $R$ in four pieces, $R_I$, $R_{II}$, ... and it is enough to search for the local / global maxima on the piece $R_I$.
On the boundary of $R_I$ (and of $R$) the given function vanishes.
The (local/global) maximal values of the function $f$ on $R_I$ correspond to the (local/global) maximal values of $f^2/(a^2b^2)$, which is a function of $X=x^2/a^2$, $Y=y^2/b^2$, explicitly given by the help function
$$
h(X,Y)=XY\left(1-X-Y\right)=XY-X^2Y-XY^2\ ,
$$
the corresponding region for $(X,Y)$ is a triangle given by $X,Y,1-X-Y\ge 0$. At the boundary the values are zero. Differentiation gives the system of equations for a local extremal point:
$$
\left\{
\begin{aligned}
Y&= 2XY +Y^2\ ,\\
X&= 2XY +X^2\ ,
\end{aligned}
\right.
$$
and subtraction gives $Y-X=Y^2-X^2=(Y-X)(Y+X)$. We have thus either $X=Y$, or $X+Y=1$.

*

*in case of $X=Y$ the common value is $0$ or $1/3$.

*in case of $X+Y=1$ adding the equations we get $1=X+Y=4XY+X^2+Y^2=2XY+1^2$, so $XY=0$, a boundary point.

So we keep only $(X,Y)=(1/3,\;1/3)$.

A: With the polar coordinates $\frac xa = r\cos t$ and $\frac yb  =r \sin t$,
$$z=\frac12ab r^2\sin 2t \sqrt{1-r^2}$$
For any given $r\le 1$,
$$|z(r)|\le \frac12abr^2 \sqrt{1-r^2}$$
Then, set $(r^2 \sqrt{1-r^2})'=0$ to locate the extreme at $r^2=\frac23$. Thus,
$$-\frac{ab}{3\sqrt3}\le z \le \frac{ab}{3\sqrt3}$$


Q: Getting 500 | Internal Server Error when using getServerSideProps in NextJS after deploying in Vercel I'm using server rendered pages in NextJS using getServerSideProps. It's in index.js (root page).
When I'm making build locally, website working fine. But when i'm hosting this site in Vercel, it's showing 500 | Internal Server error.
export async function getServerSideProps(context) {
  let params = context.query;

  const job_col = await collection(db, "job_list");
  const job_snap = await getDocs(job_col);
  let jobData = job_snap.docs.map((doc) => ({
    ...doc.data(),
    id: doc.id,
  }));

  return {
    props: {
      jobs: jobData,
      params
    },
  };
}

A: It's because of the large payload. Move the large payload code portion to the client-side(useEffect) and it will be resolved.

A: I had the same issue. But when I changed getserversideprops to getstaticprops it worked.


Q: Google Sheets pivot data with multiple values I'm trying to display sample data as follows. I'm able to do this using pivot tables and multiple values with no problem but would like to find a way using either Query or some other method. This problem was partly solved using the formula below but does not include the 'Other' column.
=Index({"",Transpose(Unique(Filter(B2:B,B2:B<>"")));Flatten({Sort(Unique(C2:C)),IFError(Unique(C2:C)/0)}),IFNA(VLookup(Transpose(Unique(Filter(B2:B,B2:B<>"")))&Flatten({Text(Sort(Unique(C2:C)),"hh:mm"),Text(Sort(Unique(C2:C)),"hh:mm")&".1"}),{Flatten({B2:B&Text(C2:C,"hh:mm"),B2:B&Text(C2:C,"hh:mm")&".1"}),Flatten({A2:A,D2:D})},2,0))})

Sample data:

Desired result:

A: use:
=ARRAYFORMULA({"", TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")));
 FLATTEN({SORT(UNIQUE(C2:C)), IFERROR(TEXT(UNIQUE(C2:C), {"@", "@"})/0)}),
 IFNA(VLOOKUP(TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")))&FLATTEN({TEXT(SORT(UNIQUE(C2:C)), "hh:mm"),
 TEXT(SORT(Unique(C2:C)), "hh:mm")&{".1", ".2"}}), {FLATTEN({B2:B&TEXT(C2:C, "hh:mm"),
 B2:B&TEXT(C2:C, "hh:mm")&{".1", ".2"}}), FLATTEN({A2:A, D2:D, E2:E})}, 2, ))})


Q: phpThumb creating corrupted/oversized thumbnails I'm having a very strange problem with the phpThumb library, for some reason when the thumbnails are generated they are being created very large in size (550k for a 150x65 image) and in many cases do not load at all. I have narrowed the issue down to the phpThumb library but I am unsure of what the actual problem is. Here is an example of one of the images: http://www.justsunnies.com.au/image/product/small/nitro_cr-c.jpg
Any help would be much appreciated as I am at my wits end as to why this problem is occurring.
Thanks

A: you can use timthumb.php if would like
<img src="<?php echo path/to/timthumb.php?src="path"&h=100&w=100&q=500 ?>"/>


Q: How to load image to imageview with url without downloading image I'm trying to load following image link to imageview. https://pbs.twimg.com/profile_banners/169252109/1422362966
Can't it problem to image size to load imageview ?
activity_profile.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/container_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <include
                    android:id="@+id/toolbar"
                    layout="@layout/toolbar" />
            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="140dp"
                android:layout_alignParentTop="true"
                android:background="@color/background_material_dark">

                <ImageView
                    android:id="@id/profile_banner"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerInParent="true"
                    android:scaleType="centerCrop"
                    />

                <ImageView
                    android:layout_width="70dp"
                    android:layout_height="70dp"
                    android:scaleType="fitCenter"
                    android:layout_centerInParent="true" />

            </RelativeLayout>

        </LinearLayout>

        <fragment
            android:id="@+id/fragment_navigation_drawer"
            android:layout_width="@dimen/nav_drawer_width"
            android:name="activity.FragmentDrawer"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"
            tools:layout="@layout/fragment_navigation_drawer" />

    </android.support.v4.widget.DrawerLayout

ActivityProfile.java
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);

        final ImageView imgView =(ImageView)findViewById(R.id.profile_banner);

        TwitterSession session = Twitter.getSessionManager().getActiveSession();

        final long userID = session.getUserId();

        MyTwitterApiClients apiclients = new MyTwitterApiClients(session);

        final Bitmap bmp = null;

        apiclients.getProfileBannerService().show(userID, null, new Callback<User>() {
            @Override
            public void success(Result<User> result) {

                String imageUrl = result.data.profileBannerUrl;
                URL url = null;
                Bitmap bmp = null;
                try {
                    url = new URL(imageUrl);
                    bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());

                    imgView.setImageBitmap(bmp);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

App stops working at this line bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
What's my wrong ?

A: Why don't you try Picasso?
It's as simple as this:
Picasso
    .with(context)
    .load("https://pbs.twimg.com/profile_banners/169252109/1422362966")
    .into(imgView);

And, you can also transform the Bitmap, applying tint, resizing to prevent memory issues, all that stuff.


Q: Inverse of cosh(x) My goal is to find the inverse of $y=\cosh(x)$
Therefore:
$$x=\cosh(y)=\frac{e^y+e^{-y}}{2}=\frac{e^{2y}+1}{2e^y}$$
If we define $k=e^y$ then:
$$k^2-2xk+1=0$$
$$k=e^{y}=x\pm\sqrt{x^2-1}$$
$$y=\ln(x\pm\sqrt{x^2-1})=\cosh^{-1}(x)$$
However, apparently: $\cosh^{-1}(x)=\ln(x+\sqrt{x^2-1})$ is right, but NOT $\cosh^{-1}(x)=\ln(x-\sqrt{x^2-1})$
What step did I miss?

A: The function $\cosh$ is even, so formally speaking it does not have an inverse, for basically the same reason that the function $g(t)=t^2$ does not have an inverse.
But if we restrict the domain of $\cosh$ suitably, then there is an inverse. The usual definition of $\cosh^{-1}x$ is that it is the non-negative number whose $\cosh$ is $x$.
Note that for $x\gt 1$, we have
$$x-\sqrt{x^2-1}=\frac{1}{x+\sqrt{x^2-1}}\lt 1,$$
and therefore $\ln(x-\sqrt{x^2-1})\lt 0$ whereas we were looking for the non-negative $y$ which would satisfy the inverse equation.
Thus, $y=\ln(x+\sqrt{x^2-1})$ is not the non-negative number whose $\cosh$ is $x$.
Remark: If one defined $\cosh^{-1}(x)$ as the non-positive number whose $\cosh$ is $x$, then the answer $\ln(x-\sqrt{x^2-1})$ would be the right one.


Q: Escrever na tela Javascript Preciso fazer uma área no form que o usuário assine digitalmente com uma caneta para tela de touch para armazenar a assinatura do mesmo.
Como se o mesmo estivesse escrevendo em um papel mas na tela.
Li sobre o Canvas mas so aprendi a fazer linhas, retângulos ou formas.

Segue código

 <!DOCTYPE html>

 <meta charset="UTF-8">
 <title>PresTO - Assinatura Digital</title>

A: Seguindo o exemplo do link postado pelo @JuniorNunes.
O Autor deixou esqueceu algumas partes como declarar as variaveis canvasWidth e canvasHeight referentes ao tamanho da area que voce pode desenhar (canvas)
Testado com mouse no: IE11, Chrome, Firefox e Edge
Testado touch: tela do note touchscreen
EDIT
Adicionados equivalentes para suporte a touch. dado que o evento disparado por um dispositivo touch é não é o mousedown mouseup e mousemove e sim touchstart touchend e touchmove, respectivamente.

var canvasWidth = 300;
var canvasHeight = 150;
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
 canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

$('#canvas').mousedown(function(e){
  var mouseX = e.pageX - this.offsetLeft;
  var mouseY = e.pageY - this.offsetTop;

  paint = true;
  addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
  redraw();
});

$('#canvas').mousemove(function(e){
  if(paint){
    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
    redraw();
  }
});

$('#canvas').mouseup(function(e){
  paint = false;
});

$('#canvas').mouseleave(function(e){
  paint = false;
});

var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);
}

// Set up touch events for mobile, etc
canvas.addEventListener("touchstart", function (e) {
        mousePos = getTouchPos(canvas, e);
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousedown", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);

canvas.addEventListener("touchend", function (e) {
  var mouseEvent = new MouseEvent("mouseup", {});
  canvas.dispatchEvent(mouseEvent);
}, false);

canvas.addEventListener("touchmove", function (e) {
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousemove", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);

// Get the position of a touch relative to the canvas
function getTouchPos(canvasDom, touchEvent) {
  var rect = canvasDom.getBoundingClientRect();
  return {
    x: touchEvent.touches[0].clientX - rect.left,
    y: touchEvent.touches[0].clientY - rect.top
  };
}

// Prevent scrolling when touching the canvas
document.body.addEventListener("touchstart", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchend", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchmove", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);

function redraw(){
  context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas

  context.strokeStyle = "#df4b26";
  context.lineJoin = "round";
  context.lineWidth = 5;

  for(var i=0; i < clickX.length; i++) {
    context.beginPath();
    if(clickDrag[i] && i){
      context.moveTo(clickX[i-1], clickY[i-1]);
     }else{
       context.moveTo(clickX[i]-1, clickY[i]);
     }
     context.lineTo(clickX[i], clickY[i]);
     context.closePath();
     context.stroke();
  }
}
body {
  background:#eee;
}
#canvas {
  background:#fff;
}


Q: How to check if the matched EMPTY line is the LAST line of a file in a while IFS read I have a while IFS read loop to check for different matches in the lines.
I check for and empty/blank line like this:
while IFS= read -r line; do
[[ -z $line ]] && printf some stuff

I also want to check if the matched empty/blank is also the last line of the file. I am going to run this script on a lot of files, they all:
-end with an empty line
-they are all a DIFFERENT LENGTH so I cannot assume anything
-they have other empty lines but not necessarily at the very end (this is why I have to differentiate)
Thanks in advance.

A: As chepner has noted, in a shell line-reading loop the only way to know whether a given line is the last one is to try to read the next one.
You can emulate "peeking" at the next line using the code below, which allows you to detect the desired condition while still processing the lines uniformly.
This solution may not be for everyone, because the logic is nontrivial and therefore requires quite a bit of extra, non-obvious code, and processing is slowed down as well.
Note that the code assumes that the last line has a trailing \n (as all well-formed multiline text input should have).
#!/usr/bin/env bash

eof=0 peekedChar= hadEmptyLine=0 lastLine=0
while IFS= read -r line || { eof=1; (( hadEmptyLine )); }; do

  # Construct the 1-2 element array of lines to process in this iteration:
  #   - an empty line detected in the previous iteration by peeking, if applicable
  (( hadEmptyLine )) && aLines=( '' ) || aLines=()
  #   - the line read in this iteration, with the peeked char. prepended
  if (( eof )); then
    # No further line could be read in this iteration; we're here only because
    # $hadEmptyLine was set, which implies that the empty line we're processing
    # is by definition the last one.
    lastLine=1 hadEmptyLine=0
  else
    # Add the just-read line, with the peeked char. prepended.
    aLines+=( "${peekedChar}${line}" )

    # "Peek" at the next line by reading 1 character, which
    # we'll have to prepend to the *next* iteration's line, if applicable.
    # Being unable to read tells us that this is the last line.
    IFS= read -n 1 peekedChar || lastLine=1
    # If the next line happens to be empty, our "peeking" has fully consumed it,
    # so we must tell the next iteration to insert processing of this empty line.
    hadEmptyLine=$(( ! lastLine && ${#peekedChar} == 0 ))
  fi

  # Process the 1-2 lines.
  ndx=0 maxNdx=$(( ${#aLines[@]} - 1 ))
  for line in "${aLines[@]}"; do
    if [[ -z $line ]]; then # an empty line
      # Determine if this empty line is the last one overall.
      thisEmptyLineIsLastLine=$(( lastLine && ndx == maxNdx ))
      echo "empty line; last? $thisEmptyLineIsLastLine"
    else
      echo "nonempty line:    [$line]"
    fi
    ((++ndx))
  done

done < file


Q: How to randomize points on a sphere surface evenly? Im trying to make stars on the sky, but the stars distribution isnt even.
This is what i tried:
rx = rand(0.0f, PI*2.0f);
ry = rand(0.0f, PI);
x = sin(ry)*sin(rx)*range;
y = sin(ry)*cos(rx)*range;
z = cos(ry)*range;

Which results to:
img http://img716.imageshack.us/img716/3320/sphererandom.jpg
And:
rx = rand(-1.0f, 1.0f);
ry = rand(-1.0f, 1.0f);
rz = rand(-1.0f, 1.0f);
x = rx*range;
y = ry*range;
z = rz*range;

Which results to:
img2 http://img710.imageshack.us/img710/5152/squarerandom.jpg
(doesnt make a sphere, but opengl will not tell a difference, though).
As you can see, there is always some "corner" where are more points in average. How can i create random points on a sphere where the points will be distributed evenly?

A: you can do
z = rand(-1, 1)
rxy = sqrt(1 - z*z)
phi = rand(0, 2*PI)
x = rxy * cos(phi)
y = rxy * sin(phi)

Here rand(u,v) draws a uniform random from interal [u,v]

A: You don't need trigonometry if you can generate random gaussian variables, you can do (pseudocode)
x <- gauss()
y <- gauss()
z <- gauss()
norm <- sqrt(x^2 + y^2 + z^2)

result = (x / norm, y / norm, z / norm)

Or draw points inside the unit cube until one of them is inside the unit ball, then normalize:
double x, y, z;

do
{
    x = rand(-1, 1);
    y = rand(-1, 1);
    z = rand(-1, 1);
} while (x * x + y * y + z * z > 1);

double norm = sqrt(x * x + y * y + z * z);
x / norm; y /= norm; z /= norm;

A: It looks like you can see that it's the cartesian coordinates that are creating the concentrations.
Here is an explanation of one right (and wrong) way to get a proper distribution.


Q: Need help on implementing NMS (Non-Max-Suppression) python I save the results of my object detection model in a .json file and it has the score, box coordinated, the detected class of multiple objects. There are multiple overlapped detections on the image and I heard that NMS can help do exactly that. I found a code that does that but I am not seeing any results and I think I am implementing it wrong. Can someone help me with it as it is much appreciated. Or if there is a better way to get it of overlapping detection (boxes) ?
The code is as follows,
# import the necessary packages
import numpy as np
from PIL import Image, ImageFont, ImageDraw
import cv2
import json
import pandas as pd

json_path2 = "A3_detections.json"

# Opening JSON file
f = open(json_path2)
# Reading into string
whole_text = f.read()

# Editing the text to fit JSON format

whole_text = "{'items':"+whole_text[1:-1]+'}'
whole_text = whole_text.replace("'",'"')
data = json.loads(whole_text)

count = 0
for i in data['items']:
    count+=1

# Iterating through JSON and add
for i in range(count):

    x2 = data['items'][i]['box'][2]
    y2 = data['items'][i]['box'][3]
    x1 = data['items'][i]['box'][0]
    y1 = data['items'][i]['box'][1]
    boxes = [(x1, y1, x2, y2)]

#  Felzenszwalb et al.
def non_max_suppression_slow(boxes, overlapThresh):
    # if there are no boxes, return an empty list
    if len(boxes) == 0:
        return []

    # initialize the list of picked indexes
    pick = []
    pick.append(boxes[index])

    # grab the coordinates of the bounding boxes
    x1 = boxes[:,0]
    y1 = boxes[:,1]
    x2 = boxes[:,2]
    y2 = boxes[:,3]

    # compute the area of the bounding boxes and sort the bounding
    # boxes by the bottom-right y-coordinate of the bounding box
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    idxs = np.argsort(y2)

    # keep looping while some indexes still remain in the indexes
    # list
    while len(idxs) > 0:
        # grab the last index in the indexes list, add the index
        # value to the list of picked indexes, then initialize
        # the suppression list (i.e. indexes that will be deleted)
        # using the last index
        last = len(idxs) - 1
        i = idxs[last]
        pick.append(i)
        suppress = [last]

        # loop over all indexes in the indexes list
        for pos in range(0, last):
            # grab the current index
            j = idxs[pos]

            # find the largest (x, y) coordinates for the start of
            # the bounding box and the smallest (x, y) coordinates
            # for the end of the bounding box
            xx1 = max(x1[i], x1[j])
            yy1 = max(y1[i], y1[j])
            xx2 = min(x2[i], x2[j])
            yy2 = min(y2[i], y2[j])

            # compute the width and height of the bounding box
            w = max(0, xx2 - xx1 + 1)
            h = max(0, yy2 - yy1 + 1)

            # compute the ratio of overlap between the computed
            # bounding box and the bounding box in the area list
            overlap = float(w * h) / area[j]

            # if there is sufficient overlap, suppress the
            # current bounding box
            if overlap > overlapThresh:
                suppress.append(pos)

        # delete all indexes from the index list that are in the
        # suppression list
        idxs = np.delete(idxs, suppress)

    # return only the bounding boxes that were picked
    return boxes[pick]

The .json file looks like this,
"[{'score': 0.9994423, 'box': [371, 108, 451, 165], 'class': 1, 'area': 4560.0}, {'score': 0.9993526, 'box': [309, 383, 393, 438], 'class': 1, 'area': 4620.0}, {'score': 0.9989114, 'box': [408, 336, 482, 394], 'class': 1, 'area': 4292.0}, {'score': 0.9980921, 'box': [276, 443, 359, 510], 'class': 1, 'area': 5561.0}, {'score': 0.99784064, 'box': [276, 144, 352, 198], 'class': 1, 'area': 4104.0}, {'score': 0.99754494, 'box': [399, 494, 492, 550], 'class': 2, 'area': 5208.0}, {'score': 0.9967483, 'box': [414, 403, 493, 474], 'class': 3, 'area': 5609.0}, {'score': 0.99523735, 'box': [359, 194, 456, 267], 'class': 1, 'area': 7081.0}, {'score': 0.99133027, 'box': [258, 238, 346, 313], 'class': 1, 'area': 6600.0}, {'score': 0.9883846, 'box': [223, 361, 279, 460], 'class': 3, 'area': 5544.0}, {'score': 0.9849324, 'box': [480, 318, 543, 381], 'class': 3, 'area': 3969.0}, {'score': 0.972732, 'box': [456, 108, 520, 195], 'class': 3, 'area': 5568.0}, {'score': 0.967366, 'box': [505, 39, 544, 140], 'class': 1, 'area': 3939.0}, {'score': 0.9157209, 'box': [441, 222, 482, 318], 'class': 3, 'area': 3936.0}, {'score': 0.9959129, 'box': [559, 22, 624, 103], 'class': 1, 'area': 5265.0}, {'score': 0.9946513, 'box': [541, 374, 630, 425], 'class': 1, 'area': 4539.0}, {'score': 0.99179137, 'box': [537, 420, 584, 525], 'class': 1, 'area': 4935.0}, {'score': 0.94723177, 'box': [529, 205, 563, 308], 'class': 1, 'area': 3502.0}, {'score': 0.9857883, 'box': [244, 476, 285, 575], 'class': 1, 'area': 4059.0}, {'score': 0.8887795, 'box': [185, 514, 226, 623], 'class': 1, 'area': 4469.0}, {'score': 0.7980404, 'box': [382, 546, 427, 640], 'class': 3, 'area': 4230.0}, {'score': 0.99635565, 'box': [515, 542, 605, 595], 'class': 1, 'area': 4770.0}, {'score': 0.998, 'box': [595, 310, 663, 389], 'class': 1, 'area': 5372.0}, {'score': 0.9968482, 'box': [582, 442, 659, 494], 'class': 1, 'area': 4004.0}, {'score': 0.9964861, 'box': [626, 487, 680, 579], 'class': 1, 'area': 4968.0}, {'score': 0.9919488, 'box': [618, 1, 665, 99], 'class': 1, 'area': 4606.0}, {'score': 0.99128747, 'box': [574, 172, 658, 220], 'class': 1, 'area': 4032.0}, {'score': 0.99087024, 'box': [580, 594, 639, 639], 'class': 1, 'area': 2655.0}, {'score': 0.9883312, 'box': [639, 277, 728, 329], 'class': 1, 'area': 4628.0},


Q: как получить значение столбца excerpt где slug = services, reviews, about из БД . Laravel Пытался получить так
$excerpt = DB::table('pages')->where('slug', ['services', 'reviews', 'about' ])->value('excerpt');

в результате в $excerpt =  только значееие первого т.е services

A: Уже нашел
$excerpt = DB::table('pages')->select('excerpt')->whereIn('slug', ['services', 'reviews'])->get();