Q:

Find the point minimizing the distance from a set of N lines

Given Multiple (N) lines in 3d space, find the point minimizing the distance to all lines.

Given that the Shortest distance between a line [aX + b] and a point [P] will be on the perpendicular line [aX+b]–[P] I can express the minimal squared distance as the sum of squared line distances, eg. ([aX+b]–[P])^2 +…+ ([aX+b]n–[P])^2 .
Since the lines are perpendicular I can use Dot Product to express [P] in the line terms

I have considered using Least Squares for estimating the point minimizing the distance, the problem is that the standard least squares will approximate the best fitting line/curve given a set of points, What I need is the opposite, given a set of lines estimate the best fitting point.
How should this be approached ?

A:

From wikipedia, we read that the squared distance between line a'x + b = 0 and point p is (a'p+b)^2 / (a'a). We can therefore see that the point that minimizes the sum of squared distances is a weighted linear regression problem with one observation for each line. The regression model has the following properties:

Sample data a for each line ax+b=0
Sample outcome -b for each line ax+b=0
Sample weight 1/(a'a) for each line ax+b=0

You should be able to solve this problem with any standard statistical software.


Q:

How to select * from table but distinct on 1 column and order by on another column

I have a messages table with fields channel_number, body, created_at, recipeint_id & sender_id I want to have messages distinct on channel_number and order by messages.created_at
basically I want to show all channels in paginations and channels with latest message will be at top. This is what I've tried:
SELECT *
FROM messages
where id IN ( (SELECT channel_number, MIN(id) AS messages_id
               FROM messages
               GROUP BY channel_number
              ) as a
           ) a.messages_id
ORDER BY a.messages_id DESC;

I have been working on this for a couple of hours and made many queries but it didn't work because in results I need all fields of message instead of selected channel and id.
Edits - I am using postgres and there is no uniq constrain on channle_number in messages table

A:

This worked good for me
SELECT *
FROM messages
where (channel_number, id) IN (select channel_number, MIN(id) AS last_message_id
                                FROM "messages"
                                WHERE (sender_id = 3 OR recipient_id =2)
                               )
GROUP BY "messages"."channel_number"
ORDER BY created_at DESC


Q:

Why does this codeigniter .htaccess file work

I have a codeigniter website which has a broken link structure. The initial page loads normally. My Navbar looks like:
myproject

Home

Facts

About

Contact

I've tested it locally with the following .htaccess file in the root directory:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

This appears to fix the directory structure (I assumed) by turning:
http://localhost/projectname/basecontroller/contact

into:
http://localhost/projectname/index.php/basecontroller/contact

as I look at it more closely I would have thought that it would create:
 http://localhost/index.php/projectname/basecontroller/contact

which should not work, but it is working! Can someone explain this?

A:

.htaccess works from the current directory. If your project is located in /projectname, then the .htaccess rules will be applied assuming this folder as root.
This means, the server is oblivious to the over all directory hierarchy of the server. If you place the .htaccess in /dir1 it will not have the same effect as if it was placed in /dir2, but will instead just be applied to the respective directory.
If you want a .htaccess to work from the root of the server, you must place the file in the actual server root.


Q:

empty() check not validating after POST

I'm setting a session variable in my header.php here:
<?php

session_start();

if(empty($_SESSION['name'])) {
    ?>
    No name set!

    <form action="" method="post">
        <input type="text" name="textName"/>
        <input type="submit" name="submitName" value="Log in"/>
    </form>

    <?php
    if(isset($_POST['submitName'])) {
        $_SESSION['name'] = $_POST['textName'];

    }
}

and validating that the name variable is set on my index here:
<?php

include 'header.php';

if(!empty($_SESSION['name'])){
    ?>
Log out
<?php
}

?>

I can confirm that the session variable exists because the logout link appears.
After submitting a name via the form, the session variable updates but the empty() check doesn't reoccur, meaning the textarea stays on the page unless I refresh.
Can anyone tell me why this happens?

A:

Take this part:
if(isset($_POST['submitName'])) {
    $_SESSION['name'] = $_POST['textName'];

}

above this:
if(empty($_SESSION['name'])) {}

When you submit the form, at the beginning; since the session is empty and hence the form remains there and then the session is initialized. And when you refresh the page the session check works.


Q:

Can I put a second layer of caulk over newly installed caulk to fill a gap?

My bathroom backsplash-to-wall junction was just re-caulked yesterday. (The old caulk was discolored and showing signs of mold.) But on one side of the countertop where there's a 3/8" gap between wall and backsplash, the new caulk was applied at a slightly lower level than the top of the backsplash, meaning there's a small area where water will pool on top of the caulk instead of draining back down onto the backsplash and countertop.
Question: can I just add more caulk on top of the now-dried other caulk, in order to raise the caulk level above the backsplash top so water will drain correctly? Or do I need to rip out all the caulk and start from scratch?
I'm using GE Max 5000 caulk if it matters.

A:

Ideally it would be one continuous bead of caulking, however for 3/8" of a gap at the very top, you will probably be OK just adding a bit more caulking to fill it in.  However, if you don't want to have to touch it again for a while--and considering the low cost and relative ease of applying it--I think I would be inclined to remove the existing bead and apply a new one that covers the entire length. That way you don't have to worry about water getting behind it.


Q:

iPhone - How to modify a static library (.a file)

I was given an static library (.a extension file) that I have to use in a project, however I need to modify some of the source code before it is useful to me. What is the best way to accomplish this?

A:

The easy-but-most-of-the-time-not-applicable solutions are subclassing or extending.
You can also try to decompile the .a file if its licence authorizes it: cf. Decompiling Objective-C libraries, but it can be tricky and/or illegal.


Q:

Button listener in background to trigger activity

Recently I've started to write my own assistant, but encountered with a problem. I need to listen Push to Talk (physical) button event even when my app is on background. I know button listeners are not available within Service's, but I wonder how come Google Assistant can be triggered when there is another app on foreground ? Does anyone know what is different on that ?
Thanks

A:

It seems it is very possible to do it, IF you have chance to compile your own Android version. For reference you can try imitate following class  and implementations around it.
Although, this is not only implementation and change, it also requires changes in HAL layer.
Also I couldn't find how Google handles this. But my best guess would be either something like this or something like this.


Q:

Overriding HTTP errors with urllib2

I have this code, but it is not working. I want to use urllib2 to iterate through a list of urls. Upon opening each url, BeautifulSoup locates a class and extracts that text. The program stalls if there is an invalid url in the list. If there is any error, I just want to have 'error' as the text, and for the program to continue on to the next url. Any ideas?
    for url in url_list:
         page=urllib2.urlopen(url)
         soup = BeautifulSoup(page.read())

         text = soup.find_all(class_='ProfileHeaderCard-locationText u-dir')
         if text is not None:
            for t in text:
                text2 = t.get_text().encode('utf-8')
         else:
            text2 = 'error'

A:

try/except is your friend!  Change your code to s/thing like...:
for url in url_list:
    try:
        page = urllib2.urlopen(url)
    except urllib2.URLError:
        text2 = 'error'
    else:
        soup = BeautifulSoup(page.read())
        text = soup.find_all(class_='ProfileHeaderCard-locationText u-dir')
        if text:
           for t in text:
               text2 = t.get_text().encode('utf-8')
        else:
           text2 = 'error'

A:

urllib2.urlopen raises URLError on error as you can find in docs
Use try-except block:
try:
    page = urllib2.urlopen(url)
except urllib2.URLError as e:
    print e


Q:

Function specialization with array argument

Is it possible to specialize a function for a specific array type?
For example having a template function:
template <typename T, size_t size>
void process(T (&arr)[size])
{
    // do smth
}

Could a function specialization for T=uint8_t be done in such case? Or is the only reasonable solution here to use an overload like the one below?
template <size_t size>
void process(uint8_t (&arr)[size])
{
    // do smth else
}

Thanks for suggestions and comments.

A:

It is not possible to specialize function templates partially, so you will probably have to use a separate overload.


Q:

Functions are not being highlighted in Python2.7 in Pycharm-community

I'm using Pycharm-community 2016 0.3 on Ubuntu 16.04.
I'm coding in Python 2.7, the problem is that the functions which are defined  by me are not being syntax-highlighted. For example, before using Pycharm I was using Atom, in it the functions are highlighted making it very easy to debug.
I have turned on Semantic highlighting and i'm using the theme 'Dracula'.
I tried to re install Pycharm-communty, tried installing the latest edition, but none if it  is working.

A:

I found a work-around foe this problem,
If you install the 'onedark' theme and enable it, the local functions are also highlighted.
To install,
go to settings > plugins >  search for 'onedark', and install


Q:

Questions simply seeking ideas

What kind of game (in Scratch) would require use of a list?
It is clearly too broad, but finding great examples is also entirely central to what we do as educators.  How could a question like this be reworked to both help someone like @Scimonster find ideas for projects, but also garner "Good Subjective" answers?
To add to this, we already have a lesson-ideas tag.

A:

While I like the idea of soliciting help for finding examples, I think this particular example would fall under the category of "too broad."
As I see it, this relates to our lesson plan review thread. It could just be as simple as providing more context; the question itself is not inherently problematic. I'd just want to know things like:

Is the goal game design?
Is the goal understanding lists?
What is the experience level of students?
What is the context for wanting to know this? Teacher-led demo?

The issue to me is precision. With more context and background, this kind of subjective question can lead more towards good than bad.
It'd be good to form a list of helpful information when we get questions like this one, so we say, "To improve your question, please provide X, Y, and Z..." as in student ability, classroom context, learning objective, etc. Determining the key elements to making a "good subjective" question for teaching examples is our challenge here in meta as we form this community.


Q:

DVD playback jagged

One of my DVD plays jagged when objects moves fast in the picture, I want to know what is this effect called and hope someone could give a solution. I have VLC. It is like this:

A:

This happens with interlaced video. Interlaced video is drawn to the screen in two passes, first the odd lines from top to bottom, then the even lines from bottom to top.
This is a legacy thing inherited from the days of good ol' CRT tubes when the dots on the screen was drawn using a beam; and to optimize the physical limitations of that the beam could not be all places at once this method where used together with phosphoric layer to reduce flicker.
With this you end up with two half frames (odd and even lines). Now, this is also the way video is captured on many video cameras. The exception is progressive recording where a single frame is recorded at once, like with analogue film cameras.
The problem you see happens when something moves fast and the odd lines captures one position of the object, while the process is about to capture the even lines the object has moved enough to be visible on the two merged half-frames.
Of course, you can drop one half-frame and use various techniques to for example interpolate the remaining lines, but always with a loss of quality as a result.
The only way to really eliminate this problem is to record everything progressively.
Hope this will give some input.


Q:

PHP Restricting Access to web pages

I have several folders within my web server.
Each folder contains php / html files. In total there is around 40 files.
Using php I can determine the identity of the user who is currently logged in.
Is it possible to allow users to only access specific pages, based on who they are logged in as ?
I was wondering if .htaccess would allow this ? Or if there is a better way ?
I don't really want to start having to create a user / password authentication script.
Thanks

A:

Using sessions, you can create user levels and restrict access to various areas by assigning user levels to SESSION variables. Presumably, since, quote Using php I can determine the identity of the user who is currently logged in., you have the ability to set up session variables. I believe this is known as role based access control - In it's very simplest form
if ($_SESSION['user_level'] == "Administrator") {
# do something
}

This article may help further


Q:

Powershell Compare-Object on empty folder

I am writing a simple DLL copying script to help my dev team in setting up their local environments. I check the build devdrop folder and get a list of DLL files. I then look at the local folder and copy any newer DLLs over.
My problem is when the local folder is empty (i.e. the first time the script runs) it all falls apart.
$newFiles = Get-ChildItem -recurse -path "$drop\$latest\ship" -name
$oldFiles = Get-ChildItem -recurse -path $bin -name

$files = Compare-Object $newFiles $oldFiles -IncludeEqual -PassThru
$files | Where-Object { $_.SideIndicator -eq '<=' -or $_.SideIndicator -eq '=='} | % {
    Copy-Item -Path "$drop\$latest\ship\$_" -Destination $bin -Force
}

When $bin is empty the gci call leaves $oldFiles as null, giving me a nice error:

Compare-Object : Cannot bind argument to parameter 'DifferenceObject' because it is null.

I have searched around and all how-tos for Compare-Object don't seem to deal with this. I could check if the folder is empty and then copy all the files over, but I was wondering if there was a better way.
Cheers.

A:

$newFiles = @(Get-ChildItem -recurse -path "$drop\$latest\ship" -name)
$oldFiles = @(Get-ChildItem -recurse -path $bin -name)
$files = Compare-Object -ReferenceObject $newFiles -DifferenceObject $oldFiles -IncludeEqual -PassThru


Q:

Does thickness impact resolving loads for an inclined beam?

I have a 3 m x 1 m x 1 m cuboid weighing approximately 10,000 kg. I am trying to resolve the vertical forces that will support the cuboid if the cuboid must rest at a 45 degree angle.
Which of the two solutions below (if either) is best for calculating the resolving forces?
In both cases I assume a 2-D cross section of the cuboid where the resolving forces act at the bottom two corners.
The first method is to treat the cuboid as a beam and the weight as an continuously distributed load. This results in an even distribution of the load between the two resolving forces being even irrespective of the angle.
The second method is to assume the weight to be a point load at the center of mass. Then use the sine rule to determine the position the force acts along the base line of the beam. This gives an uneven distribution of the loads with weighting slightly towards the lower corner but seems to be dependent on thickness.
I am reasonably confident it is the second but I want to know the mathematical explanation.

A:

The more exact solution is the second one. Usually beams aren't very wide or high compared to their length, so if they are inclined, taking their self weight as a linear load is acceptable. As you mentioned, the distribution of the load depends on the height of your cross-section and on the angle of your "cuboid." You can see this by making an extreme case where the right reaction needs to be reversed to hold up your cuboid:

In this case it is clear that the linear load would not apply. If you want to resolve the reactions, simply do a summation of your vertical forces (only dead weight at the center of mass) and a summation of moments.


Q:

How to Redirect from Http to Https in Intranet?

I have a vb.net application running as intranet on Win Server 2003. So should I use HTTPS instead of HTTP?
What is the difference or why should I if the answer is HTTPS? Is there any code in VB to redirect from HTTP to HTTPS?
Thanking you all in advance for your time and consideration.

A:

You should use HTTPS to ensure reasonable protection from eavesdroppers and man-in-the-middle attacks. HTTPS creates a secure channel over the network, provided that adequate cipher suites are used and that the server certificate is verified and trusted.
An intranet is obviously less exposed than the public internet, but you should still use HTTPS if you are transferring sensitive data (such as passwords) from the server to the browsers.
Assuming you are using IIS to serve your website, you may want to check the following articles for further reading:

Microsoft Support - How To Set Up an HTTPS Service in IIS
Forcing HTTPS in IIS 6.0
Configure SSL on Your Website with IIS


Q:

speed up array functions in Ruby

I have a simple method that finds prime numbers, puts them in an array and then sums them up. What are some possible steps to speed it up?
def prime?(number, array)
  array.each do |x|
    if number % x == 0
      return false
    end
  end
  true
end

def sum_prime(number)
  i = 0
  prime = 1
  output = [2]
  while prime < number
    if prime?(prime, output)
      i += 1
      output << prime if prime != 1
      p prime
    end
    prime += 2
  end
  output.inject(:+)
end

sum_prime(200000)

is array#each ok? Can I concatinate differently for faster results?

A:

This should work.  It uses others' suggestions:
require 'prime'
def sum_prime(limit)
  Prime.each(limit).inject(0) {|sum, num| sum + num}
end
puts sum_prime(200000)


Q:

Use table manager in modeler in qgis

I need to reorder the fields in a tab file from within QGIS modeler. Table Manager plugin allows this but I can't seem to find a way to do this in modeler. It needs to be run on thousands of files.
Can we import/use plugins like table manager in the graphical-modeler or in the python window?

@Olle - I don't see the same options. How do I add them to my toolbox? They are active in processing-->options

A:

in the graphical modeller you have the opportunity to refactor fields wihtin a vector layer.

There you can reorder fields like in the table Manager plugin.  In a second step you could use this model with processing.runalg("modeler:youmodelname", inputlayer, outputlayer)in the console to iterate trough all desired files.


Q:

Use activityIndicator as image placeholder

I use UIImageView+AFNetworking.swift in my project, and to load image to imageView with placeholder, i use this code:
imageCell!.imageView.setImageWithUrl(NSURL(string: post.image)!, placeHolderImage: UIImage(named: "PlaceholderIMG"))

How can i replace the PlaceholderIMG with a activityIndicator instead?

A:

Use setImageWithURLRequest from UIImageView+AFNetworking.swift instead of your solution.  So here's a rough example:
// create a UIActivityIndicatorView with the
let ai = UIActivityIndicatorView(frame: cell.imageView.frame)
// Add the UIActivityIndicatorView as a subview on the cell
cell.addSubview(ai)
// Start the UIActivityIndicatorView animating
ai.startAnimating()
// Load the remote image with this different API, and send nil as the placeholder
cell.imageView?.setImageWithURLRequest(NSURLRequest(URL: NSURL(string: post.image)),
    placeholderImage: nil,
    success: { (request, response, image) -> Void in
        // on completion, stop it and remove it
        ai.stopAnimating()
        ai.removeFromSuperview()
        cell.imageView?.image = image
    },
    failure: { (request, response, error) -> Void in
        // on completion, stop it and remove it
        ai.stopAnimating()
        ai.removeFromSuperview()
})


Q:

VBA Insert Text below cell1 based on text in cell1 (text/cell variable; in range)

I have a worksheet that is basically a calendar in which I add certain tasks.
Now I would like for excel to add a certain text below a cell if I enter a certain text in this cell.
E.g. If I wrote "Evaluation" in cell A1, the text "Personnel" would appear in cell A2. However, if I wrote "Evaluation" in cell B1, the text "Personnel" would appear in B2 and so on. Furthermore, I would also probably write "Evaluation" in more than one cell and the insertion of "Personnel" should apply to all these cells.
Since it is completely variable where I enter the text ("Evaluation") and all other cells also need to be free, I cannot do it with basic Excel formulas. Thus, I think, VBA is the only way to go.
Unfortunately I have not much experience with VBA, so I would be very glad if you could help me out.

A:

Put this in the worksheet's private code sheet.
private sub worksheet_change(byval target as range)
    application.enableevents = false
    dim t as range
    for each t in intersect(target, target.parent.usedrange)
        if lcase(t.value2) = "evaluation" then
            t = "Evaluation"
            t.offset(1, 0) = "Personnel"
        end if
    next t
meh:
    application.enableevents = true
end sub


Q:

How to integrate keyword search function with web browser on iOS?

There is a custom web browser in our app. We want to show keyword suggestions when user input some words in search field. Is there some Google api for this?
I've found the similar api of Baidu:
https://m.baidu.com/su?&from=wise_web&action=opensearch&ie=utf-8&wd=keyword.
This api will return a response in json format.
How about Bing and Yahoo? Do they have some kind of keyword suggestion api?
Thanks a lot!

A:

For now , Google\Bing\Yahoo do not offer keyword research api. The keyword planner of Google or the keyword research of Bing are just tools for a company to find which keyword is more valuable for their Ads.
We can get keyword research api from some other websites, such as https://keywordtool.io/google-suggest , but it is not free.
Here is want I found:
https://keywordtool.io/google-suggest : Google does not want people to programmatically pull its autocomplete keyword suggestions.
https://www.quora.com/Does-Yahoo-or-Bing-offer-a-keyword-research-API-similar-to-Googles-Adwords-API : No API for keyword research from Yahoo! or Bing.
Hoping this answer will help someone else.


Q:

Batch removing part of filenames using Automator

I'm trying to create an Automator script that removes portion of a filename after a delimeter while preserving the extension.
Files are usually called like 1-cropped_DSC5888.jpg, 2-cropped_Whatsapp75.png etc. I want to remove everything after _ and keep only the part with number and '-cropped' so like: 1-cropped.jpg
I tried it with this script
on run {input, parameters}
try
    set AppleScript's text item delimiters to {"_"}
    set theFileNameList to {}
    repeat with thisItem in input
        set the end of theFileNameList to text item 2 of (thisItem as text)
    end repeat
    set AppleScript's text item delimiters to {}
    return theFileNameList
on error eStr number eNum
    display dialog eStr & " number " & eNum buttons {"OK"} ¬
        default button 1 with icon caution
    set AppleScript's text item delimiters to {}
    return
end try

end run
But this removes the part I want to keep and keeps the part I want to delete. Also it gives me just an output, but doesn't rename the actual files. Any help with this, please?

A:

All you are doing is returning a list of the last part of the names (if there is more than one delimiter character, the second part) to the next action.
Text item delimiters aren't really needed if you are just using the first occurrence of a character, so you can do something like:
on run {input, parameters}
    set output to {}
    repeat with anItem in input
        set {theFolder, oldName, extension} to getNamePieces from anItem
        try
            set here to offset of "_" in oldName
            set newName to text 1 thru (here - 1) of oldName
            tell application "Finder" to set name of anItem to (newName & extension)
            set end of output to (theFolder & newName & extension) as alias
        on error errmess -- don't rename if error (delimiter not found, duplicate file, etc)
            log errmess
            set end of output to anItem as alias
        end try
    end repeat
    return output -- for next action
end run

to getNamePieces from someItem
    tell application "System Events" to tell disk item (someItem as text)
        set |container| to path of container
        set {|name|, extension} to {name, name extension}
    end tell
    if extension is not "" then
        set |name| to text 1 thru -((count extension) + 2) of |name| -- just the name part
        set extension to "." & extension
    end if
    return {container, |name|, extension}
end getNamePieces


Q:

Android - application depending on own api - server offline

I don't know if this is the right place to post but I am completly lost.
My application, that is relying on an api from my own vps(that is down for 4 hours now), is not working anymore.
I have contacted my host, but they aren t moving fast and I have no backup of my vps content.
Many users are bad reviewing my application and I'm starting to be crazy about it.
Is there any solution to avoid bad reviewing you could advice me?
Thank you

A:

In your case, If I was a user and I would see a crash issue I would downvote too, but I wouldn't be so annoyed if your app gives me something like
"We are improving something bla bla"

and I would wait for it.
It's best check those situations such as downtime,no internet etc and let the user know about it.


Q:

How to format cells in specific column of an ng-repeat table?

I have a table and the last column is overflowing off the page. It's just one line that overflows over the right edge of the page and keeps extending, but you can't see it or scroll through it. I am using semantic ui framework.
How can I contain the text within the bounds of each cell of ONLY the last column? I'm not sure how to approach it because I  need to use ng-repeat to produce table data.
I tried adding ng-style="overflow:scroll; max-width:300px" to my 	 tags, but it's applying a scrollable overflowed cell for every single cell in the table.

A:

Why don't you use the 'last-child' selector? Add this to your CSS.
    tr td:last-child{
          overflow:scroll;
          max-width:300px;
    }

Hope it helps.


Q:

If $f(x)=g(x)$ for all $x:A$, why is it not true that $\lambda x{.}f(x)=\lambda x{.}g(x)$?

There's something about lambda calculus that keeps me puzzled. Suppose we have $x:A\vdash f(x):P(x)$ and $x:A\vdash g(x):P(x)$ for some dependent type $P$ over a type $A$. Then it is not necessarily true that $\lambda x{.}f(x)=\lambda x{.}g(x)$.
I've tried to understand this phenomenon and then it goes something like this: actually, the argument you pass to $\lambda$ is not just $x{.}f(x)$, but it is the entailment $x:A\vdash f(x):P(x)$. Thus different reasons why $f(x):P(x)$ for each $x:A$ give different functions. But I've never seen things like this written down somewhere, so I feel quite uncertain about it.
I'd like to know why $\lambda x{.}f(x)$ is not $\lambda x{.}g(x)$ even if $f(x)=g(x)$. From a type theoretical point of view, but maybe also from a models point of view. If there are models that can easily explain what kind of behavior we can expect from $\lambda$, that would be very helpful.

Edit. I should add that the bit of lambda calculus I have learned is from doing dependent type theory (and more specifically, Martin-Lof's intensional type theory) in Coq. There, the dependent product $$\prod(x:A),\ P(x)$$ is defined for a dependent type $P:A\to\mathsf{Type}$ over a type $A$ by introducing elements $\lambda x{.}f(x)$ for each $x:A\vdash f(x):P(x)$, with for each $f:\prod(x:A),\ P(x)$ and each $a:A$, a term $\mathsf{apply}(f,a):P(a)$. These are then required to satisfy the $\beta$- and $\eta$-conversion rules:
$$
\begin{split}
\beta.\qquad\qquad & \mathsf{apply}(\lambda x{.}f(x), a)=f(a)\\
\eta.\qquad\qquad & \lambda x{.}\mathsf{apply}(f,x)=f,
\end{split}
$$
but not rule $\xi$, which is the rule saying that $\lambda x{.}f(x)=\lambda x.g(x)$ whenever $f(x)=g(x)$ for all $x:A$. But I don't know about anything that would break rule $\xi$, hence my question.

Here's a concrete example where I face this problem.
An example of such $f$ and $g$ where this problem bugged me the most comes from proving that the axiom of choice is an equivalence. Suppose that $A$ is a type, that $P$ is a dependent type over $A$ and that $R$ is a dependent type over $P$, i.e. $R:\prod(x:A),\ (P(x)\to\mathsf{Type})$. Then the type theoretical axiom of choice is the function
$$
\mathsf{ac}:\prod(x:A)\sum (u:P(x)),\ R(x,u)\to\sum\Big(s:\prod(x:A),\ P(x)\Big)\prod(x:A),\ R(x,s(x))
$$
given by
$$
\lambda f.\langle \lambda x.\mathsf{proj_1}f(x),\lambda x.\mathsf{proj_2}f(x)\rangle
$$
A candidate inverse would be given by
$$
\mathsf{ac{-}inv}:=\lambda w.\lambda x.\langle\mathsf{proj_1}w(x),\mathsf{proj_2}w(x)\rangle.
$$
To prove that this is a right inverse you need the $\eta$-conversion at some point, but to prove that it is a left inverse, the identity
$$
\lambda x.\langle\mathsf{proj_1}f(x),\mathsf{proj_2}f(x)\rangle=\lambda x.f(x)
$$
is needed at some point. While it is fairly obvious that $\langle\mathsf{proj_1}f(x),\mathsf{proj_2}f(x)\rangle=f(x)$ for each $x:A$,  this is not a step you can make in Coq, because there's no rule $\xi$ there (as far as I know). Even $\eta$ you have to introduce manually and that is only possible using the identity types of Martin-Lof. Mike Shulmann has constructed a way around this issue: there is a proof that the map $\mathsf{ac}$ is indeed an equivalence. I understand this proof, but not the behavior of $\lambda$. What can $\lambda$ do if you don't have $\xi$ that prohibits me from making this step?

A:

I’m pretty sure that the $\xi$ rule is implemented in Coq. The doc says somewhere

Let us write E[Γ] ⊢ t ▷ u for the contextual closure of the relation t reduces to u in the environment E and context Γ with one of the previous reduction β, ι, δ or ζ.

The $\xi$ rule is usually not even mentionned because this is a consequence of the contextual closure of definitional equality which is usually assumed.
In your concrete example, the problem does not come from $\xi$ but from the "fairly obvious" fact that $\langle\mathsf{proj_1}f(x),\mathsf{proj_2}f(x)\rangle=f(x)$. This is called $\eta$-equality for dependent sums, but Coq does not satisfy this definitionally (not even Coq 8.4 which has only $\eta$-equality for functions).
So yes, in Coq you have to prove $\eta$-equality for dependent sums using identity types, but this has nothing to do with $\xi$.
In Agda there is $\eta$-equality for dependent sums (and more generally for records), so probably that these two functions are definitionally inverse to each other in Agda.


Q:

How to set access control allow origin on particular file web.config

If this were a dynamic response, I'd simply do Response.Headers.Add("Access-Control-Allow-Origin", "*"); but I have a static file I'd like to allow cross domain access to.
Is there a way to assign this header to a particular file just using web.config? Say it's just example.com/flat.json
I guess I could route the file to dynamic page, but that would be a bit silly.

A:

This should work
<location path="Sample.txt">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>


Q:

Can I define my variables *inside* a function?

Recently, I came across a beginner's question while self-teaching which asked for me to write a program to compute pay given input for hours worked and hourly rate. For any hours over 40, time-and-a-half should be paid. I did this successfully, but it seemed weird to me for some reason. The following code works perfectly and I got a 100% on the assignment:
def computepay(h,r):
    try:
        hrsfloat = float(h)
    except:
        print("Error: 'Hours' must be a number")
        quit()
    try:
        ratefloat = float(r)
    except:
        print("Error: 'hourly rate in dollars' must be a number")
        quit()
    if hrsfloat <= 40:
        return(hrsfloat*ratefloat)
    else:
        x=hrsfloat-40
        return((1.5 * x + 40) * ratefloat)

h = input("Enter Hours:")
r = input("Enter hourly rate in dollars:")
p = computepay(h,r)
print('Pay', p)

But for some reason I would much rather put the
 h = input("Enter Hours:")
 r = input("Enter hourly rate in dollars:")

inside the definition of computepay in the following manner:
def computepay(h,r):
    h = input("Enter Hours:")
    r = input("Enter hourly rate in dollars:")
    try:
        hrsfloat = float(h)
    except:
        print("Error: 'Hours' must be a number")
        quit()
    try:
        ratefloat = float(r)
    except:
        print("Error: 'hourly rate in dollars' must be a number")
        quit()
    if hrsfloat <= 40:
        return(hrsfloat*ratefloat)
    else:
        x=hrsfloat-40
        return((1.5 * x + 40) * ratefloat)

p = computepay(h,r)
print('Pay', p)

But this returns an error:

Traceback (most recent call last):
   File "C:[redacted]", line 20, in
    p = computepay(h,r)
  NameError: name 'h' is not defined

So, is there a way to write computepay so that it is self-contained in this way? I don't know why I feel compelled to do this, but I really really do.

A:

Yes, you can. The problem, as the error message indicates, is that h and r don't exist at the point where you call the function:
p = computepay(h,r)

Note that these are different h and r from the ones defined inside the function! Read up on scopes if you find this confusing.
The solution is to omit the arguments both from the function definition and from the call site:
def computepay():
    ...

p = computepay()

There is, however, a case to be made for passing these variables as arguments. It makes your function more versatile if it does one thing (computing the pay) rather than two orthogonal things (asking for input, then computing the pay). If you pass the values as arguments, the function doesn't care where they come from, so the calling code could read them from a file or from a GUI without having to modify the function itself.
This versatility also makes the function more amenable to unit testing, which Python supports particularly nicely in the form of doctests.
If you're still getting to grips with the basics of the language, you shouldn't be concerned about this. I just thought I'd mention it.


Q:

Keras - error when adding layers to loaded model

I want to use ResNet50 as a feature extractor. For this purpose, I have loaded the pre-trained model, deleted a few layers and added my layers to the model. For adding my layers, I have used the Sequential API. The code is the following:
resnet_model = ResNet50(weights='imagenet')

# Delete layers
for i in range(12):
  resnet_model.layers.pop()

# Fix weights
for layer in resnet_model.layers:
  layer.trainable = False

base_model = Model(inputs=resnet_model.inputs, outputs=resnet_model.layers[-1].output)

model = Sequential()
model.add(base_model)

model.add(Conv2D(2048, kernel_size=(3, 3), input_shape=(7, 7, 2048)))
model.add(BatchNormalization(momentum=bn_momentum))
model.add(Activation('relu'))

model.add(Conv2D(2048, kernel_size=(3, 3)))
model.add(BatchNormalization(momentum=bn_momentum))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(200, activation='softmax'))

This code works. However, when I run print(model.summary()) I obtain the following:
Model: "sequential_26"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
model_16 (Model)             (None, 7, 7, 2048)        19115904
_________________________________________________________________
conv2d_31 (Conv2D)           (None, 5, 5, 2048)        37750784
_________________________________________________________________
batch_normalization_23 (Batc (None, 5, 5, 2048)        8192
_________________________________________________________________
activation_917 (Activation)  (None, 5, 5, 2048)        0
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 3, 3, 2048)        37750784
_________________________________________________________________
batch_normalization_24 (Batc (None, 3, 3, 2048)        8192
_________________________________________________________________
activation_918 (Activation)  (None, 3, 3, 2048)        0
_________________________________________________________________
flatten_10 (Flatten)         (None, 18432)             0
_________________________________________________________________
dense_17 (Dense)             (None, 1000)              18433000
_________________________________________________________________
dense_18 (Dense)             (None, 200)               200200
=================================================================
Total params: 113,267,056
Trainable params: 94,142,960
Non-trainable params: 19,124,096
_________________________________________________________________
None

As you can see, the conv layer adds 37750784 new parameters to the network!!! Obviously, this isn't right, but I can't see why this happens...

A:

Actually, the number of parameters for the second layer is correct, the number of parameters in a convolutional layer is calculated as follows:
n_parameters = n_filters_l * (n_filters_l-1 * (kernel_size_h * kernel_size_w) + 1)
             = 2048 * (2048 * (3 * 3) + 1) = 37750784

If you want to decrease the number of parameters, you therefore have multiple options:

Decrease the number of filters in the layer before it
Decrease the number of filters in the layer itself
Use a lower kernel height of width


Q:

Typescript: Defining undeclared props for generic React component

I have this simple generic React component where I won't always know which element type or props I'll be using and don't want to have to set up an interface for each potential prop.
Using TS v2.9.
The fact that I'm using React Native and not React shouldn't be relevant in this instance.
import React, { StatelessComponent as SC } from "react";

interface IGenComponentProps {
  /**
   * Component type
   */
  ComponentName: string;

  /**
   * Test Id used for automation testing
   */
  testId?: string;

  /**
   * I'd like to define this here to supress TS errors I'm getting
   */
  remainderProps?: any;
}

const GenComponent:SC<IGenComponentProps> = ({ComponentName, testId, children, ...remainderProps}) => {

  return (
    <ComponentName id={testId} {...remainderProps}>
      {children}
    </ComponentName>
  )
}

export default GenComponent;

This works great and as expected but I get TS errors when using the component like so:
   <GenComponent
      ComponentName={Image}
      testId="test-image"
      source={{uri: 'someImageSrc'}}
      opacity={0.1}
    />

[ts] Property 'source' does not exist on type 'IntrinsicAttributes & IGenComponentProps & { children?: ReactNode; }'.
[ts] Property 'opacity' does not exist on type 'IntrinsicAttributes & IGenComponentProps & { children?: ReactNode; }'.

or:
   <GenComponent
      ComponentName={View}
      testId="left-container"
      accessibilityHint="left-container"
    >
      { someContent }
   </GenComponent>

[ts] Property 'accessibilityHint' does not exist on type 'IntrinsicAttributes & IGenComponentProps & { children?: ReactNode; }'.

A:

If you want to be able to allow properties with any name without enumerating those names, you can do something like this:
interface IGenComponentProps {
  ComponentName: string;
  testId?: string;
  [key: string]: any;
}

Be aware that you'll have limited type checking with this. Your IDE will basically enforce that ComponentName exists and is a string, and that if testId exist it is a string. Anything else is a free for all, but at least it's allowed.


Q:

Sense of the second "were" in this line of When I Survey

I was listening to this the other day and was wondering if this was grammatically correct.

Were the whole realm of nature mine...

I'm OK with this one; the realm isn't mine and likely never will be;

that were an offering far too small

Why is were used here?  To me it feels that would be would be more correct, although not as good a fit to the metre.

A:

Yes the meaning is "would be".
"were" in he sense of "would be" is an archaic usage, particularly common in Biblical language (King James version) and other writings from that period, such as Shakespeare.
Here it is used for meter, to echo the previous use of "were", and because the suggestion of biblical language fits the religious verse here.


Q:

Actionscript, improving xor performance?

I am using the below code to process some large files.
var joinedBytes:ByteArray = new ByteArray;
joinedBytes.length = _chunkSize;

for (var i:Number = 0; i < _chunkSize; i++) {
    joinedBytes.writeByte(_xorBytesBuffer[i]^_rndBytesBuffer[i]);
}

Its taking about 2.5 seconds to process 10mb of data on a desktop.
Is this normal performance?
Does any way exist to speed it up?
I think that some of the time is writing to the byte array.
EDIT:
_xorBytesBuffer and _rndBytesBuffer are both byte arrays.

A:

I didn't test everything. I could be wrong somewhere below but...
ByteArray is faster
The [i] suggest you are using Vector/Array using another ByteArray for _xorBytesBuffer and _rndBytesBuffer should speed things up.
You want also operate on larger data i.e. writeUnsignedInt() instead of writeByte()
See also this question
uint is faster vs Number
And if you only have 10MB, you would like to use var i:uint instead of Number.
Another thing is you can replace i++ wit ++i though I did't really test  if this has much impact - I only heard that it's faster.
Remove additional steps.
You could even try something like:
for (var i:uint = 0; i < _chunkSize;) {
    joinedBytes.writeByte(_xorBytesBuffer[i]^_rndBytesBuffer[i++]);
}

Please let us know it _rndBytesBuffer[i++] makes any difference ;)
Wait, I just said to not use indicies but another ByteArrays... Well If you still want to try above still let us know how it performs ;)
Make sure your condition check is as simple as possible.
Make sure you have something like var _chunkSize:uint instead of
function _chunkSize(){return something;}


Q:

How make some boostrap columns taller than other?

So basically I'm still a begginer when it comes to doing interfaces on the web and trying to allign everything properly. I've decided to use the bootstrap library. I'm trying to make a modal dialog divided into multiple section but i'm really struggling to make some section stack on top of each other and have another section take up the entire space.
What I currently have :
https://i.gyazo.com/adeeb3cca0abb6dea4a5d002d3568afa.png
What I'm trying to achieve :
https://i.gyazo.com/e8513c243424cb71926ac838e8b1166e.png
This is the code I currently have with some sample text to try to delimiter each section :

      STATUS

     L

      SOME TEXT ASDASDASDJLASDJKLASDJAD
      ASDASDLASKD
      aASDASDK:ASDKASDK
      ASDASJDASDASDKASJDASDJ

     L

A:

To match the image you've provided, you want two columns - one three wide with four rows, and one nine wide with one row.
The height of the rows in the left column will be determined by their contents. I've written an example with extra content in one row in the left column:

        3

        3

        wide

        but

        taller

        3

        3

      9

JSFiddle for a live example.


Q:

How did I end up with two Area 51 accounts, and can I get this fixed?

I already had an Area 51 account, but today, logging in the same way as usual (using Facebook login) on a system that hadn't visited Area 51 before, I ended up getting a brand new account instead of getting into my existing one.
The detail pages for my old account and my new account both show the same network profile, confirming that the system does still recognise the old one as mine.
Can these accounts be merged? Completely deleting the new account also works for me, if it means that logging in again will get me back into my old account.
Just as reported in Duplicate account on Area 51, I cannot use the Contact page in the Help Center to request a merge of these accounts. I get the same "this operation cannot be performed on a meta site; please continue on the main site." message.

A:

Sorry it took me a while to get around to this. Your account should be all fixed up now.
As for what happened... I wish I had a good story here. All that happened, though, was that you had a wrong entry in the table we use to map users on various sites to an account. So when you went to log in on Area 51, that table cheerfully said you had no account and we made you a new one.


Q:

SQL statement, get query RSQLite

I am new to SQL and having trouble with RSQLite.
Here is an example of my table:
counts    Month
0         June
4         June
2         March
5         July
3         July

I would like to create a search query using dbGetQuery that will count up the number of counts for each month from my totals table. Im looking for output that looks like this:
counts    Month
4         June
2         March
8         July

So far I have this but is incorrect. dbGetQuery(conn=db, "SELECT Count(counts) FROM totals group by [Month]")

A:

From your desired output seems that you don't want to count the counts but to sum them. As stated by @AlexK, you also need Month in your select to have it displayed along with the sum result
dbGetQuery(conn=db, "SELECT [Month], sum(counts) as counts FROM totals group by [Month]")


Q:

text color in HTML MVC

Here's the program which checks status of customer's parcel in switch loop. There's a couple different statuses and I'd like to show them in different colors. Here's a loop with example case:
switch (Parcel.Status) {
    case Customer.enSOMAccountIsEmpty:
        parcel.Comment = status.Comment;
        break;
    ...
}

In Model I created two types of colors in class Parcel:
public class Parcel {
    public string StatusColor { get; set; }
    public string CommentColor { get; set; }
}

And finally, the kode in View:

        @foreach (var item in Model.ParcelList)
        {

                @item.StatusText

                @item.Comment

                @item.InfoDate

        }

How to connect these types from Models to View to show every status in different color? For example status from first case has red color becouse "Account is Empty" and comment to it should be blue. Thanks.

A:

You can do it like this:
@{
if(string.IsnullOrEmpty(item.StatusText))
Text

@else
Text

}

Where this is the check with the behalf of we will choose color, you can change it accordingly.

A:

You could set the status colour in the switch.
case Customer.enSOMAccountIsEmpty:
                        parcel.Comment = status.Comment;
                        parcel.StatusColor = "red";
                        break;

and then in your view you can

    @foreach (var item in Model.ParcelList)
    {

            @item.StatusText

            @item.Comment

            @item.InfoDate

    }

I believe this is what you are requesting?


Q:

customized email system

I have a need to add a personalized email form on each registered user's page. I would ordinarily use webforms but because the email form needs to dynamically change the destination email address to the email address of the registered user whose page a visitor is on.
From my research, Webforms can't dynamically change their destination address. Can anyone offer me some alternative solution(s).
Thanks

A:

Incase anyone is interested in a solution to this problem - the answer is webforms.
The 6.x.3-1.1 version offers the ability to set a static email address or to a component field as a recipient address.
The component field is one of those that you configure as an input field for the webform. If you create an email component field you can set it as the recipient.


Q:

How can I solve fatal compiler errors when installing GLScene into RAD Studio 2010?

I'm trying to install GLScene into RAD Studio 2010, with the aim of using it from a mostly C++ project. I downloaded the latest snapshot (5991, November 2011) and have been trying to compile and install the two main packages:  GLScene_DesignTime and GLScene_RunTime. I haven't even tried some of the other libraries (CUDA, etc), I just want to get the base packages running.
I've encountered a number of problems, one of which I can't solve, and I'm seeking the help of anyone on SO who has successfully installed GLScene, or might know how to solve these Delphi compiler errors.
First problem (solved?)
When compiling, a number of files gave the following error:
[DCC Warning] GLSelection.pas(297): W1025 Unsupported language feature: 'abstract class method'

This is caused by a method declaration something like:
TGLBaseSelectTechnique = class
  public
    class function IsSupported: Boolean; virtual; abstract;

It seems that a virtual abstract class method is not supported in Delphi 2010, and I have solved it by removing 'abstract' and providing a dummy implementation, e.g. just returning false.
The second problem (not solved) - Delphi compiler fatal errors
I am now encountering two more serious errors. When compiling, the compiler fails like so:
[DCC Fatal Error] Exception EAccessViolation: Access violation at address 05AE8ED9 in module 'dcc140.dll'. Read of address 00000003
[DCC Error] Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

It doesn't say what file caused this, but I think it's caused by Spline.pas. Occasionally and not as often, I get this:
[DCC Fatal Error] Spline.pas(1): F2084 Internal Error: AV062D8ED9-R00000003-0

This indicates Spline.pas, and I think the first error is probably related to the file too, because after getting the first one if I then clean the project, cleaning will fail saying it could not delete Spline.hpp. (I have to close and reopen the IDE.) Spline.hpp just contains the following:
// CodeGear C++Builder
// Copyright (c) 1995, 2009 by Embarcadero Technologies, Inc.
// All rights reserved

// (DO NOT EDIT: machine generated header) 'Spline.pas' rev: 21.00

#ifndef SplineHPP
#define SplineHPP

#pragma delphiheader begin
#pragma option push
#pragma option -w-      // All warnings off
#pragma option -Vx      // Zero-length empty class member functions
#pragma pack(push,8)
#include <System.hpp>   // Pascal unit
#include <Sysinit.hpp>  // Pascal unit

and there it stops.  It looks to me like it failed when trying to generate the HPP file.
I always get one of these two failures.  The second is the only one I can tie to a specific file; the first fails halfway through the project, but I can't see where it got up to when it failed.  I am compiling from inside the IDE.
I've looked in Spline.pas, and it seems pretty basic code - I can't see anything unusual at all. You can find it here, and apparently the file hasn't been touched for seven years... so I think it should compile :)
If I change the project settings so it does not generate headers, it compiles fine. (Generating just obj files, and any other of the settings that does not include "headers", all work fine.) But this isn't a good workaround for me - after all, I need to use it from C++ Builder, so my normal setting would be "Generate all C++ Builder files". At a bare minimum, I need HPP and OBJ files.
Has anyone here used GLScene in a recent version of C++ Builder? Have you encountered similar problems? Any idea how to solve this one?
I am using:

RAD Studio 2010 (fully patched and up to date; DDevExtensions and IDEFixPack installed.)
The November 2011 snapshot; I tried the March 2011 snapshot too, and got the same problems.  Link to snapshots here.
The Delphi 2010 packages modified only by changing the linker output to generate C++ Builder files; and also the BCB 6 packages.  Both give the same errors.

A:

Edit: GLScene now has compatibility with RAD Studio XE3 (including C++ Builder.)

Now there is full compatibility of GLScene with Embarcadero RAD Studio
  C++Builder XE3 as in design and runtime mode.
You can download it from http://yadi.sk/d/o1QGI2KA10MK1 (95Mb)

-- from Pal Wassail's post on the Embarcadero forum thread.

{quote:title=David M wrote:}{quote}
  Hi,
I'm trying to install GLScene into RAD Studio...
  David

And here is more simple Test for EMB developers of Delphi XE3 header generator -
1.Create a VCL Form Application
2.Add in Unit1.pas interface section
type
 TVector3f = array[0..2] of single;
 TVector4f = array[0..3] of single;

 function VectorAdd(const v : TVector3f; const f : Single) : TVector3f; overload;
 function VectorAdd(const v : TVector4f; const f : Single) : TVector4f; overload;

3.Add in implementation section
function VectorAdd(const v : TVector3f; const f : Single) : TVector3f;
begin
  Result[0]:=v[0]+f;
  Result[1]:=v[1]+f;
  Result[2]:=v[2]+f;
end;

function VectorAdd(const v : TVector4f; const f : Single) : TVector4f;
begin
   Result[0]:=v[0]+f;
   Result[1]:=v[1]+f;
   Result[2]:=v[2]+f;
   Result[3]:=v[3]+f;
end;

Set Delphi Compiler option “Generate C++ .objs, headers, namespaces, export”
Build the project
Then Delphi XE3 compiler generates wrong header file Unit1.hpp with lines:
extern PACKAGE TVector3f __fastcall VectorAdd
  (float const v, const float f)/ overload   */;
extern PACKAGE TVector4f __fastcall VectorAdd
  (float const v, const float f)/ overload */;
If now you are trying to use this header file Unit1.hpp in my.cbproj you get fatal error:
“E2238 Multiple declarations in …”

Yes, if you change vector array types to records:
 TVector3f = record
    case boolean of
      true  : (Coord: array[0..2] of single);
      false : (X,Y,Z: single);
end;

then the problem could be solved, because in this case Delphi compiler generates
extern PACKAGE Vectortypes::TVector3f __fastcall VectorAdd
   (const Vectortypes::TVector3f &v, const float f)/* overload */;
extern PACKAGE Vectortypes::TVector4f __fastcall VectorAdd
   (const Vectortypes::TVector4f &v, const float f)/* overload */;

and you could build your C++Builder VCL application without "Multiple declaration " error. It was done for old GLScene version in 2007, but now you need to rewrite some part of code  in new library, starting from VectorGeometry.pas module.

There are second way to fix such automatic header's errors - improvement of Delphi compiler in Generating C/C++ headers, namespaces and packages option. But it's in hands of EMB developers.

A:

Here's how I do it:

Download and extract this ZIP file (directly into the root folder of GLScene, allowing it to overwrite as necessary)
Load up the appropriate RAD Studio version (2007 to XE2) and open the file *GLScene_Group.groupproj* (where  = your RAD Studio version)
Build/Install each Package in group order

I have carefully assembled these fixed packages to ensure they all install and function properly from 2007 to XE2. Some packages (at the bottom of each group) require additional dependencies to function (such as the Python package) so be mindful of these.
I have tested and confirmed that these work on RAD Studio 2007 to XE2 only.
Don't forget to add the \Source folder (and all subfolders) to the Search Paths (either for the IDE itself or an individual Project, as you desire) otherwise the projects using GLScene components will fail to compile complaining of missing units.
Enjoy!


Q:

Illustrator export gives a huge white border

I am trying to export a business card size in Adobe Illustrator but each time I export, I get this annoyingly huge white borders that are unecessary, even if I save it as .png, any ideas? (click image to see the border because its white like the page)

A:

If you save using 'Save for Web', uncheck 'Clip to Artboard' before exporting.
If you save as PDF (which you actually should be doing for print), make sure your artboard size is the same as the card size.


Q:

Call stored procedure through nhibernate

I need to call a stored procedure through nhibernate, but I do not know how.
I have simple stored procedure:
CREATE PROCEDURE InsertDoc
    @Name nvarchar(50),
    @Author nvarchar(50),
    @Link nvarchar(50)
AS
    INSERT INTO documents(name, date, author, doclink)
    VALUES(@Name, CURRENT_TIMESTAMP, @Author, @Link)

I tried this in my code:
public class documents
{
    public int id;
    public string name;
    public DateTime date;
    public string author;
    public string doclink;

    public void CreateDocuments(String n,String l,String u)
    {
        documents exSample = new documents();
        exSample.name = n;
        exSample.date = DateTime.Now;
        exSample.author = u;
        exSample.doclink = l;

        using (ISession session = OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {
            //Session.CreateSQLQuery("EXEC :sp_name :start_date :end_date").SetString("sp_name", <>;)
            session.CreateSQLQuery("EXEC InsertDoc @Name = N'" + exSample.name + "',@Author = N'" + exSample.author + "',@Link = N'" + exSample.doclink + "'");
            // session.Save(exSample);
            transaction.Commit();
        }
    }

    public ISessionFactory factory;

    public ISession OpenSession()
    {
        if (factory == null)
        {
            Configuration conf = new Configuration();
            conf.AddAssembly(Assembly.GetCallingAssembly());
            factory = conf.BuildSessionFactory();
        }
        return factory.OpenSession();
    }
}

I call the stored procedure
session.CreateSQLQuery("EXEC InsertDoc @Name = N'" + exSample.name + "',@Author = N'" + exSample.author + "',@Link = N'" + exSample.doclink + "'");

In my mapping file I have these settings:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" namespace="WebApplication1" assembly="WebApplication1">
  <class name="WebApplication1.documents" table="documents" lazy="false">
    <id name="id" access="field">
      <generator class="native" />
    </id>
    <property name="name" access="field" column="name" type="String"/>
    <property name="date" access="field" column="date" type="date"/>
    <property name="author" access="field" column="author" type="String"/>
    <property name="doclink" access="field" column="doclink" type="String"/>
  </class>
</hibernate-mapping>

Help me solve this problem or link me to something useful.

A:

See if these links help you:
Using NHibernate With Stored Procedures (from Ayende - the father of NHibernate)
How do I call a stored procedure from NHibernate that has no result?
How to execute Stored Procedure with NHibernate - Working Sample Code

A:

Seems you're missing a Query.executeUpdate() for one, so
session.CreateSQLQuery("EXEC InsertDoc @Name = N'" + exSample.name + "',@Author = N'" + exSample.author + "',@Link = N'" + exSample.doclink + "'").executeUpdate();

should work, but it's much nicer to bind your variables programaticly


Q:

Show Message if results are empty

I have a search form for products. I would like to make sure that it shows me a message when the list is empty, when there is no result.
My code :
<form ng-controller="productCtrl" name="searchForm" ng-submit="searchProduct()" ng-disabled="searchForm.$invalid">
    <input placeholder="Search" type="text" ng-model="form.name" required>
  <ion-list>
    <ion-item ng-repeat="product in list track by $index">{{ product.name }}</ion-item>
  </ion-list>
</form>

thank you :)

A:

You can use ng-if above the ng-repeat
Like this
<div ng-if="list.length<=0" style="color:red;">Error!

Ex:

  <div ng-if="todos.length<=0" style="color:red;">Error!

{{item.color}}

https://jsfiddle.net/vqJ5q/48/


Q:

Replace text in a file?

I am successfully replacing a text in a file.
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)

