text:
Q: Is there any mapping between MaxMind's locid and GeoNames id? I use GeoLite from MaxMind. My real task is to determine CityId in our system by specific IP. In MaxMind I find locid by IP and then use hand-maded table of cross between locid and our CityId. But this cross-table is uncompleted. I found good file of localization from MaxMind where each locid mapped to GeoNames id. GeoNames id it's good for me, but this file is uncompleted. For example, there is no Birmingham in this file.
So, has anybody such problem? And if any ways to decide it?

A: MaxMind's GeoLite2 databases return GeoNames IDs.

A: This is a three parter which gives you all desired output. up to you to wrap it but all city info is provided. by reverse lookup of lon lat and iprange.
It takes python GeoIP example for 1 IP lookup. Then strips the IP ranges. Looks up each range. Then tags its city / lon lat. This is not every IP in every city. But it will give you the main providers and a pretty close if not entirely accurate estimation of what city they are in or next to.
1)
#!/usr/bin/python
import GeoIP
gi = GeoIP.open("/bin/script/tbl/state/GeoLiteCity.dat",GeoIP.GEOIP_STANDARD)

with open ("city.txt", "r") as myfile:
    data=myfile.read().replace('\n', '')
gir = gi.record_by_addr(data)

if gir != None:
        print gir['city']
        print gir['region']
        print gir['region_name']
        print gir['latitude']
        print gir['longitude']

2)
#!/bin/bash
cd /bin/script/tbl/state
for state in $(cat state.abrv); do
 state=$(echo $state)
 cat outputfile | grep $state | cut -f1 -d"," > SB
 output=sb.csv
 echo "ip,country" > $output

 for  i in $( cat SB );
  do echo "$i,\"$( geoiplookup -f GeoLiteCity.dat $i -i | cut -d' ' -f4-99 )\"" >> $output
 done

 echo "a" > sb1.csv && echo "a" >> sb1.csv && echo "a" >> sb1.csv
 cat sb.csv >> sb1.csv

 awk 'NR == 1 || NR % 7 == 0' sb1.csv | tr -d ' ' | tr '-' '/' > sb.csv
 tail -n +2 "sb.csv" > $state

 rm SB sb.csv sb1.csv
done

you can then generate a quick loadable script for iptables like so.  This creates a new chain so you can drop a catch all first.  Python will load these to the top of the chain.  You can then continue setting your primary chain without having to wait 30 minutes for this to load. (depending on your computer of course)
#IPT=/sbin/iptables
#ACT=/bin/script/tbl/state/active.txt
#Py=/usr/bin/python
#suba='p=subprocess.Popen(["'
#subb='"],?stdout?=?subprocess.PIPE)'
#sub2='output?,?err?=?p.communicate()'
#sub3='print?output'
#
#### Any Changes?
#if diff 'active.txt' 'active.old' > /dev/null; then
#    echo 'Loading Group Interests'
#    /bin/bash state.bash
#    $Py state.py
#    exit
#else
#    echo 'Modifying Rules For'
#    echo $(diff active.txt active.old | head -50 | tail -49 | cut -f2 -d'0')
#fi
#
### Then lets go
#   echo '#!/bin/bash' > state.bash
#   echo '#!/usr/bin/python' > state.py
#   echo 'import?subprocess' >> state.py
#
#for state in $(cat $ACT)
#do
#   echo $IPT' -N '$state >> state.bash
#   echo $IPT' -A '$state' -j DROP' >> state.bash
#done
#/bin/bash state.bash
#
#for state in $(cat $ACT)
#do
#        BADIPS=$(egrep -v -E "^#|^$" $state |  sed 's/[A-Za-z]*//g' | tr -d ":")
#        for ip in $BADIPS
#        do
#                echo $ip | cut -f1 -d'/' > city.txt
# $Py city.py | head -4 | tail -1 > lon.ip
#                $Py city.py | head -5 | tail -1 > lat.ip
#                city=$(cat city.ip | tr ' ' '_')
#                lon=$(cat lon.ip)
#                lat=$(cat lat.ip)
#                echo $suba'iptables -A INPUT -s '$ip' -j '$state$subb >> state.py
#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#                echo $suba'iptables -A FORWARD -s '$ip' -j '$state$subb >> state.py
#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#                echo $suba'iptables -A OUTPUT -d '$ip' -j '$state$subb  >> state.py
#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#                echo $suba"iptables -A "$state" -s "$ip" -j LOG --log-prefix \
#'STATE_,"$ip","$state","$city","$lon":"$lat",_OUT_:'"$subb >> state.py
#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#                echo $suba"iptables -A "$state" -d "$ip" -j LOG --log-prefix \
#'STATE_,"$ip","$state","$city","$lon":"$lat",_IN_:'"$subb >> state.py
#                echo $sub2 >> state.py
#  echo $sub3 >> state.py
#                echo $suba"iptables -A "$state" -s "$ip" -j LOG --log-prefix    \
    'STATE_,"$ip","$state","$city","$lon":"$lat",_OUT_:'"$subb >> state.py

#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#                echo $suba"iptables -A "$state" -d "$ip" -j LOG --log-prefix    #'STATE_,"$ip","$state","$city","$lon":"$lat",_IN_:'"$subb >> state.py
#                echo $sub2 >> state.py
#                echo $sub3 >> state.py
#        done
#done

### MAGIC
sed 's/ /"','"/g' state.py > state1.py
cat state1.py | tr '?' ' ' > state.py

sleep 3
python state.py
cat active.txt > active.old

### adapting this to ASN or country is way easier.
### your welcome
### last time I post anything on this webpage.  There is NOTHING wrong with my formatting. go cry about it

A: I couldn't match geoname_id and registered_country_geoname_id for country in the maxmind database geolite2 until I found this:
https://www.kaggle.com/geonames/geonames-database?select=geonames.csv


text:
Q: Where do you find templates useful? At my workplace, we tend to use  iostream, string, vector, map, and the odd algorithm or two.  We haven't actually found many situations where template techniques were a best solution to a problem.
What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life.
As a bribe, expect an up vote for your answer.

A: I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to write any.
One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the ExeFile class that I'd written to handle the files only worked with 32-bit ones. The code required to manipulate the 64-bit version was essentially identical, but it needed to use a different address type (64-bit instead of 32-bit), which caused two other data structures to be different as well.
Based on the STL's use of a single template to support both std::string and std::wstring, I decided to try making ExeFile a template, with the differing data structures and the address type as parameters. There were two places where I still had to use #ifdef WIN64 lines (slightly different processing requirements), but it wasn't really difficult to do. We've got full 32- and 64-bit support in that program now, and using the template means that every modification we've done since automatically applies to both versions.

A: One place that I do use templates to create my own code is to implement policy classes as described by Andrei Alexandrescu in Modern C++ Design.  At present I'm working on a project that includes a set of classes that interact with BEA\h\h\h Oracle's Tuxedo TP monitor.
One facility that Tuxedo provides is transactional persistant queues, so I have a class TpQueue that interacts with the queue:
class TpQueue {
public:
   void enqueue(...)
   void dequeue(...)
   ...
}

However as the queue is transactional I need to decide what transaction behaviour I want; this could be done seperately outside of the TpQueue class but I think it's more explicit and less error prone if each TpQueue instance has its own policy on transactions.  So I have a set of TransactionPolicy classes such as:
class OwnTransaction {
public:
   begin(...)  // Suspend any open transaction and start a new one
   commit(..)  // Commit my transaction and resume any suspended one
   abort(...)
}

class SharedTransaction {
public:
   begin(...)  // Join the currently active transaction or start a new one if there isn't one
   ...
}

And the TpQueue class gets re-written as
template <typename TXNPOLICY = SharedTransaction>
class TpQueue : public TXNPOLICY {
   ...
}

So inside TpQueue I can call begin(), abort(), commit() as needed but can change the behaviour based on the way I declare the instance:
TpQueue<SharedTransaction> queue1 ;
TpQueue<OwnTransaction> queue2 ;

A: I used templates (with the help of Boost.Fusion) to achieve type-safe integers for a hypergraph library that I was developing.  I have a (hyper)edge ID and a vertex ID both of which are integers.  With templates, vertex and hyperedge IDs became different types and using one when the other was expected generated a compile-time error.  Saved me a lot of headache that I'd otherwise have with run-time debugging.

A: Here's one example from a real project. I have getter functions like this:
bool getValue(wxString key, wxString& value);
bool getValue(wxString key, int& value);
bool getValue(wxString key, double& value);
bool getValue(wxString key, bool& value);
bool getValue(wxString key, StorageGranularity& value);
bool getValue(wxString key, std::vector<wxString>& value);

And then a variant with the 'default' value. It returns the value for key if it exists, or default value if it doesn't. Template saved me from having to create 6 new functions myself.
template <typename T>
T get(wxString key, const T& defaultValue)
{
    T temp;
    if (getValue(key, temp))
        return temp;
    else
        return defaultValue;
}

A: Templates I regulary consume are a multitude of container classes, boost smart pointers, scopeguards, a few STL algorithms.
Scenarios in which I have written templates:

*

*custom containers

*memory management, implementing type safety and CTor/DTor invocation on top of void * allocators

*common implementation for overloads wiht different types, e.g.
bool ContainsNan(float * , int)
bool ContainsNan(double *, int)
which both just call a (local, hidden) helper function
template <typename T>
bool ContainsNanT<T>(T * values, int len) { ... actual code goes here } ;

Specific algorithms that are independent of the type, as long as the type has certain properties, e.g. binary serialization.
template <typename T>
void BinStream::Serialize(T & value) { ... }

// to make a type serializable, you need to implement
void SerializeElement(BinStream & strean, Foo & element);
void DeserializeElement(BinStream & stream, Foo & element)

Unlike virtual functions, templates allow more optimizations to take place.

Generally, templates allow to implement one concept or algorithm for a multitude of types, and have the differences resolved already at compile time.