But how can I replace if I don't know the middle of the text ? For example
example_my("browser.taskbar.lastgroupid", "E7CF176E110C211B");
How to replace the E7CF176E110C211B ?

A:

One way is to use RegEx. You can specify the first and last parts and then use \d+ or better [0-9A-F]+ to match any hex number. So given that the part that you don't know is a hexadecimal number, you can use the following code:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fileReader = System.Text.RegularExpressions.RegEx.Replace(fileReader, "[0-9A-F]+", "bar")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)

This will replace all hexadecimal numbers in the file with the word "bar".
Note that for a text file this kind of global Replace can have undesirable results. For example the above regex will replace letters A to F even within normal text. So you'll probably want to put some kind of limitations such as min. number of digits to make sure it replaces only valid hex numbers. For example you may want to use [0-9A-F]{4,} which will replace only 4 or more consecutive hex digits. But even that is not 100% safe; e.g. it will replace DEAD, FACE, FADE, FACED etc. with the word "bar". To figure out exactly what is 100% safe for your file, you'll need to examine its contents carefully.
Edit
Reading you comments, you can use the following code instead:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fileReader = System.Text.RegularExpressions.RegEx.Replace(fileReader , "lastgroupid"", ""(.+)""\)", "lastgroupid"", ""ANYTHING_YOU_WANT""\)")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fileReader, False)