A: We use COM and accept a pointer to an object that can either implement another interface directly or via [IServiceProvider](http://msdn.microsoft.com/en-us/library/cc678965(VS.85).aspx) this prompted me to create this helper cast-like function.
// Get interface either via QueryInterface of via QueryService
template <class IFace>
CComPtr<IFace> GetIFace(IUnknown* unk)
{
    CComQIPtr<IFace> ret = unk; // Try QueryInterface
    if (ret == NULL) { // Fallback to QueryService
        if(CComQIPtr<IServiceProvider> ser = unk)
            ser->QueryService(__uuidof(IFace), __uuidof(IFace), (void**)&ret);
    }
    return ret;
}

A: General info on templates:
Templates are useful anytime you need to use the same code but operating on different data types, where the types are known at compile time.   And also when you have any kind of container object.
A very common usage is for just about every type of data structure.  For example: Singly linked lists, doubly linked lists, trees, tries, hashtables, ...
Another very common usage is for sorting algorithms.
One of the main advantages of using templates is that you can remove code duplication.  Code duplication is one of the biggest things you should avoid when programming.
You could implement a function Max as both a macro or a template, but the template implementation would be type safe and therefore better.
And now onto the cool stuff:
Also see template metaprogramming, which is a way of pre-evaluating code at compile-time rather than at run-time.  Template metaprogramming has only immutable variables, and therefore its variables cannot change.  Because of this template metaprogramming can be seen as a type of functional programming.
Check out this example of template metaprogramming from Wikipedia.  It shows how templates can be used to execute code at compile time.  Therefore at runtime you have a pre-calculated constant.
template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

A: I use templates to specify function object types.  I often write code that takes a function object as an argument -- a function to integrate, a function to optimize, etc. -- and I find templates more convenient than inheritance.  So my code receiving a function object -- such as an integrator or optimizer -- has a template parameter to specify the kind of function object it operates on.

A: The obvious reasons (like preventing code-duplication by operating on different data types) aside, there is this really cool pattern that's called policy based design. I have asked a question about policies vs strategies.
Now, what's so nifty about this feature. Consider you are writing an interface for others to use. You know that your interface will be used, because it is a module in its own domain. But you don't know yet how people are going to use it. Policy-based design strengthens your code for future reuse; it makes you independent of data types a particular implementation relies on. The code is just "slurped in". :-)
Traits are per se a wonderful idea. They can attach particular behaviour, data and typedata to a model. Traits allow complete parameterization of all of these three fields. And the best of it, it's a very good way to make code reusable.

A: I once saw the following code:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
   // three lines of code
   callFunctionGeneric1(c) ;
   // three lines of code
}

repeated ten times:
void doSomethingGeneric2(SomeClass * c, SomeClass & d)
void doSomethingGeneric3(SomeClass * c, SomeClass & d)
void doSomethingGeneric4(SomeClass * c, SomeClass & d)
// Etc

Each function having the same 6 lines of code copy/pasted, and each time calling another function callFunctionGenericX with the same number suffix.
There were no way to refactor the whole thing altogether. So I kept the refactoring local.
I changed the code this way (from memory):
template<typename T>
void doSomethingGenericAnything(SomeClass * c, SomeClass & d, T t)
{
   // three lines of code
   t(c) ;
   // three lines of code
}

And modified the existing code with:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
   doSomethingGenericAnything(c, d, callFunctionGeneric1) ;
}

void doSomethingGeneric2(SomeClass * c, SomeClass & d)
{
   doSomethingGenericAnything(c, d, callFunctionGeneric2) ;
}

Etc.
This is somewhat highjacking the template thing, but in the end, I guess it's better than play with typedefed function pointers or using macros.

A: It's already been mentioned that you can use templates as policy classes to do something. I use this a lot.
I also use them, with the help of property maps (see boost site for more information on this), in order to access data in a generic way. This gives the opportunity to change the way you store data, without ever having to change the way you retrieve it.

A: I personally have used the Curiously Recurring Template Pattern as a means of enforcing some form of top-down design and bottom-up implementation. An example would be a specification for a generic handler where certain requirements on both form and interface are enforced on derived types at compile time. It looks something like this:
template <class Derived>
struct handler_base : Derived {
  void pre_call() {
    // do any universal pre_call handling here
    static_cast<Derived *>(this)->pre_call();
  };

  void post_call(typename Derived::result_type & result) {
    static_cast<Derived *>(this)->post_call(result);
    // do any universal post_call handling here
  };

  typename Derived::result_type
  operator() (typename Derived::arg_pack const & args) {
    pre_call();
    typename Derived::result_type temp = static_cast<Derived *>(this)->eval(args);
    post_call(temp);
    return temp;
  };

};
Something like this can be used then to make sure your handlers derive from this template and enforce top-down design and then allow for bottom-up customization:
struct my_handler : handler_base<my_handler> {
  typedef int result_type; // required to compile
  typedef tuple<int, int> arg_pack; // required to compile
  void pre_call(); // required to compile
  void post_call(int &); // required to compile
  int eval(arg_pack const &); // required to compile
};

This then allows you to have generic polymorphic functions that deal with only handler_base<> derived types:
template <class T, class Arg0, class Arg1>
typename T::result_type
invoke(handler_base<T> & handler, Arg0 const & arg0, Arg1 const & arg1) {
  return handler(make_tuple(arg0, arg1));
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Crash in ios7 while setting font on navigation bar I am using this link here to change the font and color of title in navigation bar. I also tried this. Both of them run fine in ios8 but when i test in ios7 each time it crashes at "NSFontAttributeName". If i remove the code to set the font and only set the color , it works.
The crash message that I get is * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]
Any help would be appreciated. Hope my problem is clear.

A: Use this code:
UINavigationBar *navBar = [UINavigationBar appearance];
[navBar setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"yourFont" size:15]];

A: Try this, it works fine for me in both IOS8 as well as IOS7
`
NSShadow * shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor clearColor];
shadow.shadowOffset = CGSizeMake(0, 0);
[self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:@"custom-color",
                                                 NSShadowAttributeName: shadow,
                                                 NSFontAttributeName: @"font-name",
                                                 }];`


text:
Q: Error message when attempting to define a function Using python on repl.it
Attempting to define a function, and getting a vague syntax error when trying to run the program. I have attempted to fix this by redoing the indentations, with no luck. Please help. code below
health = 10

def labencounter():
  entity = 'alchemist'
  battlevar = 0
  entityhp = 10
  print('An alchemist jumps out of the darkness, surrounded by neon ooze and bubbling vats!')
  battleaction = str(input('What will you do? [a]ttack [s]uper attack [i]tem or [r]un?'))
  while entityhp > 0:
    while battlevar  < 0:
      if battleaction == 'a':
        battlevar += 1
        entityhp -= 1
        health -= 3
        print('The ' + entity + '\'s health is' + entityhealth + '! Your health is ' + health)
        battlevar = 0
      elif battleaction == 's':
        battlevar += 1
        entityhp -= 3
        health -= 2
        print('The ' + entity + '\'s health is' + entityhealth + '! Your health is ' + health)
        battlevar = 0
      elif battleaction == 'i':
        battlevar += 1
        print('You have no items!')
        battlevar = 0
      elif battleaction == 'r':
        print('It chases you down and kills you.')
        health -= 10
      else:
        battleaction = str(input('[a]ttack [s]uper attack [i]tem or [r]un')

def entryway():
  x = 0
  enter = input('You see a gigantic doorway, yawning in the morning sun. Will you forsake the light and enter the dungeon? [y]/[n]')
  while x < 1:
    if enter.lower() != 'y' and enter != 'n':
      enter = input('[y]/[n]')
    elif enter.lower() == 'y':
      x += 1
      print('The darkness grows around you, as you yourself do the same into the abyss.')
    else:
      print('You turn away. Caves are not meant for one such as you.')
      exit()

with an error message reading
  File "main.py", line 34
    def entryway():
    ^
SyntaxError: invalid syntax

A: I haven't closed the brackets on line 31
battleaction = str(input('[a]ttack [s]uper attack [i]tem or [r]un')


text:
Q: Icon changing on it's own when resizing icons So I'm practicing with Windows Apps and I've created a 2048 version in WinApi coded in C++.
Added a simple icon created in Paint just to see how it works, now few mins ago I've created a better looking one to update the game and add few features, I've successfully changed the icon but if I resize or better to say, enlarge the icons to see how it looks it changes back to the old one. I've even deleted all references of the old icon from the .cpp, .h and .rc files but the problem is still there.
Here's what's going on (upper icons are before I enlarged them a bit with (ctrl+scroll)):
http://postimg.org/image/aqw52jdtp/
Icon is 32x32, 24bit.
This is what my code looks like:
WndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON2));
WndClass.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON2));

IDI_ICON2 has the value from  .rc file, no other references exist regarding icons or bitmaps.
Any1 know why this is happening?


text:
Q: Mac app icons dissapearing and reappearing randomly Alright so most of the people have their desktop having some missing icons but i'm not really having this problem, the real problem is that all the apps in finder are missing icons and sometimes they reappear weirdly...

DolphinEMU's icon is the most inactive.
When i look up on finder... this happens...

Yes it's french, but almost all my apps have no icon and they reappear sometimes. they still run perfectly.


text:
Q: How to change some part of text in PySpark? I have a data set with million rows. And I have a huge list of keywords :
AS     Alan Sir
BFD    Baba Farda Dobare

And so on. I want each row if it has AS, change it to Alan Sir, if it has BFD, change it to Baba Farda Dobare.
How I can do that in PySpark?

A: You can convert the txt file into a dictionary, and use df.replace to replace the values according to the dictionary mapping. You can also specify which column to replace using the subset parameter:
df2 = df.replace({'AS': 'Alan Sir', 'BFD': 'Baba Farda Dobare'}, subset = ['column1'])

However this only works for exact matches. For non-exact matches, you can use the other replace function:
import pyspark.sql.functions as F
from functools import reduce
df2 = reduce(
    lambda x, y: x.withColumn(
        'column1', F.expr(f"replace(column1, '{y[0]}', '{y[1]}')")
    ),
    my_dict.items(),
    df
)


text:
Q: argmax function in Haskell I want to create a one-line function "argmax" using fold where I enter an anonymous/lambda function and a list. Then I apply the function to the list and get a new list based on the function. Now I get the maximum value of the second list and return the element from the first list which created the maximum value when applied to the function.
It should look like this:
Input: argmax (\x -> mod x 5) [1,4,7]
the second list should be: [1,4,2]
The Maximum element from the second list is 4 so it should return 4 from the first list, because mod 4 5 = 4.
So the output should be: 4
Currently I have this:
argmax :: (Ord a) => a -> [a] -> a

argmax f xs = foldr max f xs

but it doesnt work for a anonymous function
I get this error: No instance for (Show (Integer -> Integer))
I tried to change the type signature, but that did not help.
If someone could help me fixing my code, I would appreciate it
Thanks in advance! ^^


text:
Q: How to download the files using vbscript in classic asp I am working on Classic Asp with VBScript. I am trying to display list of files from a directory with download option. like,
When i click on the download link the corresponding file need to be download for that i have used the following code like,

<title> My First ASP Page </title>

<%
Dim fso
Dim ObjFolder
Dim ObjOutFile
Dim ObjFiles
Dim ObjFile

'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Getting the Folder Object
Set ObjFolder = fso.GetFolder("F:\karthik")

'Creating an Output File to write the File Names
Set ObjOutFile = fso.CreateTextFile("F:\WindowsFiles.txt")

'Getting the list of Files
Set ObjFiles = ObjFolder.Files