This will replace all occurrances of hex numbers between  lastgroupid", " AND ") with the string ANYTHING_YOU_WANT.


Q:

Disable past dates in a picker

How can I disable past dates in the picker? I want the users to choose only the future dates. So what I want is to disable the current date and all the past date so that one can only choose the date from tomorrow.
Picker datePicker = new Picker();
datePicker.setUIID("small");
datePicker.setType(Display.PICKER_TYPE_DATE);

A:

The Picker class doesn't allow you to set the min or max dates.  You can file an RFE on this in the CN1 issue tracker.
The Spinner class, however, does allow you to set a minimum and maximum date.  Spinner is marked deprecated since we try to encourage use of Picker when applicable - mainly because it uses the platform's native picker widget when available, and generally results in better UX.  In certain cases, like this, you can fall back to Spinner and it should still be fine.


Q:

Load data at startup in Metro style app

I am trying to develop an app that uses the camera and stores the photo in the app's local folder written in javascript and html5. I have 3 pages that uses the same files(the images) and it is too expensive to load the images at each page's ready section so i was thinking about loading the images to an array or list with the getFilesAsync() method when the app starts up and then making it public with the WinJS.Namespace.define. The solution works for a few amount of data but when a lot of pictures stored in the images folder the async operation takes more time so when I try to access the files on another page it is still undefined.
Do you have any idea how to load data at the launch of the app and make it accessable from other pages and force the program to wait until it finishes? I know this is the exact opposite of async programming but I do not see any other solution. Thank you!

A:

You need to use a promise, and promise chain to allow you to wait on the completion:
var getFiles = Windows.Storage.StorageFolder.getStorageFilderSync("Your folder").then(function(folder) {
    return folder.getFilesAsync();
});

/* somewhere else in your app */
getFile.done(doWorkWithResult);

You can call the done from your other pages; if getFilesAsync has completed, then it will return immediately and won't re-run the query. If it's not ready, then it will just wait until it is complete.
There is a nice sample here that has some more worked examples.


Q:

Display Data from Table with Latest Associated Data from Two Related Tables

I have 3 tables for Authors, Books, and Articles. An Author can have multiple Books and multiple Articles, so those have AuthorId as a foreign key.
Authors

AuthorId
AuthorName

Books

BookId
AuthorId
BookTitle

Articles

ArticleId
AuthorId
ArticleTitle

For each Author, I want to display their name, along with the Titles of their most recent Book and their most recent Article. (Assume that the row with the largest BookId/ArticleId is the latest. Also assume that each author has at least one Book and one Article.)
In other words, each row would look something like this:

John Smith | Blacksmithing Handbook | Newest Tools for 2019

I can't figure out how to write the query for this.
SELECT AuthorName, BookTitle, ArticleTitle
FROM Authors
INNER JOIN Books ON Books.AuthorId = Authors.AuthorId
INNER JOIN Articles ON Articles.AuthorId = Authors.AuthorId
ORDER By AuthorName