'Writing Name and Path of each File to Output File
Response.Write("
")
For Each ObjFile In ObjFiles
    Response.Write("
"&ObjFile.Name & String(50 - Len(ObjFile.Name), " ")&"	Download
")
Next
 Response.Write("
")
ObjOutFile.Close
%>

A: It seems you are trying to do this on the server-side using client-side scripting. Here is a better solution that uses server-side ASP to send the file. You will need to split your code over two pages.
Your current script should be replaced with this:

<title> My First ASP Page </title>

<% Dim fso
Dim ObjFolder
Dim ObjOutFile
Dim ObjFiles
Dim ObjFile

'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Getting the Folder Object
Set ObjFolder = fso.GetFolder("F:\karthik")

'Getting the list of Files
Set ObjFiles = ObjFolder.Files

'Writing Name and Path of each File to Output File
Response.Write("
")
For Each ObjFile In ObjFiles
    Response.Write("
"&ObjFile.Name & String(50 - Len(ObjFile.Name), " ")&"	Download
")
Next
 Response.Write("
")
%>

Then you need to create another script which I have called download.asp which handles the download:
<%
Dim objConn, strFile
Dim intCampaignRecipientID

strFile = Request.QueryString("file")

If strFile <> "" Then

    Response.Buffer = False
    Dim objStream
    Set objStream = Server.CreateObject("ADODB.Stream")
    objStream.Type = 1 'adTypeBinary
    objStream.Open
    objStream.LoadFromFile("F:\karthik\" & strFile)
    Response.ContentType = "application/x-unknown"
    Response.Addheader "Content-Disposition", "attachment; filename=" & strFile
    Response.BinaryWrite objStream.Read
    objStream.Close
    Set objStream = Nothing

End If
%>

A: I like this solution, but users can see the downloads in the history, or modify the querystring. This solution can be modified for POST usage this way:
    in the page code modify the link:

    FileName`

and further down
    <form id="frm2dl" action="download.asp" method="post"><input type="hidden" id="file2dl" name="file2dl" value="" /></form>

then in your javascript file get the filename:
    function getfile(obj) {
      var f=obj.innerText;
      $("#frm2dl #file2dl").val(f);
      $("#frm2dl").submit();
    }

alternately you could use a file ID then in the download.asp have a lookup function from ID to filename.
Then in the download.asp use request.form("file2dl") instead of request.querystring.
UPDATE:
Also, depending on server version you might get the 4MB limit (I have to work with Microsoft-IIS/7.5 on intranet). Therefore for large files the code will not work. Here is my improved version:
Dim strFileName, strFilePath, objFSO, objStream, objFile, intFileSize
Const lChkSize = 524288 ' 500KB - server typical limit is 4MB
'If session("loggedIn") = True Then ' insert your logon validation code here. bypassed for testing
    strFileName = request.form("file2dl")
    strFilename = Replace(strFilename,"..","") ' prevent parent path navigation - also ensure uploaded files do not contain this sequence
    strFilename = Replace(strFilename,"/","") ' prevent path navigation
    strFilename = Replace(strFilename,"\","") ' filenames should already be cleaned by a previous process
    strFilePath = server.MapPath("/insert your URL absolute sources filepath here/" & strFilename)
    Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(strFilePath) Then
        Set objFile = objFSO.GetFile(strFilePath)
        intFileSize = objFile.Size
        Set objFile = Nothing
        Response.AddHeader "Content-Disposition","attachment; filename=" & strFileName
        Response.ContentType = "application/x-msdownload"
        Response.AddHeader "Content-Length", intFileSize
        Set objStream = Server.CreateObject("ADODB.Stream")
        objStream.Type = 1 'adTypeBinary
        objStream.Open
        objStream.LoadFromFile strFilePath
        Do While Not objStream.EOS And Response.IsClientConnected
            Response.BinaryWrite objStream.Read(lChkSize)
            Response.Flush()
        Loop
        objStream.Close
        Set objStream = Nothing
    Else
        Response.write "Error finding file: " & request.form("file2dl")
    End if
    Set objFSO = Nothing
'End If


text:
Q: How to import excel data from specific rows into EXISTING SQL table? I need to import an excel spreadsheet into a database. I get the spreadsheet every few months so the amount of data varies each time. Data either starts from row 7 or row 8 which contain header information and does not have specific row to end. The amount of data varies from 400 to 10000s rows. Above and below the data is information I don't need. I am trying to create an automated procedure in SQL server to read only data I want and import into an existing table.
I was thinking of creating a condition where the data must be read from the header information which starts from either row 7 or row 8 all the way to the first blank row. How do I create a condition like this?
I am aware of the OPENROWSETS. The problem with OPENROWSETS is it can specified to read from a specific row and I don't think it can be specified to end reading at a blank row.

A: Without seeing the spreadsheet data, I would suggest reading the entire worksheet into a temp table, trim "off the fat" and insert the meat into the real table.


text:
Q: Optimal Binarize value for counting experiment I am currently working on a physics experiment where I count particles. I have looked at and used a bit of code from the following sources:
Cell counting from an image file and
Count Elements in Image
However,this is my first attempt at the code.
(Note: this code wasn't giving good counts for the particles at particular slide depths. I attached my final solution to the end of this post):
locate = SystemDialogInput["FileOpen"];
img = Import[locate]
b = FillingTransform[ColorNegate[Binarize[img]]]
disT = DistanceTransform[b, Padding -> 0];
marker = MaxDetect[ImageAdjust[disT], 0];
w = WatershedComponents[GradientFilter[b, 3], marker,
   Method -> "Rainfall"];
cells = SelectComponents[w, "Count",
  0 < # < 500 &];(*Pixel interval*)measures =
 ComponentMeasurements[
  cells, {"Centroid", "EquivalentDiskRadius", "Label"}];
Grid[{{Style[
    "Number of Particles is " <> ToString[Dimensions[measures][[1]]] <>
     ".", "Title"],
   Button["Save it?",
    Export[DirectoryName[locate] <> FileBaseName[locate] <> ".txt",
     "Number of Cell is " <> ToString[Dimensions[measures][[1]]] <>
      ".     " <> DateString[]]]}, {Show[img,
    Graphics[{Red, Circle @@ # & /@ (measures[[All, 2, 1 ;; 2]]),
      MapThread[
       Text, {measures[[All, 2, 3]], measures[[All, 2, 1]]}]}]]}}]

isn't working very well with my images.

Furthermore, I am having to adjust the value of x in Binarize[img, x] for each image in order to get accurate counts. I don't exactly know how to adjust Binarize to get consistent counts for my data

The final picture in my data set is also proving to be a challenge to process.
I solved the ImageCrop[] problem of this question by pre-processing all of my images, now I just need to find a way to make Binarize[] give good counts of the particles in my image(s).
Final Code
For those who need it.
(The above method gave somewhat inaccurate results so I settled on this one, it basically searches for the images called ker, ker2, and ker3 and finds the points associated with these images in the file that you input to the function. It produced some nice counts)
(ker) = Kernal 1 =
(ker2) = Kernal 2 =
(ker3) = Kernal 3 =
ker = (*Image of Kernal 1*)
locate = SystemDialogInput["FileOpen"];
img = Import[locate];
i = ImageCorrelate[img, ker, NormalizedSquaredEuclideanDistance];
dots = Point[#[[2]]] & /@
   ComponentMeasurements[
    MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
    "Centroid"];
Length[dots]
Show[img, Graphics[{Red, dots}]]

ker2 = (*Image of Kernal 2*)
i = ImageCorrelate[img, ker2, NormalizedSquaredEuclideanDistance];
dots2 = Point[#[[2]]] & /@
   ComponentMeasurements[
    MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
    "Centroid"];
Length[dots2]
Show[img, Graphics[{Red, dots2}]]

ker3 = (*Image of Kernal 3*)
i = ImageCorrelate[img, ker3, NormalizedSquaredEuclideanDistance];
dots3 = Point[#[[2]]] & /@
   ComponentMeasurements[
    MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
    "Centroid"];
Length[dots3]
Show[img, Graphics[{Red, dots2}]]
Length[dots] + Length[dots2] + Length[dots3]

A: You may want to do some processing on the image before your Binarize it.
Working with the Blue channel of your jpg:
img = ColorSeparate[Import["tRGTt.jpg", "JPG"]][[2]];

Use a BottomHatTransform to correct the background
img2 = Binarize[BottomHatTransform[img, DiskMatrix[15]]]

There are many ComponentMeasurements options you can play with to be selective about the components it picks.
morph = MorphologicalComponents[img2, CornerNeighbors -> True];
comps = ComponentMeasurements[morph, {"Centroid", "EquivalentDiskRadius", "Circularity"}, ((5 < #2 < 30) && (#3 > 0.2)) &];

Show[Image[img, "Byte", ImageSize -> Large], Graphics[{Red, Map[Circle[#, 15] &, comps[[1 ;;, 2, 1]]]}]]

It's definitely not perfect, there are some false positives and it misses a lot of your faint, out of focus particles, but hopefully its enough to give you a start! In your measurement, is it possible to keep your particles in the focal plane of your imaging system to make your processing easier? For example by making a thinner flow cell for your particles?


text:
Q: Django combine two fields data into a queryset I have a model say Club where we have fields like:
manager = models.ForeignKey(Users, related_name="return_manager", on_delete=models.CASCADE)
members = models.ManyToManyField(Users, related_name="return_members", blank=True)

Now I want to create a drop down in a form where I can add both the manager and members to it. I tried making two requests for Club.objects.filter(pk=mypk).members.all() and Club.objects.filter(pk=mypk).manager. I tried chain function and using '| ' operator but none worked. I think the manager is a single User and not a queryset, that is what the main problem is. Any workarounds?

A: One possible way getting all of the information together involves modifying your form choices.
In your view you would need to pass the choices along as context to your form.
def my_view(request, club_pk):
    context = {}
    context.update({
        "manager": Club.objects.get(pk=club_pk).manager,
        "members": Club.objects.get(pk=club_pk).members.all()
    }
    form = MyForm(request.POST or None, request=request, context=context)

In your form, you would need to modify the __init__ method to update your choices like so:
class MyForm(forms.Form):
    all_club_members = forms.ChoiceField('Manager + Members', required=True)

    def __init__(self, *args, **kwargs):
        self.context = kwargs.pop('context', None)

        super(MyForm, self).__init__(*args, **kwargs)

        manager_tuple = [(self.context['manager'].id, self.context['manager'].display_name)]
        members_tuples = [(member.id, member.display_name) for member in self.context['members']
        self.fields['all_club_members'].choices = manager_tuple + members_tuples

A: Try this:
manager = [Club.objects.filter(pk=mypk).manager]
members = Club.objects.filter(pk=mypk).members.all()
userlist = list(manager) + list(members)
return Users.objects.filter(pk__in=userlist)

Should create a queryset of all users


text:
Q: Creating multidimensional array and removing empty categories I have a single-dimensional array of categories; some of which are children of other categories, and some of which contain 'elements'. I need to turn it into a multidimensional array, and remove any categories which have no elements in them or any of their children (or children's children...).
I have the following array:
$category_array = array(

    1 => array(
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    ),

    4 => array(
        'elementcount' => 0,
        'parentcat' => 1,
        'depth' => 2
    ),

    8 => array(
        'elementcount' => 0,
        'parentcat' => 4,
        'depth' => 3
    ),

    9 => array(
        'elementcount' => 2,
        'parentcat' => 4,
        'depth' => 3
    ),

    11 => array(
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    ),

    12 => array(
        'elementcount' => 0,
        'parentcat' => 11,
        'depth' => 2
    ),

    21 => array(
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    )

);

and I need the following array:
$multidimensional_array = array(

    1 => array(
        'elementcount' => 3,
        'children' => array(
            4 => array(
                'elementcount' => 0,
                'children' => array(
                    9 => array(
                        'elementcount' => 2
                    )
                )
            )
        )
    ),

    11 => array(
        'elementcount' => 3,
    ),

    21 => array(
        'elementcount' => 3,
    )

);

How can this be achieved?

A: This would be an approach:
<?php

$input = [
    1 => [
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    ],
    4 => [
        'elementcount' => 0,
        'parentcat' => 1,
        'depth' => 2
    ],
    8 => [
        'elementcount' => 0,
        'parentcat' => 4,
        'depth' => 3
    ],
    9 => [
        'elementcount' => 2,
        'parentcat' => 4,
        'depth' => 3
    ],
    11 => [
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    ],
    12 => [
        'elementcount' => 0,
        'parentcat' => 11,
        'depth' => 2
    ],
    21 => [
        'elementcount' => 3,
        'parentcat' => 0,
        'depth' => 1
    ]
];

$maxDepth = max(array_column($input, 'depth'));

// handle elements from higher to lower depth
for ($d = $maxDepth; $d >= 0; $d--) {

  array_walk($input, function(&$entry, $index) use (&$input, $d) {
    if (isset($entry['depth']) && $entry['depth'] == $d) {

      // omit entries without elements or elements in children
      if ($entry['elementcount'] < 1 && empty($entry['children'])) {
        unset($input[$index]);

      // handle as child entry of a parent entry
      } else if (array_key_exists($entry['parentcat'], $input)) {
        $input[$entry['parentcat']]['children'][$index] = [
          'elementcount' => $entry['elementcount'],
          'children' => isset($entry['children']) ? $entry['children'] : []
        ];
      unset($input[$index]);

      // handle as ordinary entry
      } else {
        $input[$index] = [
          'elementcount' => $entry['elementcount'],
          'children' => isset($entry['children']) ? $entry['children'] : []
        ];
      }
    }
  });

}

print_r($input);

The strategy:

*

*handle higher depths first so that the order of input elements does not matter

*for each element check if the parent exists, if so stuff it in there

*redefine all handled elements

The obvious output is:
(
    [1] => Array
        (
            [elementcount] => 3
            [children] => Array
                (
                    [4] => Array
                        (
                            [elementcount] => 0
                            [children] => Array
                                (
                                    [9] => Array
                                        (
                                            [elementcount] => 2
                                            [children] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )
    [11] => Array
        (
            [elementcount] => 3
            [children] => Array
                (
                )
        )
    [21] => Array
        (
            [elementcount] => 3
            [children] => Array
                (
                )
        )
)

I took the liberty to create a slightly modified result compared to your suggestion:
The 'children' property always exists as an array. That makes the usage of the result easier and more robust later on. I'd say that in general all elements inside a structure should have identical structure themselves if possible ...

A: function isParent($id, $list) : bool {
    foreach($list as $item) {
        if ($item['parentcat'] === $id) {
            return true;
        }
    }

    return false;
}

function buildLevel($parent, $catsByParent) : array {
    $result = $catsByParent[$parent] ?? [];

    foreach($result as $id => $cat) {
        if (isset($catsByParent[$id])) {
            $result[$id]['children'] = buildLevel($id, $catsByParent);
            unset($catsByParent[$id]);
        }
    }

    return $result;
}

// Filter out empty categories
$cats = array_filter(
    $category_array,
    function($cat, $id) use($category_array) {
        return $cat['elementcount']>0 || isParent($id, $category_array);
    },
    ARRAY_FILTER_USE_BOTH
);

$catsByParent = [];
// Build cats list keyed by parentcat
foreach($cats as $id => $cat) {
    $parent = $cat['parentcat'];
    unset($cat['parentcat'], $cat['depth']);
    $catsByParent[$parent] = ($catsByParent[$parent] ?? []) + [$id => $cat];
}

// Build result
$multidimensional_array = buildLevel(0, $catsByParent);

print_r($multidimensional_array);

First one filters out empty elements, i.e "categories which have no elements in them or any of their children". (children's children requirement sounds strange, wouldn't that be "any of their children" one level further down?)
Then the remaining categories are grouped/sorted by parentcat, aka "level id", to make the list workable :).
Then that list is traversed, starting with level id 0 at the top, and recursively processed(the children) as deep down as needed.


text:
Q: What are some good methods for finding value of $\arctan (x- \sqrt{y}).$ Don't know how to find value of $\arctan (-2-\sqrt3$)? Please give some useful insights that in 'general' (which I mentioned above in variable form) how can we find it?

A: In general, you don't get "nice" values for expressions like $\arctan(x - \sqrt y)$ or $\arctan(x + \sqrt y).$
In some cases you will get an angle that is a rational multiple of $\pi.$
For example,
\begin{align}
\arctan(1) &= \frac14 \pi,\\
\arctan(\sqrt3) &= \frac13 \pi.
\end{align}
This is the exception rather than the rule.
See $\arctan$ of a square root as a rational multiple of $\pi$ for a partial explanation.
Of course you can always construct the angle geometrically:
if $x$ and $y$ are integers, classical geometry enables you to construct a line segment whose length is $x - \sqrt y$ times the length of a given line segment,
and to position the new segment so the two segments meet at endpoints and are perpendicular; then you join the other endpoints with a third segment and voilá, there is an angle of measure $\arctan(x - \sqrt y).$
But that method does not necessarily lead to a good answer concerning what fraction of a full circle that angle represents.
For "nice" values of the arc tangent, you can use various techniques that basically amount to pattern recognition and guesswork.
Since you're essentially guessing anyway, you can try "nice" values of the tangent function and work backward from there.
The arc tangent examples above are based on the facts that
$\tan\left(\frac14\pi\right)=1$
and $\tan\left(\frac13\pi\right)=1.$
Even in this direction there is only a limited amount you can do:
$\tan\left(\frac17\pi\right)$ and $\tan\left(\frac19\pi\right)$
are not constructible by classical methods, so they certainly cannot be
written $x - \sqrt y$ or $x + \sqrt y$ for any integers $x$ or $y.$
Constructible tangents of "nice" angles include
$\tan\left(\frac15\pi\right) = \sqrt{5 - 2\sqrt 5},$
which is not quite the kind of number you want.
Using the half-angle formula and the sum and difference formulas for tangents,
as well as the fact that $\tan\left(\frac\pi2 - x\right) = 1/\tan(x),$
it is possible to write tangents of many other rational multiples of $\pi$
as expressions that involve addition, subtraction, and square roots starting with integers, but not so many of those will simplify to the form $x \pm \sqrt y.$
We just happen to get lucky in the case of $-2 - \sqrt 3,$
because
\begin{align}
\tan\left(-\frac{5}{12}\pi\right)
= -\tan\left(\frac{5}{12}\pi\right)
&= -\tan\left(\frac14\pi+\frac16\pi\right) \\
&= -\left(\frac{\tan\left(\frac14\pi\right) + \tan\left(\frac16\pi\right)}
               {1 - \tan\left(\frac14\pi\right)\tan\left(\frac16\pi\right)}\right)\\
&= -\left(\frac{1 + \frac1{\sqrt3}}{1 - (1)\left(\frac1{\sqrt3}\right)}\right)\\
&= -2 - \sqrt 3.
\end{align}
I skipped several steps of the algebra that you would need to do to show the last equation in this chain of equations, but that at least is something you can solve without guessing.
You can also see similar approaches in
How to calculate $\arctan(\sqrt3-2)$ to be $-15°$ by hand?
(for $\arctan(-2 + \sqrt3)$ rather than $\arctan(-2 - \sqrt3),$
but these two things are closely related).
Another related question is How to find precise value in terms of $ \pi $.

A: There is! In complex analysis there is the following expression for the arctangent:
$$\arctan(x)=\frac{1}{2}i\text{Log}\left(\frac{1-xi}{1+xi}\right).$$
Now maybe the question remains: how to compute this logarithm? Let's look at your example:
$$
\text{Log}\left(\frac{1-(-2-\sqrt{3})i}{1+(-2-\sqrt{3})i}\right)=
$$
$$
\text{Log}\left({1-(-2-\sqrt{3})i}\right)-\text{Log}\left({1+(-2-\sqrt{3})i}\right)
$$
where
$$
\text{Log}\left({1-(-2-\sqrt{3})i}\right)=\ln|1-(-2-\sqrt{3})i|+i\text{Arg}(1-(-2-\sqrt{3})i).
$$
Here, $|\cdot|$ is de modulus which means $|a+bi|=(a+bi)(a-bi)=a^2+b^2$ and Arg is the angle in $[0,2\pi)$.


text:
Q: React Electron two window RDP server folder/app movement I was created 2 display/window in react electron... for now, I try to move app/folder in one screen to another screen... but it's not working...
enter image description here


text:
Q: Why does a decision variable domain declaration not work in Pyomo v5.7 that worked with v5.6.9 I have a decision variable declaration that does not work in Pyomo 5.7 that did work in 5.6.9.
The line in question is part of building a (concrete) model:
    model.v = pe.Var(within = pe.RealSet)    #pe = pyomo.environ

This ran fine when I had Pyomo version 5.6.9, but now gives errors described below in the provided code block.
To run with 5.7 I had to drop the within statement so I am left with:
    model.v = pe.Var()

What is the reasoning for no longer supporting an explicit statement that the domain includes all reals?
When running with the original statement with Pyomo 5.7, I get this error (CPython 3.7.1 on Windows 10):
    ERROR: Constructing component 'v' from data=None failed: TypeError: __new__()
    takes 1 positional argument but 2 were given
    Traceback (most recent call last):
      File "runscript.py", line 216, in <module>
        payoff_matrix = my_matrix
      File "C:\Users\myusername\Documents\modelbuildscript.py", line 24, in __init__
        model.v = pe.Var(within = pe.RealSet)
      File "C:\EngTools\Anaconda3\2018.12\lib\site-packages\pyomo\core\base\block.py", line 543, in __setattr__
        self.add_component(name, val)
      File "C:\EngTools\Anaconda3\2018.12\lib\site-packages\pyomo\core\base\block.py", line 1081, in add_component
        val.construct(data)
      File "C:\EngTools\Anaconda3\2018.12\lib\site-packages\pyomo\core\base\var.py", line 613, in construct
        self._initialize_members((None,))
      File "C:\EngTools\Anaconda3\2018.12\lib\site-packages\pyomo\core\base\var.py", line 682, in_initialize_members
        self.domain = self._domain_init_rule(self._parent())
    TypeError: __new__() takes 1 positional argument but 2 were given

A: The short answer is that you should use
model.v = pe.Var(within=pe.Reals)

The slightly longer answer is that the Pyomo global sets (Reals, NonNegativeReals, Integers, PositiveIntegers, Binary, etc.) were originally defined using their own class hierarchy independent of the Set and RangeSet components.  Unfortunately, that led to numerous problems (correctly detecting discrete sets, performing set operations using global sets, etc).  Pyomo 5.7 switched to a new rewrite of the Set / RangeSet components that among numerous other bug fixes moved to a new paradigm where all sets in Pyomo were either Set or RangeSet components (even global sets).  We put in a backwards compatibility layer that caught all the legacy uses of the RealSet class in the test suite, but your use case (while it worked) was not a documented / tested case.  PR 1619 will restore this functionality (likely will be included in Pyomo 5.7.1), and adds an official deprecation warning for use of RealSet.


text:
Q: Ubuntu 12.10 (32bit) System heatup I'm using HP envy 4
intel i5 3rd gen, 4GB ram, 2GB ATI Raedon 7670M graphics card.
freshly installed Ubuntu 12.10 (32bit) in my laptop used to turn off within 20 minutes due to overheating.
i followed up similar posts and installed an AMD graphics driver.
What is the correct way to install proprietary ATI Catalyst Video Drivers (fglrx) directly from AMD?
after following the above post i my system would turn off less often due to overheating, but whenever my system heated up, which it did roughly after half an hour, all my programs gets hanged.
what do i do??

A: Installing the ATI drivers is one thing but remember both graphics cards are still running together which is heating up your system so you need to switch one off to save heat and energy...  Try this link and see if any of the solutions work: http://mschoofs.blogspot.co.uk/2012/07/switch-off-ati-vga-in-hybrid-cards-with.html
Also, you could try a lighter desktop environment other than Unity to save on graphics card use, maybe Xubuntu (XFCE)...


text:
Q: Using ST_Transform when inserting new row? I have written a script which reads a CSV file with lat/lon coordinates in WGS84 and inserts them into a table in PostGIS.
What I want to do now is to change the insert query in order to make a transformation of the coordinates from WGS84 to another reference system.
My qyestion is if something like this is possible while inserting the data.
I was trying something like this but doesn't work:
   INSERT INTO imgRural(geom) VALUES (ST_Transform(ST_GeomFromText('POINT(23.771111111111 38.013888888889)', 2100)),2100) RETURNING imgId;

What am I missing here?

A: As John Barca said in his comment: I neglected to set the SRID before the transformation. This worked fine:
   INSERT INTO imgRural(geom) VALUES (ST_Transform
   (ST_GeomFromText('POINT(23.771111111111 38.013888888889)',4326),2100))
   RETURNING imgId;


text:
Q: jQuery Sticky Navigation Center during scrolling How can i set the width of the Navigation during scrolling. The Navigation fits 100% width during scrolling. If i set the width to 500px than its left:0 positioned. At left i cant set auto center the Navigation.
http://jsfiddle.net/aY8a7/
$(function() {

    var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;

    var sticky_navigation = function(){
        var scroll_top = $(window).scrollTop(); // our current vertical position from the top

        if (scroll_top > sticky_navigation_offset_top) {
            $('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
        } else {
            $('#navigation_menu').css({ 'position': 'relative' });
        }
    };

    sticky_navigation();

    $(window).scroll(function() {
         sticky_navigation();
    });

});

A: Try this: http://jsfiddle.net/aY8a7/1/
$(function() {

    var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;

    var sticky_navigation = function(){
        var scroll_top = $(window).scrollTop(); // our current vertical position from the top
        var $ul = $('#sticky_navigation ul').width()+'px';

        if (scroll_top > sticky_navigation_offset_top) {
            $('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 });
            $('#sticky_navigation ul').css({'width':$ul, 'display':'block', 'text-align':'center'});
        } else {
            $('#navigation_menu').css({ 'position': 'relative' });
        }
    };

    sticky_navigation();

    $(window).scroll(function() {
         sticky_navigation();
    });

});


text:
Q: Django: Sort articles by hourly/daily views (trending) Suppose we have a blog with 100 articles.
How can we let the users sort articles (objects) by the number of views (field) in the last hour/day/week/month?
Can we implement something that makes the field views_today such that it becomes 0 every hour?


text:
Q: sql in python functions I have tables as the following:
table1: name born country id
        A    1943  UK      3
        B    1966  USA     2...
table2: artist_id  artist_name formation
        3           The Beatles  1960
        2           The Door     USA

so i am struggling how to write the following function, can somebody give me an idea to start?
def band_by_country(sql_cursor,country):
'''(sqlite3.Cursor,str)->list of[]
return a list of bands representing all the bands who have at least one member who was born in that country.
>>>band_by_country(sql_cursor, UK)
['The Beatles']
>>>band_by_country(sql_cursor,USA)
['The Doors']
'''

A: Assuming your connection is setup already, the following should give you the "name" parameter from your table.
def band_by_country(sql_cursor,country):
    bands = []
    for row in sql_cursor.execute('SELECT name FROM table1 WHERE country=?', (country,)):
        bands.append( row[0] )
    return bands

If you want to join table1 with table2 it would look like this:
def band_by_country(sql_cursor,country):
    bands = []
    for row in sql_cursor.execute(
        "SELECT table2.artist_name FROM table1 JOIN table2 ON "
        "table1.id=table2.artist_id WHERE table1.country=?", (country,)):
        bands.append( row[0] )
    return bands


text:
Q: out of scope, the vector of pointers can delete the pointer's self occupied space? string *str=new string;

vector<string *> vector;

vector.push_back(str)

in brief, I want know when vector of pointers out of scope, is the pointer's self's occupied space freed?

A: Your question is a little unclear, but I guess, you want the strings to be allocated dynamically, yet automatically freed after the vector goes out of scope, right?
Vector will destroy only its contents when it is destroyed. That means, when the vector goes out of scope, it will destroy pointers held on its list, but it won't destroy objects pointed to by these pointers. So it may result in memory leak.
Actually, there are a few solutions to this problem. You can store instances of std::string instead of pointers to std::strings:
std::vector<std::string> strings;
strings.push_back("Alice has a cat");

When strings goes out of scope, all strings will be destroyed.
Another option is to use boost (in case you use C++ pre-11) or std (in case you use C++11) class called shared_ptr or unique_ptr. It behaves more less like a pointer, but when it goes out of scope, it destroys the contained object. So if you declare your list like this:
std::vector<std::shared_ptr<std::string>> strings;
std::push_back(std::make_shared<std::string>("Alice has a cat"));

String will be allocated dynamically, and be freed automatically (vector will free all shared_ptr's and if there are no more references to held strings than in these pointers, they will free strings as well).
Read further:

*

*http://www.parashift.com/c++-faq/container-of-smart-ptr.html

*http://msdn.microsoft.com/en-us/library/vstudio/hh279674.aspx


text:
Q: odd character in Linux file name I made a mistake and sent a filename to the server (through cloud API) which contains the scandinavian letter å. I forgot to URL encode it. It shouldn't have been there anyway. If I had spotted it I would have changed it to an a. You can't have scandinavian letters in Linux filenames, can you? Or?
Anyway, what happened was that an odd character turned up in the filename. When I list the file the API shows x\ufffdy.jpg instead of xåy.jpg, the filename I sent. When I list it in the GUI the odd character is displayed as a question mark inside a diamond.
Problem: To delete the file I need to know the exact filename. Alas, since I don't know which character Linux has put there instead of å I can't tell. All attempts fail. It even fails to delete it in the GUI. I managed however to upload an almost empty file with the same filename in the same way so that the file doesn't take up any space on the disk.
Never the less, I would like to have the file deleted. What can I do? To delete I need to send the filename in a json doc, where the character encoding is supposed to be utf8. So much coding and decoding, I am confused.


text:
Q: Implementing `concat` for `Cons a` I'm looking at an exercise to implement instance Monad []. However, I'd like to implement Monad Cons given the following definition:
data Cons a = Cons a (Cons a) | Empty
I attempted to implement the equivalent of concat, but I called it flatten:
flatten :: Cons (Cons a) -> Cons a
flatten Empty                  = Empty
flatten (Cons c@(Cons _ _) xs) = ...

But then I got confused about how [a] maps to Cons a (Cons a).
Please give me a hint to write the rest of flatten.

A: It is actually pretty simple. The concat function is usually defined as follows:
concat :: [[a]] -> [a]
concat = foldr (++) []

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ a []     = a
foldr f a (x:xs) = f x (foldr f a xs)

(++) :: [a] -> [a] -> [a]
[]     ++ ys = ys
(x:xs) ++ ys = x : xs ++ ys

Let's call the Cons version of these functions flatten, reduceR and append respectively:
flatten :: Cons (Cons a) -> Cons a
flatten = reduceR append Empty

reduceR :: (a -> b -> b) -> b -> Cons a -> b
reduceR _ a Empty       = a
reduceR f a (Cons x xs) = f x (reduceR f a xs)

append :: Cons a -> Cons a -> Cons a
append Empty       ys = ys
append (Cons x xs) ys = Cons x (append xs ys)

Unlike @jamshidh I used implemented a right fold instead of a left fold because the way (++) is implemented, a ++ (b ++ c) is less computationally expensive than (a ++ b) ++ c.
Now we can make Cons an instance of Monad as follows:
instance Functor Cons where
    fmap _ Empty       = Empty
    fmap f (Cons x xs) = Cons (f x) (fmap f xs)

instance Monad Cons where
    return a = Cons a Empty
    m >>= f = flatten (map f m)

Simple. Try making Cons an instance of Applicative and Alternative next.

A: Just to keep my brain from exploding, I would first define a function that combines two Cons a items
consPlus::Cons a->Cons a->Cons a
consPlus Empty x = x
consPlus (Cons x rest) y = Cons x (consPlus rest y)

Then I would define a Cons a version of foldl
consFoldl::(b->a->b)->b->Cons a->b
consFoldl f init Empty = init
consFoldl f init (Cons x rest) = consFoldl f (f init x) rest

then finally extend it to concat in the obvious way
consConcat = consFoldl consPlus Empty

Another brain-explosion-avoidance-technique would be to define Cons a like this
data Cons a = a ::: Cons a | Empty
infixr 8 :::

The difference is just syntax, but is is way easier to read this
(1:::2:::Empty):::(3:::Empty):::Empty

than this
Cons (Cons 1 (Cons 2 Empty)) (Cons (Cons 3 Empty) Empty)


text:
Q: why array.length showing false result.... with variable "name" i m just learning es 6 and i just socked when... i run this code..

var name = ["Rahul","Ritika","Amit","Radhika"];
  console.log(name.length);

the answer is 25.. 25 why?
it must have the answer 4 but gives 25 i don't know why?
i just run the code in browser console the answer is same... 25
but when i change the name of the variable name to something else like "c_name" it works fine...

let c_name = ["Rahul","Ritika","Amit","Radhika"];
  console.log(c_name.length);

when i m trying to execute this code the out is again miss behaving...

// with name varible let name = ["Rahul","Ritika","Amit","Radhika"];
  for(let i = 0 ; i < name.length; i++)   console.log(name[i]);

****output****
"Rahul"
"Ritika"
"Amit"
"Radhika"

// other variable let c_name = ["Rahul","Ritika","Amit","Radhika"];
  for(let i = 0 ; i < c_name.length; i++)   console.log(c_name[i]);
output

"R"
"a"
"h"
"u"
"l"
","
"R"
"i"
"t"
"i"
"k"
"a"
","
"A"
"m"
"i"
"t"
","
"R"
"a"
"d"
"h"
"i"
"k"
"a"

for loop
Output with name
Output with c_name

A: This is because name is a property on window object.
If you run your code other than the global scope, it will give you the correct result. The following code example shows that how to do that usingIIFE (Immediately Invoked Function Expression):

(function(){
  var name = ["Rahul","Ritika","Amit","Radhika"];
  console.log(name.length);
})();


text:
Q: Elastic Search Exact Match - wrong results I've done the following two searches according to tutorials and the official documentation from the ElasticSearch site but I'm getting more like a contains result other than an exact match.
I'm very new to ES so excuse any noob mistakes.
Any help would be appreciated.
According to the tutorials I've gone through so far this is not the case with their results. So I'm quite confused as to why I am getting the results I am.
Data Structure:
{
    "_scroll_id": "cXVlcnlBbmRGZXRjaDsxOzI3OlRsWmVmMGh5VENLR0FVclB3eXpIaVE7MDs=",
    "took": 7,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "failed": 0
    },
    "hits": {
        "total": 16896,
        "max_score": 1,
        "hits": [
            {
                "_index": "cus_index",
                "_type": "place",
                "_id": "71272349",
                "_score": 1,
                "_source": {
                    "id": 34543,
                    "date1": "1928-09-13 00:00:00",
                    "date2": "1929-01-01 00:00:00",
                    "code": "1000",
                    "phrase": "GOD MODE",
                    "boolCol": false
                }
            },
            {
                "_index": "cus_index",
                "_type": "place",
                "_id": "71272349",
                "_score": 1,
                "_source": {
                    "id": 78635,
                    "date1": "1928-09-13 00:00:00",
                    "date2": "1929-01-01 00:00:00",
                    "code": "3000",
                    "phrase": "THANK GOD",
                    "boolCol": false
                }
            },
            {
                "_index": "cus_index",
                "_type": "place",
                "_id": "71272349",
                "_score": 1,
                "_source": {
                    "id": 45645,
                    "date1": "1928-09-13 00:00:00",
                    "date2": "1929-01-01 00:00:00",
                    "code": "5000",
                    "phrase": "SOME OTHER GOD PHRASE",
                    "boolCol": false
                }
            },
        ]
    }
}

Queries:
// returns all rows
{
    "query" : {
        "constant_score" : {
            "filter" : {
                "match" : {
                    "phrase": "GOD MODE"
                }
            }
        }
    }
}

// this returns all rows
{
    "query" : {
        "query_string": {
            "query": "GOD MODE",
            "fields": ["phrase"]
        }
    }
}

// this returns no rows
{
    "query" : {
        "term": {
            "phrase": "GOD MODE"
        }
    }
}

Mappings:
{
    "cus_index": {
        "aliases": {},
        "mappings": {
            "place": {
                "properties": {
                    "id": {
                        "type": "int"
                    },
                    "date1": {
                        "type": "date"
                    },
                    "date2": {
                        "type": "date"
                    },
                    "code": {
                        "type": "string"
                    },
                    // this is the important one
                    // i just guessed the others as this is an example, But the col in qu is a string
                    "phrase": {
                        "type": "string"
                    },
                    "boolCol": {
                        "type": "boolean"
                    }
                }
            }
        },
        "settings": {
            "index": {
                "creation_date": "1545321229864",
                "number_of_shards": "1",
                "number_of_replicas": "0",
                "uuid": "4PpzZ49SQZWDDW8sawOIaA",
                "version": {
                    "created": "2030199"
                }
            }
        },
        "warmers": {}
    }
}

ES Version:
{
    "name": "Test Node",
    "cluster_name": "firsttestnode",
    "version": {
        // this was a very old version latest "6.5.4" this is what i
        // should have been using for the answers below to work.
        "number": "2.3.1",
        "build_hash": "bd980929010aef404e7cb0843e61d0665269fc39",
        "build_timestamp": "2016-04-04T12:25:05Z",
        "build_snapshot": false,
        "lucene_version": "5.5.0"
    },
    "tagline": "Test tag line"
}

---------------------- Answer Attempts -----------------------------------
I PUT and POST to the following body to the given Url below and got the following errors:
// URL: http://ip_address:9200/test_index1

{
  "mappings": {
    "demo":{
       "properties": {
          "phrase": {
            "type": "string"
          },
          "phrase1": {
            "type": "keyword"
          }
       }
    }
  }
}

// errors
{
    "error": {
        "root_cause": [
            {
                "type": "mapper_parsing_exception",
                "reason": "No handler for type [keyword] declared on field [phrase1]"
            }
        ],
        "type": "mapper_parsing_exception",
        "reason": "Failed to parse mapping [demo]: No handler for type [keyword] declared on field [phrase1]",
        "caused_by": {
            "type": "mapper_parsing_exception",
            "reason": "No handler for type [keyword] declared on field [phrase1]"
        }
    },
    "status": 400
}

both of the answers below are working as expected.
Thanks to both. Not really sure to answer correct, But to other reading this I would recommend both.
Only thing is in answer 1 the '"type": "string"' should be '"type": "text"' for the example to just work.

A: The term query finds documents that contain the exact term specified in the inverted index.
TL;DR:
Example:
PUT test_index1
{
  "mappings": {
    "demo":{
       "properties": {
          "phrase": {
            "type": "string"
          },
          "phrase1": {
            "type": "keyword"
          }
       }
    }
  }
}

POST test_index1/demo/1
{
  "phrase":"GOOD GOD",
  "phrase1":"GOOD GOD"
}

GET  test_index1/_search
{
  "query": {
    "match": {
      "phrase": "GOOD"
    }
  }
}

above returned result
GET  test_index1/_search
{
  "query": {
    "term": {
      "phrase1": "GOOD"
    }
  }
}

above does not return result
You can even use _analyze
GET  test_index1/_analyze
{
  "field": "phrase",
  "text": ["GOOD GOD"]
}

to see how the the documented is stored in inverted index.
To answer your question:
Term query look for exact match.Since your phrase type is String, The word GOD MODE is stored as GOD and MODE, where the term query will do exact match with GOD MODE. Either you have to change it to Keyword or use match query

A: I would suggest to update the phrase property as below:
"phrase": {
   "type": "text",
   "fields": {
      "keyword": {
         "type": "keyword"
      }
   }
}

In the above case when indexing document you only need to pass the value to phrase field and phrase.keyword gets auto-indexed.
Whenever you want to do exact match you can use term query as below:
{
   "term": {
      "phrase.keyword": "some text"
   }
}


text:
Q: iCal sending decline e-mails when it purges old calendar entries I have iCal version 4.0.4.  I have enabled the "Delete events 30 days after they have passed" preference option.  When iCal purges these events, it is sending a decline e-mail to the event organizer.
Is there a way to stop iCal from sending decline e-mails when it automatically purges calendar entries?

A: I turned off my internet connection. Declined(works for Accept as well) the invites in iCal.
iCal sends the messages to your email client. I deleted them from the Mail/Outbox manually.
Then I turned the wifi card back on.
Done.

A: Turn off automatically retrieve invitations from mail if you don't intend to handle them sooner manually.
Once the invitation is in iCal - it's job is to send a decline message when it gets declined or deleted. There is no easy way to delete the notification or temporarily ask mail to not send mail before the purge happens.
Just wait until Mobile Me changes again and all your old accepted invitations get an email that you are again accepting their past invitations. ;-)


text: Q: How can I recover a Jupyter notebook? So I was working on a jupyter notebook and after I was done, I just closed the tab and then when I checked in the folder on my system, the file just wasn't there. I lost all my work. The checkpoints folder has a file where there's some stuff written that I don't really understand. Can somebody help me? I don't know if it was auto-saving or not, it usually does. I've never encountered such problem before. Any help would be appreciated.


text:
Q: "Content not available for this message" error in Gmail add-ons This is my Code.gs and I've created Index.html file
function buildAddOn(e) {
    var template = HtmlService.createTemplateFromFile('Index')
    var html = template.evaluate().setTitle('Title');

    var htmlOutput = HtmlService.createHtmlOutput(html);
    htmlOutput.addMetaTag('viewport', 'width=device-width, initial-scale=1');
    return htmlOutput;
}

This is my appsscripts.json file
{
    "oauthScopes": [
        "https://www.googleapis.com/auth/gmail.addons.execute",
        "https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
        "https://www.googleapis.com/auth/gmail.modify"
    ],
    "gmail": {
        "name": "Gmail Add-on Quickstart - QuickLabels",
        "logoUrl": "https://www.gstatic.com/images/icons/material/system/1x/label_googblue_24dp.png",
        "contextualTriggers": [
        {
            "unconditional": {},
            "onTriggerFunction": "buildAddOn"
        }
        ],
        "openLinkUrlPrefixes": ["https://mail.google.com/"],
        "primaryColor": "#4285F4",
        "secondaryColor": "#4285F4"
    },
    "exceptionLogging": "STACKDRIVER",
    "runtimeVersion": "V8"
}

I'm getting same error in popup screen for all emails
I tried returning without addMetaTag but it's not working


text:
Q: OpenCV : Training SVM Error - Assertion failed Im writing program to classify objects using SVM and BoW. I am getting the following error when I try use the TrainData::create() member function to create the data necessary to train SVM classifier.

OpenCV Error: Assertion failed (responses.type() == CV_32F || responses.type() == CV_32S) in setData

This is my function to read the train data from a director, compute BoW histogram for each train image, create a matrix of all descriptors of all train images in a matrix and the create the train data, labels and then train the SVM
void trainClassifier(string dictionaryPath, string trainDataPath, string saveClassifierPath, int samples){

//Write file
FileStorage readFile(dictionaryPath, FileStorage::READ);

//Load into Dictionary matrix
readFile["Data"] >> dictionary;

if(dictionary.empty() == false)
{
    cout << "Error loading visual vocalbulary" << endl;
}

//Set the Bow descripter with the dictionary
testBOW.setVocabulary(dictionary);

//Inititate variables
vector<KeyPoint> keypointTrain;
vector<DMatch> matchTrain;
Mat descriptorTrain;

//inputTrain -> input images, inputFeatures -> BoW descriptor output
Mat inputTrain;
Mat inputFeatures;

//Label array
vector<string> label;

//Create a string to read files from directory
string updatedDataPath;

for(int i = 1; i <= samples; i++)
{
    //Update the string updateDataPath to correspond the image FILENAME with each iteration
    updatedDataPath.append(trainDataPath);
    updatedDataPath += to_string(i);
    updatedDataPath.append(".JPEG");

    //Read FILE from the updated datapath
    inputTrain = imread(updatedDataPath);

    //Convert to single channel, since classifier takes only single channel data
    cvtColor(inputTrain, inputTrain, CV_BGR2GRAY);

    //Generate BoW features/histogram for the train image
    testBOW.compute(inputTrain, keypointTrain, inputFeatures);

    //Load the data in the descriptor Matrix
    descriptorTrain.push_back(inputFeatures);

    //Generate label according to the sample
    if(samples > 1 && samples <= 10)
    {
        label.push_back("OBJ1 POSSITIVE");
    }
    else if (samples > 11 && samples <= 20)
    {
        label.push_back("OBJ1 NEGATIVE");
    }

    //Reset data path
    updatedDataPath.clear();
}

//Convert the descriptor matrix into 32-pt float to make it compatible with classifier
if(descriptorTrain.type() != CV_32F)
{
    descriptorTrain.convertTo(descriptorTrain, CV_32F);
}

//Create train data using TrainData::create()
Ptr<TrainData> trainData = TrainData::create(descriptorTrain, ROW_SAMPLE, label);
//Iniitialize Support vector based classifier (SVM) to classify and detect object
Ptr<SVM>SVM = SVM::create();
SVM->setType(SVM::C_SVC);
SVM->setKernel(SVM::LINEAR);
SVM->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));

//Now train the SVM
SVM->trainAuto(trainData);
SVM->save(saveClassifierPath);

cout << "Classifier training status: SUCCESSFUL" << endl;}

Any help is appreciated. Thanks and cheers :)

A: You are using a vector<string> as the TrainData responses.
//Label array
vector<string> label;

// [long code]

//Create train data using TrainData::create()
Ptr<TrainData> trainData = TrainData::create(descriptorTrain, ROW_SAMPLE, label);

And it shoud be a Mat CV_32F or CV_32S, as the error says.
You can confirm that at:

*

*documentation: TrainData::create(...)

*source-code: TrainData::create(...) that calls  setData(...)


text:
Q: The contact's email should be auto populated in custom 'Email' field <aura:component implements="force:lightningQuickAction" controller="sendEmailController">
    <aura:attribute name="email" type="string"/>
    <aura:attribute name="subject" type="string"/>
    <aura:attribute name="body" type="string"/>
    <aura:attribute name="mailStatus" type="boolean" default="false"/>

    <aura:if isTrue="{!v.mailStatus}">

Mail Status

Email Sent successfully to {!v.email}

                    <button class="slds-button slds-button--brand" onclick="{!c.closeMessage}">Close</button>

    </aura:if>

                    Email

                        <ui:inputEmail class="slds-input" aura:id="email"  value="{!v.email}" required="true" />

                    Subject

                        <ui:inputText class="slds-input" aura:id="subject"  value="{!v.subject}" />

                    Mail Body

                        <lightning:inputRichText aura:id="body" value="{!v.body}" />

                    <button class="slds-button slds-button--brand" onclick="{!c.sendMail}">Send</button>

</aura:component>

({
    sendMail: function(component, event, helper) {

        var getEmail = component.get("v.email");
        var getSubject = component.get("v.subject");
        var getbody = component.get("v.body");

        if ($A.util.isEmpty(getEmail) || !getEmail.includes("@")) { // condition to check whether id is null and does not contain '@'
            alert('Please Enter valid Email Address'); // display alert message
        } else {
            helper.sendHelper(component, getEmail, getSubject, getbody);
        }
    },

    closeMessage: function(component, event, helper) {//when closing the message, update every fields to null.
        component.set("v.mailStatus", false);
        component.set("v.email", null);
        component.set("v.subject", null);
        component.set("v.body", null);
    },

})

public class sendEmailController {
    @AuraEnabled
    public static void sendMailMethod(String mMail ,String mSubject ,String mbody){

        List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        List<String> sendTo = new List<String>();
        sendTo.add(mMail);
        mail.setToAddresses(sendTo);
        mail.setReplyTo('iswarya.sekar@excelenciaconsulting.com');
        mail.setSenderDisplayName('Iswarya Sekar');
        mail.setSubject(mSubject);
        mail.setHtmlBody(mbody);
        mails.add(mail);
        Messaging.sendEmail(mails);
    }
}

({
    sendHelper: function(component, getEmail, getSubject, getbody) {
        // call the server side controller method
        var action = component.get("c.sendMailMethod"); //calls server side controller

        action.setParams({ //Used to set data to be passed to the server-side controller
            'mMail': getEmail,
            'mSubject': getSubject,
            'mbody': getbody
        });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") { //if state is success, displays success message
                var storeResponse = response.getReturnValue();
                component.set("v.mailStatus", true);
            }

        });
        $A.enqueueAction(action); //adds server side actions to queue.
    },
})

A: As this action is on contact record so first add the interface in your component
<aura:component controller="sendEmailController"
    implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">

    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

Now in your controller Init method Call the Apex controller and return the email using Contact Id
({
    doInit : function(component, event, helper) {

        // Prepare the action to load account record
        var action = component.get("c.getContactEmail");
        action.setParams({"contactId": component.get("v.recordId")});

        // Configure response handler
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                component.set("v.email", response.getReturnValue());
            } else {
                console.log('Problem getting account, response state: ' + state);
            }
        });
        $A.enqueueAction(action);
    },

In case you need Here's controller method
 @AuraEnabled
 public static String getContactEmail(Id contactId) {
      // Perform isAccessible() checks here
      return [SELECT Email FROM Contact WHERE Id = :contactId LIMIT 1].Email;
  }

Configure Components for Record-Specific Actions
Also you can use Lightning Data service and can load the record details without using Apex and can get the email from record.


text:
Q: How to trace/log call to each functions in my program? I would like to log in a file all procedure call in my program. Of course I can edit myself each procedure and add in it something like
  procedure sample;
  begin
    LogToFile('Enter in procedure sample');
    .....
   end;

But off course I would like to do it automatically. Is their any way to do this ?


text:
Q: How to handle OS signal in a python program? I am writing a python program which reads from a queue through a infinite while loop. How can I handle signal sent by OS / Keyboard interrupt(CTRL+C) to break from the while loop and close active connections and files and exit the program gracefully instead of killing the process.
while True:
    read_from_file_and_do_something()
    ## Handle a signal of shutdown here.
    ## Send email before exiting.

This program will run as a daemon. Thus would require a signal to be sent.

A: I think signal module is what you are looking for,
def handler(signum, frame):
    print 'Signal handler called with signal', signum

signal.signal(signal.SIGABRT, handler)


text:
Q: How to read a Subdirectory from External Storage with getExternalStorageDirectory() I am developing an Android app that should read Files from the External Storage and display them in a Listview; creating the subdirectory on the External Storage works fine. The problem is reading from the Subdirectory of the External Storage and I still haven´t figured out how to solve this problem. The Listview displays all the subdirectories of the External Storage and I just want to display the content in one particular subdirectory. The problem consists in "casting" a String into a File Object, which is obviously not possible. Do I really need to open a FileInputStream for that? Any help or hints would be very much appreciated.
I tried to attach the subdirectory as a string to the Environment.getExternalStorageDirectory() method, lik this:
Environment.getExternalStorageDirectory() + "/Audio";
mTextMessage = findViewById(R.id.message);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener
(mOnNavigationItemSelectedListener);
mListView = (ListView) findViewById(R.id.listView1);
file = Environment.getExternalStorageDirectory() + "/Audio";
fileNameList = getFileListfromSDCard();
mAdapter = new FlAdapter(this, R.layout.fl_list_item, fileNameList);
mListView.setAdapter(mAdapter);

The error message:
error: incompatible types: String cannot be converted to File

A: Because getExternalStorageDirectory() returns String, you need to convert it to file before assigning it to file.
You can try like this.
File file = new File(Environment.getExternalStorageDirectory()+"/Audio");


text:
Q: Pattern creation of collectibles - LibGdx I am working on a LibGdx running game.I have collectibles/coins in the game.
I have created a coin array,and spawned it throughout the game.
To improve the play,I want to make patterns of coins.Like 2 coins or 3 coins together , coins in vertical or diagonal arrangements etc.
I tried to implement this,but found it a difficult task as a fresher.
Please suggest me some code to implement patterns like triangle with an array of objects.
Like this:triangle with 3 coins in equal distance:

My coin array and method are included here:
I am adding new coins on the basis of last coin passes a particular distance on the screen.
Array<Coin> coins = new Array<Coin>();

private void createCoin() {

    coinObj = objectFactory.createCoin(CoinEnum.random());
    coinObj.isCollided = false;
    coins.add(coinObj);

}

private void spawnCoin() {

    if (coins.size == 0) {
        createCoin();
    } else {
        Coin c = coins.peek();

        if (c.getY() > (Constants.WORLD_HEIGHT / 8))
            createCoin();
    }
    // remove out of screen coins
    if (coins.size > 0) {
        Coin cc = coins.first();
        if (cc.getY() > Constants.WORLD_HEIGHT) {
            coins.removeValue(cc, true);
        }
    }
}

Also hope someone can tell me the mistakes in my approach if any!
Thanks in advance!

A: First of all, try to model the CoinPattern:
- What is a CoinPattern?
It is just a pattern, describing an arrangement of multiple coins.
- What do I need to describe it?
As it is just a pattern, you don't need no Coins yet.
In my opinion, a list of Points (or Vector2) should be enough.
Each of these Points could describe the relative Position of the Object (in your case Coin) inside the Pattern.
Now you could create constants for your Patterns. The triangle could look something like this:
public static final PATTERN_TRIANGLE = new Vector2[] {
    new Vector2(0,0),
    new Vector2(1,0),
    new Vector2(0,1),
};

Then you could create a method spawnPattern(Vector2[] pattern, int x, int y). This method should then create a Coin for every Vector2 in the pattern.
The position of each Coin could be calculated like this:
int posX = x + pattern[i].x;
int posY = y + pattern[i].y;

Note, that using this methode, the positions of the Coins are relative to the lower, left corner of the Pattern position.


text:
Q: Apache Redirect all to index.php with https I have read many answers on the subject but none is mentionning how to combine :
redirecting all traffic to index.php + redirect all http to httpS
the following works great for redirecting all to index.php :
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|public|css|js|robots\.txt)
RewriteRule ^(.*) index.php/params=$1 [L,QSA]

before I was doing this I was able to force http to https using this :
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

I just cannot find a way to mix both, so that It would redirect all traffic to index.php using the same conditions and force https.
* edit *
in case somebody else gets confused like I did.
The reason why https was systematically returning a 404 when I was calling rewritten urls is because... My domain configuration file was incomplete, my website-ssl.conf was missing the AllowOverride All directive, this is why it was all working fine until I added the url rewriting. My non-ssl was correctly setup for url-rewriting so this is why it took me a little while to realise this was not working when https.
I have then added the necessary in my /etc/apache2website-ssl.conf
<Directory /var/www/vhosts/exemple.com>
    Options -Indexes +FollowSymLinks +MultiViews
    AllowOverride All
    Require all granted
</Directory>

and this in my .htaccess
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://exemple.com/$1 [R,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|public|css|js|robots\.txt)
RewriteRule ^(.*) index.php/params=$1 [L,QSA]
ErrorDocument 404 /index.php

I hope that'll help somebody.
Thank you for your help

A: Just keep the https redirection rule above other rules :
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [NC,L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|public|css|js|robots\.txt)
RewriteRule ^(.*) index.php/params=$1 [L,QSA]

A: <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}/index.php
</IfModule>

So in the above case, if user is going to http link, both(re-write to https and forward to index.php) will happen (i tried and its working). but if user is going to https directly, then you should have simple rewriting to index.php in your default-ssl


text:
Q: How to edit the views list of a SharePoint list view? I have a question regarding SharePoint list views. When I visit a SharePoint List, I can see the rest of the SharePoint views as like the below screen capture.

I want to know, is there a way to change the order of this list of views in horizontally?
Please guide me to solve this.
Thanks and regards,
Chiranthaka

A: I think they are in alphabetical order so if you name them '1. All Items' '2 In Progress', 3. Date difference' you should be able to control the sequence.

A: By default, the views will be sorted alphabetically in the toolbar of the list view and in the ribbon.
To change the order of list views, you can use JS Link in web part properties. Please find the below steps:
1.Save the below script as ListOrder.js and upload it to Site Assets(or Master page Gallery)
2.Refer it in JS Link as ~site/SiteAssets/ListOrder.js for the specific view in a list.
3.specify your view names in the "viewNames" array.
(function () {
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
      'Templates': {
        'Header': renderHeaderTemplateForDocuments
      }
    });

    // enter all views here in the desired display order
    var viewNames = ['Slides', 'All Pictures', 'Thumbnails', 'Modify this View', 'Create View'];

    function renderHeaderTemplateForDocuments(renderCtx, fRenderHeaderColumnNames){
        var viewData = eval(renderCtx.ListSchema.ViewSelectorPivotMenuOptions);
        // update with an integer to specify the number of displayed views
        ClientPivotControl.prototype.SurfacedPivotCount = viewData.length;   //display ALL available menu options
        viewData.sort(compareMenuOptions);  //sort menu options in order specified in the array
        renderCtx.ListSchema.ViewSelectorPivotMenuOptions = JSON.stringify(viewData);
        return RenderHeaderTemplate(renderCtx, fRenderHeaderColumnNames); //render Header template
    }

    function compareMenuOptions(a,b) {
        if(a.DisplayText != undefined && b.DisplayText != undefined){
               var x = viewNames.indexOf(a.DisplayText);
               var y = viewNames.indexOf(b.DisplayText)
              if (x > y)
                return 1;
              if (x < y)
                return -1;
        }
      return 0;
    }
})();

NOTE: Order will be applied only to the view to which JS Link is referred.
For more detailed information, refer to the following similar issue posts:
https://social.msdn.microsoft.com/Forums/office/en-US/46eae1f3-947e-468d-a842-41089444f9de/how-do-i-change-the-displayed-view-order-for-a-list-in-sharepoint-2013?forum=sharepointdevelopment
How do I change the displayed view order for a list in SharePoint 2013?


text:
Q: Three phase power supply for test purposes I work in the electrical industry and deal with mainly three phase power.
I'm trying to broaden my knowledge of scopes and power quality and the only time I really have to do this is at work and that then is of course very limited as I have constant projects on the go.
That leaves home........I've decided not to use a VFD as the output isn't great, (I want a pure sine wave as a starting point), and a generator is too noisy.
What I thought was to use a single phase motor connected by a belt to a star connected 3 phase alternator/permanent magnet motor.
The output, (three phases and neutral), will be connected across a CATIII oscilloscope and at times possibly a dummy load together.
What raises my eyebrows is safety. Whilst the 'system output' will not be connected electrically in any way to the electrics in the house, I'll be generating a sort of floating supply so the usual protections might apply in a different way or not at all?
I'd appreciate your comments, thanks.


text:
Q: Objective C Using NSScanner to obtain  from html I am trying to create an iOS app simply to extract the  section of a web page.
I have the code working to connect to the URL and store the HTML in an NSString
I have tried this, but I am just getting null strings for my result
    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    // Create a new scanner and give it the html data to parse.

    while (![newScanner isAtEnd])
    {
        [newScanner scanUpToString:@"" intoString:NULL];
        // Scam until  tag is found

        [newScanner scanUpToString:@"" intoString:&bodyText];
        // Everything up to the end tag will get placed into the memory address of the result string

    }

I have tried an alternative way...
    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    // Create a new scanner and give it the html data to parse.

    while (![newScanner isAtEnd])
    {
        [newScanner scanUpToString:@"<body" intoString:NULL];
        // Scam until  tag is found

        [newScanner scanUpToString:@">" intoString:NULL];
        // Go to end of opening  tag

        [newScanner scanUpToString:@"" intoString:&bodyText];
        // Everything up to the end tag will get placed into the memory address of the result string

    }

This second way returns a string which starts with >< script... etc
If Im honest I don't have a good URL to test this with and I think It may be easier with some help on removing the tags within the body too (like

)
Any help would be very much appriciated

A: I don't know why your first method didn't work. I assume you defined bodyText before that snippet. This code worked fine for me,
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *htmlData = @"This is some stuff before  this is the body  with some more stuff";
    NSScanner* newScanner = [NSScanner scannerWithString:htmlData];
    NSString *bodyText;
    while (![newScanner isAtEnd]) {
        [newScanner scanUpToString:@"" intoString:NULL];
        [newScanner scanString:@"" intoString:NULL];
        [newScanner scanUpToString:@"" intoString:&bodyText];
    }
    NSLog(@"%@",bodyText); // 2015-01-28 15:58:00.360 ScanningOfHTMLProblem[1373:661934] this is the body
}

Notice that I added a call to scanString:intoString: to get past the first "".


text:
Q: Can't get a simple divide select statement to work in SQLite I have a the following code
SELECT DISTINCT M.First_Name || ' ' || M.Surname AS Manager,
                SUM(CASE WHEN MC.Team = F.Home_Team AND
                              MC.Start_Date <= F.Date AND
                              MC.End_Date >= F.Date THEN 1 WHEN MC.Team = F.Away_Team AND
                                                                MC.Start_Date <= F.Date AND
                                                                MC.End_Date >= F.Date THEN 1 ELSE 0 END) AS Games,
                SUM(CASE WHEN S.HTFT > S.ATFT AND
                              F.Home_Team = 48 AND
                              MC.Start_Date <= F.Date AND
                              MC.End_Date >= F.Date THEN 3 WHEN S.ATFT > S.HTFT AND
                                                                F.Away_Team = 48 AND
                                                                MC.Start_Date <= F.Date AND
                                                                MC.End_Date >= F.Date THEN 3 WHEN S.HTFT = S.ATFT AND
                                                                                MC.Start_Date <= F.Date AND
                                                                                MC.End_Date >= F.Date THEN 1 ELSE 0 END) AS Points,
                (SUM(1.0 * CASE WHEN S.HTFT > S.ATFT AND
                                     F.Home_Team = 48 AND
                                     MC.Start_Date <= F.Date AND
                                     MC.End_Date >= F.Date THEN 3 WHEN S.ATFT > S.HTFT AND
                                                                       F.Away_Team = 48 AND
                                                                       MC.Start_Date <= F.Date AND
                                                                       MC.End_Date >= F.Date THEN 3 WHEN S.HTFT = S.ATFT AND
                                                                                MC.Start_Date <= F.Date AND
                                                                                MC.End_Date >= F.Date THEN 1 ELSE 0 END) / SUM(CASE WHEN MC.Team = F.Home_Team AND
                                                                                MC.Start_Date <= F.Date AND
                                                                                MC.End_Date >= F.Date THEN 1 WHEN MC.Team = F.Away_Team AND
                                                                                MC.Start_Date <= F.Date AND
                                                                                MC.End_Date >= F.Date THEN 1 ELSE 0 END) ) AS PPG
  FROM Manager AS M
       LEFT JOIN
       Manager_Contract AS MC ON M.ID = MC.Manager
       LEFT JOIN
       Fixture AS F ON MC.Team = F.Home_Team OR
                       MC.Team = F.Away_Team
       LEFT JOIN
       Score AS S ON F.ID = S.Fixture
 GROUP BY M.First_Name || ' ' || M.Surname
HAVING Games > 0
 ORDER BY MC.Start_Date ASC;

Which returns

Manager
Games
Points
PPG

Ben Garner
10
12
1.2

Paul Tisdale
15
12
0.8

Tommy Widdrington
3
3
1

Joey Barton
18
11
0.61111

The last column I want to return

PPG

1.20

0.80

1.00

0.61

Every time I try to add ROUND in I get an error message - Usually Row value misused.
Any help appreciated.
I am using SQLite Studio and MacBook Pro.
QUESTION EDITED - Managed to fix initial issue.

A: The error message:

Row value misused

is often the result of incorrect usage of parentheses and this may happen because your code contains many conditions in all the branches of the CASE expressions.
I think that you can simplify the code.
The condition in the HAVING clause:
HAVING Games > 0

will filter out any managers for which this CASE expression:
CASE
  WHEN MC.Team = F.Home_Team
   AND MC.Start_Date <= F.Date
   AND MC.End_Date >= F.Date THEN 1
  WHEN MC.Team = F.Away_Team
   AND MC.Start_Date <= F.Date
   AND MC.End_Date >= F.Date THEN 1
  ELSE 0
END

is always 0.
So, why don't you set a WHERE clause, equivalent to the above conditions?
Also, this makes the first 2 LEFT joins actually INNER joins (and I'm not sure if the last join should be a LEFT join).
Try this simplified code:
SELECT M.First_Name || ' ' || M.Surname AS Manager,
       COUNT(*) AS Games,
       SUM(
         CASE
           WHEN (S.HTFT > S.ATFT AND F.Home_Team = 48) OR (S.ATFT > S.HTFT AND F.Away_Team = 48) THEN 3
           WHEN S.HTFT = S.ATFT THEN 1
           ELSE 0
         END
       ) AS Points,
       ROUND(
         1.0 *
         SUM(
           CASE
             WHEN (S.HTFT > S.ATFT AND F.Home_Team = 48) OR (S.ATFT > S.HTFT AND F.Away_Team = 48) THEN 3
             WHEN S.HTFT = S.ATFT THEN 1
             ELSE 0
           END
         ) /
         COUNT(*)
         , 2
       ) AS PPG
FROM Manager AS M
INNER JOIN manager_Contract AS MC ON M.ID = MC.Manager
INNER JOIN Fixture AS F ON MC.Team IN (F.Home_Team, F.Away_Team)
LEFT JOIN Score AS S ON F.ID = S.Fixture
WHERE MC.Start_Date <= F.Date AND MC.End_Date >= F.Date
GROUP BY Manager;