This, of course, results in multiple rows for each Author, but I can't figure out how to get the result I want.
Any help would be greatly appreciated! (I'm using SQL Server 2016.)

A:

This is a case where outer apply can be quite useful:
SELECT a.AuthorName, b.BookTitle, ar.ArticleTitle
FROM Authors a OUTER APPLY
     (SELECT TOP (1) b.*
      FROM Books b
      WHERE b.AuthorId = a.AuthorId
      ORDER BY b.BookId DESC
     ) b OUTER APPLY
     (SELECT TOP (1) ar.*
      FROM Articles ar
      WHERE ar.AuthorId = a.AuthorId
      ORDER BY ar.ArticleId DESC
     ) ar
ORDER By a.AuthorName;

APPLY implements something called a "lateral join".  This is (another) very powerful JOIN method.  It is akin to correlated subqueries, but instead of being limited to a single column and a single row, it can return multiple columns and multiple rows.


Q:

Grant access for any logged in user for common database

In SQL server 2008, I have one database that is a common database that is accessed thru stored procedures in all other databases. Each of the other databases have their own login.
I need a way that all logged in users can access that common database. I know I could create a user for the common database for each login but I would need to create over 100 users in the database then.
Is there a better way?

A:

I believe you can create a user account in that database, using WITHOUT LOGIN. This will create it where you can grant execute as permissions to the other users for any particular stored procedure in that common database. They don't have to use a password for it so you control it by who can EXECUTE AS with it. Here is a pretty good write-up on how it could be used, near the end he talks on how it can be used outside the context of the database.


Q:

¿Cuál es el chiste más antiguo escrito en español?

Trasteando en el CORDE me encontré con este texto:

    Yendo dos señoras por la calle, la una de ellas que se decía Castañeda, soltósele un trueno bajero, a lo cual dijo la otra:
      —Niña, pápate esa castaña.
      Echándose de ellos por tres veces arreo, y respondiendo la otra lo mismo, volviéronse y vieron un doctor en medicina que les venía
  detrás, y, por saber si había habido sentimiento del negocio,
  dijéronle:
      —Señor, ¿ha rato que nos sigue?
      Respondió:
      —De la primera castaña, señoras.
Juan de Timoneda, "Buen aviso y portacuentos", España (1564)

Este relato corto, uno de los muchos del libro mencionado, es lo que hoy conocemos como un chiste: "Dicho u ocurrencia agudos y graciosos." Los chistes suelen ser breves, expresados en unas pocas frases (aunque hay excepciones). Por tanto, no estoy buscando aquí diálogos humorísticos presentes en comedias, sino relatos breves, no insertados en obras más largas, que puedan constituir un chiste por sí mismo sin formar parte de un contexto más grande. Y por breve me refiero a relatos que puedan ser repetidos de memoria y de forma íntegra por cualquier persona con simplemente ser oídos una vez.
Así pues, ¿cuál podría ser considerado el chiste más antiguo escrito en español?
Por tratar de centrar un poco el tiro, en la Wikipedia se comenta lo siguiente:

En España, las primeras compilaciones de chistes se encuentran en el género renacentista de las misceláneas del siglo XVI y XVII, de ámbito especialmente cortesano, destacando en especial Pero Mexía [1497-1551], quien los agrupó por temas, entre muchos otros entre los que cabe mencionar a Juan Timoneda [1518-1583]. Algunos poetas cultivaron especialmente este tipo de divertimentos cortesanos, como por ejemplo Baltasar del Alcázar [1530-1606].

El ejemplo que encontré es precisamente de Juan de Timoneda. Luego, y salvo que algún escritor publicara algún chiste suelto intercalado en alguna obra mayor, básicamente habría que mirar cuál es la primera de esas compilaciones.

A:

VN tamborinero tenía una mujer tan contraria a su opinión que nunca cosa que le rogara podía acabar con ella que la hiziesse.
  Una vez, yendo de un lugar para otro porque havía de tañer en unos desposorios, y ella cavallera en un asno con su tamborino encima, al passar de un río díxole: "Muger, catad no tangáys el tamborino, que se espantará el asno." Como si dixera "tañedlo": en ser en el río sonó el tamborino, y el asno, espantándose, púsose en el hondo, y echó vuestra muger en el río. Y él, por bien que quiso ayudalle, no tuvo remedio.
  Viendo que se havía ahogado, fuela a buscar el río arriba. Díxole uno que lo estava mirando: "Buen hombre, ¿qué buscáys?" Respondió: "A mi muger, que se es ahogada, señor." "¿Y contrario la havéys de buscar?" Dixo: "Sí, señor, porque mi muger siempre fue contraria a mis opiniones."

Este es el primer cuento del Sobremesa y alivio de caminantes, editado en 1563. Es una de las primeras obras de Juan de Timoneda, un año anterior al Buen avíso y portacuentos mencionado por OP, y se puede consultar en formato HTML en este enlace.
Creo que estaremos todos de acuerdo en que es un texto gracioso y, de hecho, muestra todas las características de un chiste (una introducción, un tono desenfadado, la gracia final que induce a risa) según se describen en Wikipedia.
No pretendía publicar esto como respuesta, dado que OP indica que los primeros recopilatorios de chistes serían (de nuevo según Wikipedia) los hechos por Pero Mexía medio siglo antes:

En España, las primeras compilaciones de chistes se encuentran en el género renacentista de las misceláneas del siglo XVI y XVII, de ámbito especialmente cortesano, destacando en especial Pero Mexía [1497-1551], quien los agrupó por temas

Decidido a encontrar dichas compilaciones, me he estado leyendo por encima las principales obras del tal Pero Mexía: principalmente la Silua de varia lecion de 1540, y los Coloquios o dialogos de 1545. Ambas tratan temas relativamente serios (filosofía, ciencia, religión) y no he notado tono jocoso en los fragmentos que he leído. Doy por hecho que la Historia del emperador Carlos V y la Historia imperial y cesarea, del mismo autor, también son serias.
El caso es que no he encontrado entre los textos de Pero Mexía ningún recopilatorio de chistes, mucho menos por temas.
De ser cierto esto último, entonces el Sobremesa y alivio de caminantes de Juan de Timoneda sería posiblemente el primer recopilatorio de chistes impreso en español, y su "Cuento primero" el primer chiste.

A:

Entre los que se consideran los chistes más antiguos hay uno que se cree tiene unos 2000 años, hay varias versiones que han aparecido en distintos libros a lo largo del tiempo, esta una de ellas (el original es en latín):

Aquel hombre, en cambio, que todo el mundo en Sicilia estaba de
  acuerdo en que era sumamente parecido al gobernador de la provincia,
  era de espíritu insolente. En efecto,como el procónsul le dijera que
  le asombraba que fuera tan parecido a él, dado que su padre nunca
  había venido a Sicilia, aquél replicó: “Pero el mío sí que fue a
  Roma”. Con esta broma vengó la castidad ultrajada de su madre
  arrojando, a su vez, la sospecha sobre la madre de aquel, con más
  audacia de la que convenía en alguien sometido a las varas y segures.

Hechos y dichos memorables - Valerio Máximo

Pedro Mexía también recogió esta anécdota, ya traducida al español, en su libro Silva de varia lecion (1540), otros lo hicieron después. Este es el fragmento:

También le pasó a Octaviano César otra graciosa cosa con un mancebo
  que vino a Roma en el tiempo en que él imperaba en ella. Fue ésta: que
  vino a Roma un mancebo que parecía tanto al mismo Octaviano en el
  gesto, que a maravilla era mirado por todos; y siendo avisado de esto
  Octaviano, luego lo hizo traer ante sí, donde se notó y certificó más
  la grande similitud que había entre ellos. El emperador, como era de
  dulce conversación y se preciaba de decir algunas veces cosas agudas y
  graciosas, viendo que todos decían que le parecía mucho, le dijo al
  mancebo: “Dime, hermano, ¿vino tu madre alguna vez a Roma?” El mozo
  entendió la malicia y respondióle: “Mi madre, señor, nunca vino a
  Roma; pero mi padre vino muchas veces”, motejándole a él de lo que él
  había sido tocado.

Se puede consultar aquí: https://archive.org/stream/silvadevarialecc00mex#page/112/mode/2up

No sé si en el libro habrá más historias de este tipo, como dice @walen los temas son bastante serios y por lo que el propio Pedro Mexía dice no parece muy dado a hablar de temas vulgares:

Por lo qual yo, preciándome tanto de la lengua que aprendí de mis
  padres como de la que me mostraron preceptores, quise dar estas
  vigilias a los que no entienden los libros latinos, y ellos
  principalmente quiero que me agradezcan este trabajo, pues son los más
  y los que más necessidad y desseo suelen tener de saber estas cosas.
  Porque yo, cierto, he procurado hablar de materias que no fuessen muy
  comunes ni anduviesen por el vulgo, o que ellas, de si, fuessen
  grandes y provechosas, a lo menos a mi  juyzio.

Es difícil afirmar categóricamente que es el primer chiste escrito en español pero por lo que sabemos, si no lo es, se le acerca bastante.
ACTUALIZACIÓN:
Según la Wikipedia Hechos y dichos memorables (Factorum ac dictorum memorabilium) se tradujo al español por primera vez en 1395. Si esto es así, el chiste ya estaba escrito en español 145 años antes del libro de Pedro Mexía, aunque sigue siendo el mismo chiste.

Parte de la información la he sacado de aquí:
Un chiste actual de hace 2.000 años


Q:

Nonlinear behavior of function run time

I have a function which computes a sum and depending on the result of the sum does a certain task or gives a warning message. I need to run this function millions of times in a particle trajectory simulation (it calculates the time and position dependent force) and noticed that my code was very slow.
This is my MWE:
#include <stdio.h>
#include <math.h>

int foo()
{
    double sum =0;
    double dummy_sum = 0;

    for (size_t i=0; i<40; i++)
    {
        sum+=1e-2;
        dummy_sum += 1e-2;
    }

    if (sum>5.) // normally this should not happen
    {
        printf("warning message!\n");
        return(-1);
    }
    else if(sum >0)
    {
       // normal behavior
    }

    return(0);
}

int main()
{
   int fooint;

   for(size_t i=0; i<5e9; i++)
   {
       fooint = foo();
       if(fooint!=0)
       {
           return(fooint);
       }
   }
   return 0;
}

I compile with gcc -Ofast -std=c99 test.c -o test.exe using gcc version  4.8.5.
In order to find a way to optimize my function I ran time ./test.exe which indicated a run time of about 38s on my machine.
When I removed the lines
        printf("warning message!\n");
        return(-1);

or the line
        sum+=1e-2;

the run time was reduced to about 6s.
Also when I changed the number of iterations in the function loop to 35 the speed is increased and the run time is 6s. Increasing it to 36 gives a run time of 33s.
I compiled and ran the code on a different machine with the same linux and gcc versions and got similar results (run times were slightly longer as the machine is older).
What may cause this strange behavior?

A:

It is not a strange behavior.
If you remove the lines printf and return(-1) then the function foo is optimized by the compiler and will be just return(0); none of the code inside it will be executed, because the result will not change. The same happens if you comment the code sum+=1e-2;, the compiler knows that the only possible result for the function is return(0);, sum is initialized to 0 and never changes.

A:

It's a GCC bug. Clang optimises your code properly to
foo:                                    # @foo
        xor     eax, eax
        ret
main:                                   # @main
        xor     eax, eax
        ret

at near-zero run time.
Live demo


Q:

Find the specific consecutive set of numbers in a Javascript array

I want to find a number of times an integer occurs consecutively in an array. I have found one example doing something similar:
const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

let chunks = [];

let prev = 0;
numbers.forEach((current) => {
  if ( current - prev != 1 ) chunks.push([]);

  // Now we can add our number to the current chunk!
  chunks[chunks.length - 1].push(current);
  prev = current;
});

chunks.sort((a, b) => b.length - a.length);

console.log('Longest consecutive set:', chunks[0]);
console.log('Size of longest consecutive set:', chunks[0].length);

I just want to get the number of longest consecutive of 0, like:
result: {
  key: 0
  longestConsecutive: 5
}

Any good solution? Thanks!

A:

You can use Array.prototype.reduce to create an array of sequence lengths for your target value and then use Math.max to get the largest value in that array (which is the length of the longest sequence):

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293];

function max_consecutive ( arr, value ) {
  return Math.max( ...numbers.reduce( (sequence_lengths, x) => {
      x === value ? sequence_lengths[0]++ : sequence_lengths.unshift(0);
      return sequence_lengths;
    }, [0]
  ) );
}

console.log( max_consecutive(  numbers, 0 ) );
console.log( max_consecutive(  numbers, 1 ) );
console.log( max_consecutive(  numbers, 293 ) );
console.log( max_consecutive(  numbers, 296 ) );

A:

Perhaps you could do something like the following:

const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293,91];

function findConsecCount(value) {

  var startIndex = -1
  var result = 0

  for(var i = 0; i < numbers.length; i++) {

    if(numbers[i] === value) {
      if(startIndex === -1) {
        startIndex = i
      }
    }

    if(numbers[i] !== value) {
      if(startIndex !== -1) {
        result = Math.max(result, i - startIndex)
        startIndex = -1;
      }
    }
  }

  if(numbers[numbers.length - 1] === value) {
    if(startIndex !== -1) {
      result = Math.max(result, i - startIndex)
      startIndex = -1;
    }
  }

  return {
    key : value,
    longestConsecutive : result
  }
}

console.log( findConsecCount(0) )
console.log( findConsecCount(293) )
console.log( findConsecCount(296) )
console.log( findConsecCount(91) )


Q:

"I want to read this book" and "I want to be reading this book"

I would like to ask about the difference in meaning of 2 following sentences:

I want to read this book
I want to be reading this book

I understand that both generally mean "want to do someething" but also think that there should be some difference here.
Especially with the second sentence, I encounter the structure "to be V-ing" a tons of times but don't really get it, e.g. "I will be singing/talking...." ; "Tell me what you'd like to be doing right now..." to name just a few.

A:

I want to read this book.

This means that, at some point in time, and perhaps not all at once, you want to read the whole book. Perhaps you will read a chapter a day.

I want to be reading this book.

This means that you want to be engaged in the act of reading the book right now.


Q:

Multiple Entrypoints in Struts Action (Migration Struts 2.2.3 -> 2.3.1)

I have an action in struts.xml
<action name="reprint" class="reprintAction">
        <result name="success" type="redirectAction">
            <param name="actionName">reprint</param>
            <param name="namespace">/x</param>
            <param name="errorFlag">${errorFlag}</param>
            <param name="message">${message}</param>
        </result>
        <result name="view">/jsp/reprintOverview.jsp</result>
</action>

a JSP:
<s:form action="reprint">
    <s:select name="selectedPdfPrinter" list="shopPdfPrinterList" listKey="deviceId" listValue="deviceId" theme="simple"/>
    <s:submit value="Print" theme="simple" method="shopPdfReprint"/>
</s:form>

with several form elements, all bound to one action.
Each form has an individual submit-button with a distinct method (e.g. "shopPdfReprint").
Each method is mapped on to a method in the corresponding class.
Everything is working fine with Struts 2.2.3. But after Migration to 2.3.1 the method-mapping is not working. Instead calling the corresponding method (e.g. "shopPdfReprint"), only the execute-method of the class is invoked.
I've looked at the Docs, but unfortunately found no clue, how to adapt to 2.3.1
Anybody ran into this? Help is appreciated :]

A:

This happens because you have turned off DMI. The method attribute works with submit tag as before even after resent security fixes. Enable DMI using the constant
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>

let me know if it didn't work.


Q:

CakePHP month names translations

What is the best way to translate months names into another language when I use
$form->input('date_field');

A:

The month names are already wrapped in __() so you can just provide the translations (as per http://book.cakephp.org/1.3/en/The-Manual/Common-Tasks-With-CakePHP/Internationalization-Localization.html) and it should work.


Q:

4-way car connector to 7-way trailer connector

I bought a CURT custom wiring harness that plugs into vehicle tail light assembly to provide a 4-way flat socket. It has a simple plug & play design that eliminates the need for cutting and splicing of the car's original harness. It provides a wire for left turn/stop, a wire for right turn/stop, a wire for tail/side markers/license plate, and the 4th wire for the ground.
Basically this 4-way socket was supposed to be used as in the diagram provided.
The problem is that I am supposed to hook that socket into a trailer with a 7-way socket (ISO 1724).
Usually I am trying to avoid buying stuff that/if I can make as a DIY project.
Obviously I can bridge few of those 4-way socket wires to the 7-way socket:

the white ground goes to the ground (pin #3 on the 7-way socket)
the brown tail/license/side markers goes to the brown/black (pin #5 and #7 on the 7-way socket)
the green right signal/stop light goes to green (pin #4 on the 7-way socket)
the yellow left signal/stop light goes to the yellow (pin #1 on the 7-way signal)

So far so good. But what about the brake lights?
The 4-way provided assembly seems to use the same bulbs, both for turn signal and brake lights. So when the car wants to signal it probably sends a intermittent voltage through that wire, thus blinking. When the car brakes it sends a continuous (non-intermittent) voltage through that wire to the same common-shared bulb (so we interpret that as "the brake/stop light", because it does not blink). This make me think that with a 4-way wiring you cannot have both, the turn signal and break light at the same time, because these 2 functions share a common wire/bulb (as I said earlier, is the car that simulates these functions via intermittent/continuous voltage applied to the wire).
The 7-way socket (see ISO 1724) has a separate pin for brakes/stop lamps: the red pin #6.
So basically, the problem I have is to find how to connect the green/yellow wires from the 4-way socket to the pin #6 on the 7-way connector.
If we assume that we just take the yellow/green from the 4-way socket and to link them to the pin #6 it would mean that (1) the turn signal will behave like the emergency lights and nonetheless the stop lamps will do the same and (2) while braking both the turn signal lamps and the brake lamps will light.
OK, instead of using both the green/yellow 4-way harness wires to hook them to the pin #6 (brake) on the 7-way socket I could use a single one (let's say the Right). This means that while I am using the left turn signal it would be OK, while using the right turn it will flash both the right turn signal lamp but also the stop lights (which will look like the emergency lights). So this option is not working as well.
I don't see any simple solution (a wiring solution) to the problem above. The only way I know it will work is by the means of an electronic circuit that will take the advantage of the fact that the turn signal has a is intermittent voltage while the stop lights has a continuous voltage.
Any idea/hint/tips that could help me take the fog from my eyes?
Thanks in advance for (1) you patience and (2) for your help.

A:

Have you actually tried hooking it up as you suggested and ignoring pin 6 (circuit 54) on the trailer connector? I think it is likely that the trailer is wired with a single filament for the turn signals and brake lights and that pin 6 is not connected.
One of the common ways of providing braking on a trailer towed by a car is with electric brakes. Pin 6 would be used to control the brakes. But take a look at the note for pin 6 on the Wikipedia article, there are a lot of other uses for that pin. For example besides brake control and separate brake lights, it gets used for:

Rear fog lights.
Backup (reversing) lights.
12 V power to the trailer (switched and unstitched)

If you are in an area where 7-pin connectors are common, and especially if separate bulbs/filaments are used for turn signals and brake lights then you may be better off getting a different wiring harness for the towing vehicle. In the US the flat 4-wire connector and combined brake/turn signal lights on the trailer are still common, but more and more cars have separate bulbs or filaments for the brake and turn signals so the purpose of the CURT harness that you bought is to take a vehicle that starts off compatible with a 7-pin connector and provide the outputs necessary for a trailer without the separate brake/turn signals.

A:

OK, so the converter combines both the brake/turn signal into a single wire designed for a dual-filament bulb. It will send different voltage to the bulb such that either one filament is light or the other, or even both at the same time (read more).
This means that is the converter is meant for the 4-pin connector only and will not work with a 7-way socket (unless reverse engineering the whole thing). The simplest solution is to use a 7|13 -pin car specific tow hitch wiring kit (like Thule/Brink 732614) or a generic one (like AC UN-05 flash control). There are many products on the market (especially made in Germany, search for e-satz 13 polig universal).
Hope it helps!


Q:

Replace Variable Inside @content Directive in SASS Mixin

I'm trying to figure out a DRY and readable way to loop through color classes for each of my design patterns. A nice way I thought I could do this is to pass the CSS properties that need to be changed for each pattern to a mixin along with a variable, and the mixin would swap out the variable inside the @content declaration:
$color-list: (
    "c1" : #ed0ead,
    "c2" : #12bc21,
    "c3" : #2666cc
);

@mixin color-variants {
    @each $class, $color in $color-list {
        &.#{$class} {
            @content;
        }
    }
}

.my-module {
    padding: 1rem;
    background-color: #fff;
    border-top-size: 5px;
    border-top-style: solid;
    @include color-variants {
        border-top-color: $color;
    }
}

.another-module {
    padding: 1rem;
    border-radius: 5px;
    border-size: 2px;
    border-style: solid;
    @include color-variants {
        background-color: rgba($color, 0.5);
        &:hover {
          color: $color;
        }
    }
}

Unfortunately SASS doesn't parse the @content declaration along with the mixin variables, so I get a Undefined variable: "$color" error.
Is it possible to do something like this with existing SASS tools?

A:

Yes, it is. You can use !global flag creating a global variable that you can read also out of mixin scope.
$color-list: (
    "c1" : #ed0ead,
    "c2" : #12bc21,
    "c3" : #2666cc
);

@mixin color-variants {
    @each $class, $color in $color-list {
        $myColor: $color !global;
        &.#{$class} {
            @content;
        }
    }
}

.my-module {
    padding: 1rem;
    background-color: #fff;
    border-top-size: 5px;
    border-top-style: solid;
    @include color-variants {
        border-top-color: $myColor;
    }
}

.another-module {
    padding: 1rem;
    border-radius: 5px;
    border-size: 2px;
    border-style: solid;
    @include color-variants {
        background-color: rgba($myColor, 0.5);
        &:hover {
          color: $myColor;
        }
    }
}

This is a sassmeister for you: https://www.sassmeister.com/gist/8f90133f3ee1d2e67e21f086711cee39


Q:

Search for substring and store another part of the string as variable in perl

I am revamping an old mail tool and adding MIME support. I have a lot of it working but I'm a perl dummy and the regex stuff is losing me.
I had:
foreach ( @{$body} ) {

   next if /^$/;

   if ( /NEMS/i ) {
      /.*?(\d{5,7}).*/;
      $nems = $1;
      next;
   }

   if ( $delimit ) {
      next if (/$delimit/ && ! $tp);
      last if (/$delimit/ && $tp);

      $tp = 1, next if /text.plain/;
      $tp = 0, next if /text.html/;
      s/<[^>]*>//g;
      $newbody .= $_ if $tp;
   } else {
      s/<[^>]*>//g;
      $newbody .= $_ ;
   }
}  # End Foreach

Now I have $body_text as the plain text mail body thanks to MIME::Parser. So now I just need this part to work:
foreach ( @{$body_text} ) {

   next if /^$/;

   if ( /NEMS/i ) {
      /.*?(\d{5,7}).*/;
      $nems = $1;
      next;
   }
}  # End Foreach

The actual challenge is to find NEMS=12345 or NEMS=1234567 and set $nems=12345 if found. I think I have a very basic syntax problem with the test because I'm not exposed to perl very often.
A coworker suggested:
foreach (split(/\n/,$body_text)){

    next if /^$/;

    if ( /NEMS/i ) {
        /.*?(\d{5,7}).*/;

        $nems = $1;
next;

    }
}

Which seems to be working, but it may not be the preferred way?
edit:
So this is the most current version based on tips here and testing:
foreach (split(/\n/,$body_text)){

    next if /^$/;

    if ( /NEMS/i ) {
        /^\s*NEMS\s*=\s*(\d+)/i;

        $nems = $1;
    next;

    }
}

A:

Match the last two digits as optional and capture the first five, and assign the capture directly
($nems) = /(\d{5}) (?: \d{2} )?/x;  # /x allows spaces inside

The construct (?: ) only groups what's inside, without capture. The ? after it means to match that zero or one time. We need parens so that it applies to that subpattern only. So the last two digits are optional -- five digits or seven digits match. I removed the unneeded .*? and .*
However, by what you say it appears that the whole thing can be simplified
if ( ($nems) = /^\s*NEMS \s* = \s* (\d{5}) (?:\d{2})?/ix ) { next }

where there is now no need for if (/NEMS/) and I've adjusted to the clarification that NEMS is at the beginning and that there may be spaces around =.  Then you can also say
my $nems;

foreach ( split /\n/, $body_text ) {
    # ...
    next if ($nems) = /^\s*NEMS\s*=\s*(\d{5})(?:\d{2})?/i;
    # ...
}

what includes the clarification that the new $body_text is a multiline string.
It is clear that $nems is declared (needed) outside of the loop and I indicate that.
This allows yet more digits to follow; it will match on 8 digits as well (but capture only the first five). This is what your trailing .* in the regex implies.
Edit   It's been clarified that there can only be 5 or 7 digits.  Then the regex can be tightened, to check whether input is as expected, but it should work as it stands, too.

A few notes, let me know if more would be helpful

The match operator returns a list so we need the parens in ($nems) = /.../;
The ($nems) = /.../ syntax is a nice shortcut, for ($nems) = $_ =~ /.../;.
If you are matching on a variable other than $_ then you need the whole thing.
You always want to start Perl programs with
use warnings 'all';
use strict;

This directly helps and generally results in better code.

The clarification of the evolved problem understanding states that all digits following = need be captured into $nems (and there may be 5,(not 6),7,8,9,10 digits).  Then the regex is simply
($nems) = /^\s*NEMS\s*=\s*(\d+)/i;

where \d+ means a digit, one or more times. So a string of digits (match fails if there are none).


Q:

What does the -g flag mean in npm install -g

I'm interested to understand what the -g flag means.
When I type npm install -g bower grunt-cli in terminal, I get an error saying:
'bower ESUDO         Cannot be run with sudo'

I get the same error if I type sudo npm install -g bower grunt-cli. I have tried uninstalling and reinstalling everything without sudo, and I still get the same error. Does -g mean sudo? If so, I don't see why!
I've tried looking for -g flags/tags/options etc in google but I still wasn't sure what this flag does!
Thanks

A:

No, actually -g means global install (e.g. in /usr/bin or so). And as u see, that stuff doesn't happy to be running with sudo (or root) - so just install it from user.
Btw: you can set global location for your current user, in this case -g will install packages in specified location (and not actually globally). Create ~/.npmrc and set prefix to whatever location you want.
Check this link


Q:

How can I update a listView with a new item?

I have 2 fields
string Name
and
int Age
How do I add this information to the collection that is bound to the listView when a user presses a Button?

A:

Here is a simple example. It assumes the use of the RelayCommand and ObservableObject classes described in this article.
MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="60*" />
        <RowDefinition Height="20*" />
        <RowDefinition Height="20*" />
    </Grid.RowDefinitions>

    <ListBox ItemsSource="{Binding People}"
             Margin="5">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text=", " />
                    <TextBlock Text="{Binding Age}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <Grid Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="50*" />
            <RowDefinition Height="50*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        Name:
        Age:

        <TextBox Grid.Column="1"
                 Margin="5"
                 Text="{Binding Name}"/>
        <TextBox Grid.Column="1"
                 Grid.Row="1"
                 Margin="5"
                 Text="{Binding Age}"/>

    </Grid>

    <Button Grid.Row="2"
            Margin="5"
            Command="{Binding AddPersonCommand}">Add Person</Button>

</Grid>

Next, create a simple class for holding your information.
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Finally, create a simple viewModel for manipulating the information.
public class AppViewModel : ObservableObject
{
    private int _age;
    private string _name;

    private RelayCommand _AddPersonCommand;

    private ObservableCollection<Person> _people = new ObservableCollection<Person>()
    {
        new Person { Name="Ben", Age=26 },
        new Person { Name="George", Age=40 },
        new Person { Name="Amy", Age=38 },
        new Person { Name="April", Age=22 },
        new Person { Name="Mick", Age=45 },
        new Person { Name="Steph", Age=32 },
        new Person { Name="Mel", Age=35 },
        new Person { Name="Emma", Age=28 },
    };

    public IEnumerable People
    {
        get { return _people; }
    }

    public ICommand AddPersonCommand
    {
        get
        {
            if (_AddPersonCommand == null)
            {
                _AddPersonCommand = new RelayCommand(p=> this.AddPerson());
            }
            return _AddPersonCommand;
        }
    }

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            NotifyPropertyChanged("Name");
        }
    }

    public int Age
    {
        get { return _age; }
        set
        {
            _age = value;
            NotifyPropertyChanged("Age");
        }
    }

    private void AddPerson()
    {
            Person p = new Person();
            p.Name = _name;
            p.Age = _age;
            _people.Add(p);
    }
}