text:
Q: Powershell script FTP I need to automate a FTP process which downloads the most recent files from the previous day the files all have different names and all end with the *1.DAT extension.
I have in the passed had real success using the FTP Client module and this is what i normally use when uploading and downloading files using FTP. The problem I have hit is that this works with the -Credentials switch and expects the password to be encrypted, the destination  ftp server which is not in my control does not understand the credentails object when it is passed to the server and fails with a 550 error
I have seen many other posts on this site about using FTP with powershell but none really seem to be doing what i want in terms of getting only the previous days files.
can anyone help
Thank you
code as requested
`try
{
    Add-Type -Path WinSCPnet.dll
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName = "IPServer"
$sessionOptions.UserName = "username"
$sessionOptions.Password = "Password"
$sessionOptions.PortNumber = 21
#$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

$session = New-Object WinSCP.Session
$session.XmlLogPath = "D:\scripts\Xml.log"
#$session.SessionLogPath = "D:\scripts\Logs\Session.log"

$date = Get-Date
$date1 =$date.AddDays(-1)
$date2str = $date1.ToString("yyyyMMdd")

try
{
    # Connect
    $session.Open($sessionOptions)

    $localPath = "D:\Eastcoast\Input\Data\Barcode_files"
    $remotePath = "/"

    # Gel list of files in the directory
    $directoryInfo = $session.ListDirectory($remotePath)

    # Select the most recent file
    $latest = $directoryInfo.Files | Where-Object { -not $_.IsDirectory}

        Foreach ($file in $latest) {
        $filedate = $file.LastWriteTime.ToString("yyyyMMdd")
        If ( $filedate -eq $date2str) { $session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath).Check()}

        }`


text:
Q: Convert Nested IF Excel Statement to SQL Could someone please help me convert this nested IF formula in Excel to a CASE statement (or whatever is more efficient) in SQL?:
=IF(B11="",IF(OR(R11="STORY.COM",R11="EXPERIENCE"),FALSE,IF(AE11="Yes",TRUE,IF(AE11="Unknown",IF(D11="",IF(E11="",FALSE,E11),D11),FALSE))),B11)

Thank you in advance

A: If you'll scroll through left to right and put case.. when.. then.. else..end, you'll end up with the following:
case when B11 = ''
        then case when R11 = 'STORY.COM' or R11 = 'EXPERIENCE'
                then 'False'
                    else
                        case when AE11='Yes'
                            then 'True'
                        else
                            case when AE11='Unknown'
                                then case when D11=''
                                        then case when E11=''
                                            then 'False'
                                        else E11 end
                                else D11 end
                            else
                                'False' end end end
                else
                    B11 end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to override a style of a specific Joomla module? I have so many modules and I am showing border to each module.
Below is what I have
div.ja-moduletable-inner,
div.moduletable-inner {
  background: none;
  padding: 1.5em;
  box-shadow: 0px 0px 3px 3px rgba(0,0,0,.25);
}

 ...

 ...

 ...

Note : These modules are added by-default by Joomla, so I can't handle this. What I want is using Javascript, I want to add class in Mod149 so that I will have it as

`
                                           ^^^^^^^^^^^^^^

and I will have in css as
div.newMyOwnClass {
  box-shadow: 0px 0px 0px 0px rgba(0,0,0,.25);
                      ^^^^^^^
}

Any idea how to add this class to the element inside
 in Javascript (no jQuery!)?

A: 2 ways to approach your problem:
1. Pure CSS
Just increase the specifity of your selector:
#Mod149 > div.moduletable-inner {
   box-shadow: 0px 0px 0px 0px rgba(0,0,0,.25);
}

2. Using JavaScript
To add the class either use the classList.add method, or update the className attribute:
var elem = document.querySelector('#Mod149 > .moduletable-inner');
if (elem) {
    elem.className += ' newMyOwnClass';
}

To insert the CSS, either inject a


text:
Q: Symbols of animals I'm wondering whether there are symbols implemented in LaTeX to create animals.
For example like the \Bat in the marvosym, but for other animals.
I'm especially interested in \Dolphin ;-)

A: Unfortunately, Detexify doesn't find anything, and neither does The Noun Project that Martin Scharrer wrapped into a .sty file.
However, if you manage to find a suitable symbol (with the right license), you could just define your own command to include it in a document. For example, on her site mytimetocraft.com, Beth has published a nice SVG of a dolphin. The images posted on that site are free for commercial and non-commercial use.
You could either convert that SVG to a PDF file, or you could just extract the path from the file and let TikZ draw it for you. By setting the scale factor as a product of the ex unit, the symbol will scale with the surrounding text.
Look, a \Dolphin!

\Huge Wow! It's so big and blue! \Dolphin[blue,xscale=-1]

will yield

Here's the code for the above example:
\documentclass[a4paper,11pt]{article}
\usepackage{tikz}
\usetikzlibrary{svg.path}

\newcommand{\Dolphin}[1][]{%
    \tikz \fill [scale=1ex/500,yscale=-1,#1] svg "M 240,792 C 236.7964,782.29301 227.32595,769.18429 218.95458,762.8695 C 210.58318,756.55478 193.07658,741.91749 180.05096,730.34232 L 156.36806,709.29648 L 141.17601,721.53827 C 132.82037,728.27131 116.86485,736.20204 105.71929,739.16215 C 94.57372,742.12228 76.825609,750.15889 66.279001,757.02126 C 42.749986,772.33104 35.286663,768.91329 39.793018,744.89235 C 49.786747,691.62137 86.56609,637.47901 123.0161,622.38091 C 133.32885,618.10921 138.97291,610.6592 143.54681,595.28094 C 156.31386,552.35575 185.13223,485.10659 210.50659,439.02657 C 285.62548,302.61033 377.12604,221.91941 502.90248,181.17368 L 545.4538,167.38902 L 523.9559,153.16241 C 512.13201,145.33777 493.01385,137.67119 481.47106,136.12559 C 441.72739,130.80384 454.06939,100.38528 495.97229,100.38528 C 525.1625,100.38528 588.32595,117.28333 612.47161,131.55225 C 631.20187,142.62093 638.05903,143.46536 711.12662,143.70143 C 826.20118,144.07318 875.39668,159.99674 936.18511,216.548 C 957.70508,236.568 977.32088,249.47994 997.76359,257.08148 C 1037.1384,271.7229 1050.5601,280.83354 1050.5601,292.92001 C 1050.5601,304.96929 1043.1872,306.72156 979.27795,309.86153 C 937.41314,311.91844 922.54209,315.36478 870.35529,335.10414 C 837.1142,347.67736 806.21965,359.09969 801.70072,360.48707 C 797.18181,361.87448 788.5903,373.11962 782.60856,385.47631 C 769.33352,412.89887 732.8923,450.74636 708.71893,462.21739 C 687.47223,472.29962 645.39097,477.58347 636.22902,471.31951 C 626.59388,464.73198 633.77941,451.7414 651.00501,444.60631 C 668.76327,437.2506 688.54805,412.99772 693.73219,392.22992 L 697.39133,377.57125 L 659.92998,381.16743 C 639.32621,383.14537 594.48504,391.40641 560.28293,399.5254 C 408.28252,435.60753 289.59011,503.28314 223.04114,591.81285 L 199.83212,622.68772 L 222.77838,652.2359 C 249.05732,686.07569 265.30365,731.48301 265.30365,771.09095 C 265.30365,810.05728 250.10447,822.61677 240,792 M 885.93164,242.20228 C 889.77822,235.9783 875.83562,229.90601 868.33788,234.5399 C 865.37262,236.37259 864.25805,239.99423 865.8612,242.58811 C 869.72788,248.8446 881.97191,248.60916 885.93164,242.20228 z";%
}

\begin{document}
Look, a \Dolphin!

\Huge Wow! It's so big and blue! \Dolphin[blue,xscale=-1]
\end{document}

A: If you're interested in what symbols you can access through LaTeX commands, you might find the Comprehensive LaTeX Symbol List to be of some use to you.
But you won't find many animal symbols there. The few that I have managed to glean are not actually dingbats but symbols from the Phaistos Disk, accessible through the package phaistos.
Examples from the symbol list I've mentioned (p. 81):

(The cat symbol is lovely, by the way.) Still, you won't find any dolphins there, I'm sorry to say!

A: There are dedicated packages to add animals (and other beings) to latex:
\documentclass{standalone}

\usepackage{tikzlings}
\usepackage{tikzducks}

\begin{document}

\tikz\bear;
\tikz\penguin;
\tikz\marmot;
\tikz\koala;
\tikz\owl;
\tikz\coati;
\tikz\snowman;
\tikz\rhino;
\tikz\moles;
\tikz\sloth;
\tikz\pig;
\tikz\cat;
\tikz\hippo;
\tikz\panda;
\tikz\mouse;
\tikz\duck;

\end{document}

(the code above need the development version of the tikzlings package, which is available from https://github.com/samcarter/tikzlings)


text:
Q: Why do iOS keychain values not change without leaving the ViewController? I have an abstraction on the iOS Keychain API that seems to work well.  Basically, it has:
public string GetGenericPasswordField(string account)
{
    var record = SecKeyChain.QueryAsRecord(query, out code);
    if (code == SecStatusCode.ItemNotFound)
        return null;
    return NSString.FromData(record.ValueData, NSStringEncoding.UTF8);
}

public void SetGenericPasswordField(string account, string value)
{
    if (value == null)
    {
        SecKeyChain.Remove(record);
        return;
    }
    var record = new SecRecord (SecKind.GenericPassword) {
        Service = service,
        Label = label,
        Account = account,
        ValueData = NSData.FromString (value),
    };
    SecStatusCode code = SecKeyChain.Add (record);
    if (code == SecStatusCode.DuplicateItem)
    {
        // (remove and re-add item)
    }
}

I have used this abstraction on my app's settings screen to save values while leaving, and then load those values elsewhere in the app.
But I've run into an issue where saving a value does not appear to take effect if you don't leave the current ViewController.  What I'm doing is analogous to:
if (Keychain.GetGenericPasswordField("RemoteLogin") == null)
{
    var remotePassword = GetFromDialog();
    Keychain.SetGenericPasswordField("RemoteLogin", Hash(remotePassword));
    // Safe to assume the RemoteLogin password got saved, right?
}

// Later on...

if (Keychain.GetGenericPasswordField("RemoteLogin") == null)
{
    // This block is being executed
}

I've stepped through the code in the debugger to confirm that things are as I'm describing them, and that my abstraction method really is getting a SecStatusCode.ItemNotFound back, meaning null is the appropriate value to return.
I worked around this once by moving the first half of my code back to a previous ViewController, and for some reason that seemed to wake it up, or clear out whatever caching is taking place.  But now I've encountered another situation where that's not really practical.
Why is this happening?  Is my abstraction leaking?


text:
Q: SQL Server : select distinct data with transpose I have data in a table like this:
+-----------+-------------+-----------------+------+----------+
|   make    |    model    |     variant     | year |  price   |
+-----------+-------------+-----------------+------+----------+
| CHEVROLET | SPARK       | 08LS            | 2018 |  1000000 |
| CHEVROLET | SPARK       | 08LS            | 2017 |  2000000 |
| CHEVROLET | SPARK       | 08LS            | 2016 |  3000000 |
| CHEVROLET | SPARK       | 08LSTRENDY      | 2018 |  4000000 |
| CHEVROLET | SPARK       | 08LSTRENDY      | 2017 |  5000000 |
| CHEVROLET | SPARK       | 08LSTRENDY      | 2016 |  6000000 |
| TOYOTA    | LANDCRUISER | 10042DVX        | 2018 |  7000000 |
| TOYOTA    | LANDCRUISER | 10042DVX        | 2017 |  8000000 |
| TOYOTA    | LANDCRUISER | 10042DVX        | 2016 |  9000000 |
| TOYOTA    | LANDCRUISER | 10042DVX        | 2015 | 10000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2018 | 11000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2017 | 12000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2016 | 13000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2015 | 14000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2014 | 15000000 |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 2013 | 16000000 |
+-----------+-------------+-----------------+------+----------+

I want to select data in below form
+-----------+-------------+-----------------+----------+----------+----------+----------+----------+----------+
|   make    |    model    |     variant     |   2018   |   2017   |   2016   |   2015   |   2014   |   2013   |
+-----------+-------------+-----------------+----------+----------+----------+----------+----------+----------+
| CHEVROLET | SPARK       | 08LS            |  1000000 |  2000000 |  3000000 | NULL     | NULL     | NULL     |
| CHEVROLET | SPARK       | 08LSTRENDY      |  4000000 |  5000000 |  6000000 | NULL     | NULL     | NULL     |
| TOYOTA    | LANDCRUISER | 10042DVX        |  7000000 |  8000000 |  9000000 | 10000000 | NULL     | NULL     |
| TOYOTA    | LANDCRUISER | 10042DVXLIMITED | 11000000 | 12000000 | 13000000 | 14000000 | 15000000 | 16000000 |
+-----------+-------------+-----------------+----------+----------+----------+----------+----------+----------+

Could you please help me to write a query for this?

A: You can do conditional aggregation :
select make, model, variant,
       sum(case when yr = 2018 then price else 0 end),
       sum(case when yr = 2017 then price else 0 end),
       sum(case when yr = 2016 then price else 0 end),
       sum(case when yr = 2015 then price else 0 end)
from table t
group by make, model, variant;


text:
Q: Matching tuples of integers within a range of tuples The following matching switch statement simetimes seems to work and other times when I change the ranges seems that the choices sometimes make no sense. Seems to be random. Can I expect that the setup as below is correct when trying to match a tuple of integers within a range of integers within other tuples?
// tuple case branches

import UIKit

// tuple case branches
let d = (1, 21, 15, 3, 2, 0)

switch d {
case (1...100, 21...100, 14...100, 3...100, 3...100, 0...100):
    println("it's 1st")  // it's 1st
    fallthrough
case (1...100, 21...100, 15...100, 3...100, 2...100, 0...100):
    println("it's 2nd")
    fallthrough
case (1...100, 21...100, 15...100, 3...100, 2...100, 0...100):
    println("it's 3nd")

default:
    println("not 1st or 2nd or 3rd")

A: The switch will only match the cases when each one of the elements strictly falls into that range. So it's like an AND condition of all of the parts of your tuple.
You are also using fallthrough, which means you're always going to see 'it's 3nd' (did you mean 3rd?) when either the second or third case block is seen.
So in this case, because your penultimate tuple value is 2 it isn't appropriate for the first case statement. 2nd and 3nd are printed because you fallthrough to the next one.


text:
Q: Spring servlet mapping not working When I try to load http://localhost:8080/people I receive a 404 page not found error.
This is my servlet mapping iwthin web.xml :
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/people/*</url-pattern>
</servlet-mapping>

Here is how I understand it works :
A url request to http://localhost:8080/people will be intercepted by the servlet "spring" and will invoke the class org.springframework.web.servlet.DispatcherServlet Is this correct ?
Do I need some additional configuration in order for this class to be loaded correctly ?
Update :
Here is the controller :
@Controller
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/")
    public String listPeople(Map<String, Object> map) {

        map.put("person", new Person());
        map.put("peopleList", personService.listPeople());

        return "people";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("person") Person person, BindingResult result) {

        personService.addPerson(person);

        return "redirect:/people/";
    }

    @RequestMapping("/delete/{personId}")
    public String deletePerson(@PathVariable("personId") Integer personId) {

        personService.removePerson(personId);

        return "redirect:/people/";
    }
}

A: Do you have controller backing to support your GET response?
Something like this
@Controller
@RequestMapping(value = "/people")
public class LoginController {

    @RequestMapping(value = "/i_am_here", method = RequestMethod.GET)
    public String firstForm() {
        return "SHOW_ME_THE_JSP_PAGE";
    }
}

Based on above example, this will make your get URL request like -> /people/i_am_here
Method will be invoked and the response could be sent back in JSP.
Checkout this example under Github
https://github.com/hth/StatusInvoke/blob/master/src/com/example/UserController.java


text:
Q: React native changing instance prop not rerender component I have an entity class called order
const order = new Order({status: 'available'});

export default class Order {
  constructor({status}) {
    this.status = status;
  }

  isCanceled() {
    return this.status === CANCELED;
  }
}

when passing order to a component throw mapStateToProps
when the status changes. mapStateToProps will be called again with the new status but the component will not be rendered with the new data
but if I passed the order as a standard object it will re-render with the new data
This code is not working
const mapStateToProps = (state, props) => {
  const order = new Order({status: 'available'});

  return {
    order,
  };
};

This code works
const mapStateToProps = (state, props) => {
  const order = new Order({status: 'available'});

  return {
    order: {...order},
  };
};

I need the first code to work as I use some functions from the object inside the component like isCanceled()

A: Hello all I knew what was the issue
the problem was in my reducer as I was changing in the state directly so the method wasn't pure function. So, react didn't recognize the change in props
this link has an example
React Native components not re-render if props changed

A: can you try this, while keeping the {...order} (2nd method you're using)
export default class Order {
  constructor({status}) {
    this.status = status;
    this.isCanceled = this.isCanceled; //add this line
  }

  isCanceled() {
    return this.status === CANCELED;
  }
}


text:
Q: How to replace New line and ^M chars with ~~ in Unix I am not good at unix.
I have a csv file which I is having multiple columns. Out of which, one column is containing new line and ^M chars. I need to replace all of them between two " (which is a single cell value) by ~~ so that I can treat the cell value as single field. Here is the sample file :
"id","notes"
"N001","this is^M
test.

Again test

"
"N002","this is perfect"
"N00345","this is

having ^M
problem"

I need this file like :
"id","notes"
"N001","this is~~test.~~~~Again test~~~~"
"N002","this is perfect"
"N00345","this is~~~~having ~~problem"

So that the whole cell value can be read as a single field value.
I need to add one more case in this requirement where data within a cell contains " (double quotes). Here in this case we can identify ending " when it is followed by comma. Here are updated case data :
"id","notes"
"N001","this is^M
test. "Again test."

Again test

"
"N002","this is perfect"
"N00345","this is

having ^M
problem as it contains "
test"

We can keep " or remove it. The expected output is :
"id","notes"
"N001","this is~~test. "Again test."~~~~Again test~~~~"
"N002","this is perfect"
"N00345","this is ~~~~having ~~problem as it contains "~~test"

A: Try using sed
sed -i -e 's/^M//g' -e '/"$/!{:a N; s/\n/~~/; /"$/b; ba}' file

Note : To enter ^M, type Ctrl+V followed by Ctrl+M
File content after running command
"id","notes"
"N001","this is~~test.~~~~Again test~~~~"
"N002","this is perfect"
"N00345","this is~~~~having ~~problem"

Or using dos2unix followed by sed
dos2unix file
sed -i '/"$/!{:a N; s/\n/~~/; /"$/b; ba}' file

Short Description
Idea here is to remove newline character in each line not ending with "
sed -i '              # -i specifies in-place relace i.e. modifies file itself
  /"$/!{              # if a line doesn't contain end pattern, " at the end of a line, then do following
    :a                # label 'a' for branching/looping
      N;              # append the next line of input into the pattern space
      s/\n/~~/;       # replace newline character '\n' with '~~' i.e. suppress new lines
      /"$/b;          # if a line contains end pattern then branch out i.e. break the loop
      ba              # branch to label 'a' i.e. this will create loop around label 'a'
  }
' file                # input file name

Refer to man sed for further details

EDIT

Sometimes data in the cell itself contains " within it.

Using sed
sed -i ':a N; s/\n/~~/; $s/"~~"/"\n"/g; ba' file

File content after running command for updated  case data
"id","notes"
"N001","this is~~test. "Again test."~~~~Again test~~~~"
"N002","this is perfect"
"N00345","this is~~~~having ~~problem as it contains "~~test"

Using perl one-liner
perl -0777 -i -pe 's/\n/~~/g; s/"~~("|$)/"\n$1/g;' file

A: You can do this using sed command
To replace '^M' alone
sed -i 's|^M|~~|g' file_name

Edit:
Thanks for giving comment.
Adding a statement to replace '^M and new line'
To replace '^M and new line'**
sed -i ':a;N;$!ba;s|^M\n|~~|g' file_name

To get '^M' in console you should press Cntrl+v+m together

A: Use tr.
$ tr '<Ctrl>+m' '~'

A: sed 's/\^M/~~/;t nextline
b
: nextline
N
s/\n/~~/
s/^[^"]*\("[^"]*"\}\{1,\}[^"]*$
t
b nextline
"

not just change the ^M but also the new line between quote.
^M is obtain in unix session with a CTRL+V followed by a CTRL+M on keyboard


text:
Q: How do I "make install" via xcode? I have an xcode project that builds a library from C/C++ sources for OSX.  Is there a way to get xcode to install the library and its header files into /usr/local/lib?
I have the following settings under Target > Build Settings:

*

*Deployment

*

*Deployment Location = Yes

*Deployment Postprocessing = Yes

*Installation Build Products Location = /tmp/projname.dst

*Installation Directory = /usr/local/lib

*Skip Install = No

When I do Product > Build, it puts the resulting .a and adds the public headers into an include/ subfolder in the /tmp/projname.dst/ folder.  But I come from the land of Makefiles and I'd like to have the equivalent of "make install" here (I expect it to ask me for permissions when it tries to put things into /usr/local/include/ and /usr/local/lib/)

A: It looks like "xcodebuild install" is how you do this.


text: Q: Affine transformation from a parallelogram to a square I need to transform an area of an image so that a parallelogram defined as $((x0,y0), (x1,y1), (x2,y2), (x0+x2-x1, y0+y2-y1))$ is mapped on a square $((0,0),(0,128),(128,128),(128,0))$. Apparently, Python OpenCV can read and save images as well as perform affine transformations. What would be the algorithm for such transform?


text:
Q: Problem with ViewVector I am trying to have a satellite (camera) move around the earth (unit sphere) and take picture of the earth. The satellite keeps constant distance from the earth, and always looks toward earth center.
Manipulate[
   Graphics3D[Sphere[{0, 0, 0}, 1], ViewVector -> {2*{Cos[t], 0, Sin[t]}, {0, 0, 0}}],
   {t, 0, 2*Pi}]

This should produce the same size of circle no matter what angle t is being used, but the above code scales the images. I think I am not using ViewVector correctly here. Any clarification would be greatly appreciated.

A: I don't think kuba answer, although correct, really addresses the texture issue. ViewVertical is essential, but ViewAngle is not needed. Also, SphericalRegion helps.
Manipulate[
  SphericalPlot3D[1 , {u, 0, 180 °}, {v, 0, 360 °},
    Mesh -> None,
    TextureCoordinateFunction -> ({#5 - 1/2, 1 - #4} &),
    PlotStyle -> Texture[satelliteImage],
    Lighting -> "Neutral",
    Axes -> False,
    PerformanceGoal -> "Quality",
    ViewVector -> {5*{Cos[t], 0, Sin[t]}, {0, 0, 0}},
    SphericalRegion -> True,
    ViewVertical -> {-Sin[t], 0, Cos[t]}],
  {t, 0., 2.*Pi, Pi/18.}]

The Manipulate rotated a world globe about the y-axis like so

where satelliteImage is this image

A: As suggested by Szabolcs ViewAngle and ViewVertical is the answer. SphericalRegion is, in fact, redundant so I don't have to explain it (I can't ;P).
Manipulate[Graphics3D[Cone[{{0, 0, -1}, {0, 0, 1}}, 1],
                      ViewVector -> {2*{Cos[t], 0, Sin[t]}, {0, 0, 0}},
                      ViewAngle -> Pi/2,
                      ViewVertical -> {-Sin[t], 0, Cos[t]}]
          , {t, 0, 2*Pi, .3}]

ViewVertical is related with ViewVector by:
RotationTransform[-Pi/2, {0, 1, 0}][{Cos[t], 0, Sin[t]}]

{-Sin[t], 0, Cos[t]}

This fixes the problem of reorientation over the pole ;)

Is this what you are after?


text:
Q: String literals, interning and reflection I'm trying to find a third solution to this question.
I can't understand why this doesn't print false.
public class MyClass {

    public MyClass() {
        try {
            Field f = String.class.getDeclaredField("value");
            f.setAccessible(true);
            f.set("true", f.get("false"));
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        MyClass m = new MyClass();
        System.out.println(m.equals(m));
    }
}

Surely, because of string interning, the "true" instance being modified is exactly the same one used in the print method of PrintStream?
public void print(boolean b) {
    write(b ? "true" : "false");
}

What am I missing?
Edit
An interesting point by @yshavit is that if you add the line
System.out.println(true);

before the try, the output is
true
false

A: This is arguably a HotSpot JVM bug.
The problem is in the string literal interning mechanism.

*

*java.lang.String instances for the string literals are created lazily during constant pool resolution.

*Initially a string literal is represented in the constant pool by CONSTANT_String_info structure that points to CONSTANT_Utf8_info.

*Each class has its own constant pool. That is, MyClass and PrintStream have their own pair of CONSTANT_String_info / CONSTANT_Utf8_info cpool entries for the literal 'true'.

*When CONSTANT_String_info is accessed for the first time, JVM initiates the process of resolution. String interning is the part of this process.

*To find a match for a literal being interned, JVM compares the contents of CONSTANT_Utf8_info with the contents of string instances in the StringTable.

*^^^ And here is the problem. Raw UTF data from cpool is compared to Java char[] array contents that can be spoofed by a user via Reflection.

So, what's happening in your test?

*

*f.set("true", f.get("false")) initiates the resolution of the literal 'true' in MyClass.

*JVM discovers no instances in StringTable matching the sequence 'true', and creates a new java.lang.String, which is stored in StringTable.

*value of that String from StringTable is replaced via Reflection.

*System.out.println(true) initiates the resolution of the literal 'true' in PrintStream class.

*JVM compares UTF sequence 'true' with Strings from StringTable, but finds no match, since that String already has 'false' value. Another String for 'true' is created and placed in StringTable.

Why do I think this is a bug?
JLS §3.10.5 and JVMS §5.1 require that string literals containing the same sequence of characters must point to the same instance of java.lang.String.
However, in the following code the resolution of two string literals with the same sequence of characters result in different instances.
public class Test {

    static class Inner {
        static String trueLiteral = "true";
    }

    public static void main(String[] args) throws Exception {
        Field f = String.class.getDeclaredField("value");
        f.setAccessible(true);
        f.set("true", f.get("false"));

        if ("true" == Inner.trueLiteral) {
            System.out.println("OK");
        } else {
            System.out.println("BUG!");
        }
    }
}

A possible fix for JVM is to store a pointer to original UTF sequence in StringTable along with java.lang.String object, so that interning process will not compare cpool data (inaccessible by user) with value arrays (accessible via Reflection).

A: I've written this as a community wiki as I don't know if it's right and don't understand the details anyway.
What appears to happen is that when a string literal is encountered at runtime, the JVM checks the string pool (using equals) to see if the string is already there. If it isn't there, a new instance is used. This object (either the new one or the one that was already in the string pool) is the one that will be used from now on for all string literals in that class that are the same.
Consider this example:
public class MyClass {

    public MyClass() {
        try {
            Field f = String.class.getDeclaredField("value");
            f.setAccessible(true);
            f.set("true", f.get("false"));
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        System.out.println(true);       // 1
        new MyClass();
        System.out.println(true);       // 2
        System.out.println("true");     // 3
        printTrue();
        OtherClass.printTrue();
    }

    public static void printTrue() {
        System.out.println("true");     // 4
    }
}

public class OtherClass {

    static void printTrue() {
        System.out.println("true");     // 5
    }
}

This prints:

true
  false
  false
  false
  true

My explanation:
In line 1, the JVM encounters the literal "true" in the PrintStream class. A new string is added to the pool. Then new MyClass() is invoked. Inside this constructor, the JVM encounters the string literal "true" in the MyClass class. This string is already in the pool, so the instance in the pool is the one that will be used, but crucially it is also the one that will later be used in lines 3 and 4. Then the array backing this string is modified. Lines 2, 3 and 4 therefore all print false. Next, OtherClass.printTrue() is invoked and the JVM encounters the string literal "true" for the first time in OtherClass. This string is not equal to the one in the pool  because the one in the pool now has backing array [f, a, l, s, e]. Therefore a new string instance is used and true is printed at line 5.
Now suppose we comment out line 1:
//        System.out.println(true);       // 1

This time the output is:

true
  false
  false
  true

Why does line 2 produce a different result? The difference here is the literal "true" is not encountered in the PrintStream class until after the backing array has been modified. So the "wrong" string is not the one used in the PrintStream class. However, lines 3 and 4 continue to print "false" for the same reason as above.


text:
Q: Touch ID Crash issue Actually I am facing issue in the TouchID implementation. I want to implement a passcode functionality like Apple. My is problem is that I don't want to show any alert to the user like Apple.
NSString *myLocalizedReasonString = <#String explaining why app needs authentication#>;
if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
[myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:myLocalizedReasonString
reply:^(BOOL success, NSError *error) {

Here if I don't send myLocalizedReasonString the app will crash.

A: You have to show an alert and provide a reason string. It is part of Apple's privacy and security requirements for iOS. You need to inform the user why you are requesting a Touch ID authentication


text:
Q: Running Totals in a Persisted Computed Column I have a table in SQL Server 2012 like this:
CREATE TABLE [dbo].[CustomerLedgerEntries]
(
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [CustReference] [bigint] NOT NULL,
    [DebitAmount] [decimal](18, 2) NOT NULL,
    [CreationTime] [datetime] NOT NULL,
    [Description] [nvarchar](512) NULL,
    [ProductId] [nvarchar](32) NULL,

    CONSTRAINT [PK_dbo.CustomerLedgerEntries]
        PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

I want to add a calculated, persisted column that will give me the running balance of each customer. Presently I use this query to obtain the running balance of each customer:
SELECT
    Id, CustReference, CreationTime, DebitAmount, CreditAmount,
    SUM(DebitAmount - CreditAmount) OVER (PARTITION BY CustReference ORDER BY Id
                                          ROWS UNBOUNDED PRECEDING) AS Balance
FROM
    CustomerLedgerEntries

I tried to add the computed column using this query:
ALTER TABLE dbo.CustomerLedgerEntries
    ADD Balance AS (SUM(DebitAmount - CreditAmount) OVER (PARTITION BY CustReference
                                                          ORDER BY Id
                                                          ROWS UNBOUNDED PRECEDING));

But it throws an error:

Msg 4108, Level 15, State 1, Line 8
  Windowed functions can only appear in the SELECT or ORDER BY clauses.

How can I achieve this please?
Edit 1:
After following @JM_ suggestion below and creating a UDF, in the table the balance shows as below:
Id CusReference CreationTime DebitAmount CreditAmount Balance
30  3      2017-07-12 15:26:36.753  15000.00    0.00    14000.00
31  3      2017-07-12 15:26:36.753  0.00    1000.00     14000.00
Whereas when I run the query Select    Id, CustReference, CreationTime, DebitAmount, CreditAmount
        , Sum(DebitAmount - CreditAmount) Over( Partition By CustReference Order by Id
                                    rows Unbounded Preceding) As Balance
 From   CustomerLedgerEntries the result shows correctly:
30 3   2017-07-12 15:26:36.753   15000.00  0.00      15000.00
31  3   2017-07-12 15:26:36.753   0.00      1000.00   14000.00
So almost there... but not quite there. Please is there any help?

A: I assume your table has a Credit Column, but the script above did not include it.  You can do it by using a UDF:
--EDIT:
CREATE FUNCTION [dbo].[UDF_GetBalance] (@CustRef bigint, @ID bigint)
RETURNS decimal(18,2)
AS
BEGIN
  DECLARE @Balance decimal(18,2)
  SELECT @Balance = SUM(DebitAmount - CreditAmount) OVER (PARTITION BY CustReference ORDER BY Id
                                      ROWS UNBOUNDED PRECEDING)
FROM
CustomerLedgerEntries WHERE CustReference =@CustRef and ID <= @id

RETURN @Balance
END

ALTER TABLE CustomerLedgerEntries ADD Balance as (dbo.UDF_GetBalance(CustReference, ID))

A: Using a scalar udf in a computed column for this is an awful Idea for a numbers of reasons. One huge problem is that queries against that table, even when the computed column is not referenced, will run serially. Here's a great article that explains why you don't want to do this:Another reason why scalar functions in computed columns is a bad idea
SQL Server 2012 offers the ability to do index builds/rebuilds in parallel but you lose that functionality when you use a scalar udf in this way. You can test this for yourself by using the traceflag referenced in this article.
Scalar functions are bad for many other reasons too. For optimal performance that does restrict serial execution on your CustomerLedgerEntries table I would use an iTVF (note that I can't test this). An iTVF will allow you use all your CPUs.
CREATE FUNCTION dbo.UDF_GetBalance (@CustRef bigint)
RETURNS TABLE AS RETURN
  SELECT balance = SUM(DebitAmount - CreditAmount)
    OVER (PARTITION BY CustReference ORDER BY Id ROWS UNBOUNDED PRECEDING)
FROM CustomerLedgerEntries
WHERE CustReference =@CustRef;
GO


text:
Q: If user inputs directory that has subdirectories search all subdirectories in root This is a follow up to a question that has already been answered.
If a user inputs "c:\folder" and there happens to be several folders in that directory how do I make it search all subdirectories in the requested root directory.
Sample Code below currently searches one folder and displays results even if there are multiple folders.
@echo off
set total=0
set /p direct=What directory do you want to count?
for %%a in (%direct%\*.pdf) do (
   title %%a
   for /f "tokens=2 delims=: " %%b in ('pdftk "%%a" dump_data ^| find "NumberOfPages"') do (
      set /a total+=%%b
   )
)
echo TOTAL PAGE COUNT IS %total%
pause

A: Try replace
for %%a in (%direct%\*.pdf) do (
    title %%a
    for /f "tokens=2 delims=: " %%b in ('pdftk "%%a" dump_data ^| find "NumberOfPages"') do (
         set /a total+=%%b
    )
)

With
forfiles /p %direct% /c "cmd /c if @isdir == FALSE (for %%a in (@path\*.pdf) do (for /f "tokens=2 delims=: " %%b in ('pdftk "%%a" dump_data ^| find "NumberOfPages"') do (set /a total+=%%b)))"

title %%a isn't important because it only shows the last one.

A: So I solved this on my own (sort of), See my code below. Copying the files to a temporary directory and then counting them from there. This was a much easier solution for me.
set total=0
set /p direct=What directory do you want to count?

del "C:\Program Files\PDF COUNTER\TEMP\*.pdf"

pushd %direct%
   for /r %%a in (*.pdf) do (
       copy "%%a" "C:\Program Files\PDF COUNTER\TEMP\%%~nxa"
   )
popd

for %%a in ("C:\Program Files\PDF COUNTER\TEMP\*.pdf") do (
   title %%a
   for /f "tokens=2 delims=: " %%b in ('pdftk "%%a" dump_data ^| find "NumberOfPages"') do (
      set /a total+=%%b
   )
)
echo TOTAL PAGE COUNT IS %total%
pause


text:
Q: Extending Classes with Index signature I am trying to make an abstract class but things aren't working as i would like them to and i fear my knowledge of typescript is what is limiting as i think this is a fairly generic use case.
I have an abstract class Program.
This abstract class has a bunch of functions and attributes.
abstract class Program {
  someString: string = "bob";
  someFunc(): void {
    return;
  }
  someOtherfunc: void {
    this.childFunc();
    return;
  }
}

I also have interface 'IProgram' that looks like this
interface IProgram {
  childFunc: () => void;
}

class Child extends class Program like so and also implements 'IProgram' interface
class Child extends Program implements IProgram {
  childFunc(): void {
    console.log("Hello World")
  }
}

So I cant get this to work while not getting some sort of breaking (IMHO) behavior.
I've tried to add an index signature to 'Program'
That works i get no TS errors, but then anything works in child program. I dont care losing validations in IProgram as this isn't something that will be changed, but I don't want children program being able to go:
this.bob = 'potato'; //TS wont give an error because of index signature in parent

I've also tried declaring 'childFunc' as type any in the Abstract class but then it complains that it's supposed to be a function and not a member. My other issue with declaring it is that my child class implementing 'IProgram' will no longer be forced to implement 'childFunc' as TS finds it in the header.
I've also made a minimal stackBlitz reproducing this issue
https://stackblitz.com/edit/typescript-po7hbo
I basically just want the abstract class to accept that all its children will have those funcs/properties declared.

A: It looks like you really expect all concrete subclasses of Program to implement IProgram, because you are referring to this.childFunc() inside the definition of Program.  If so, you should declare that Program implements IProgram, declare the childFunc method inside Program, and mark it as abstract:
abstract class Program implements IProgram {

  abstract childFunc(): void; // marked as abstract

  someString: string = "bob";
  someFunc(): void {
    return;
  };
  someOtherfunc(): void {
    this.childFunc(); // okay now
    return;
  };
}

// you can remove the "implements IProgram" from Child since the parent has it
class Child extends Program {
  childFunc(): void {
    console.log("Hello World")
  }
}

Abstract methods are declared but not implemented in their abstract class, and all concrete subclasses will have to implement them or get an error:
class Oops extends Program { // error!
//    ~~~~
// Non-abstract class 'Oops' does not implement inherited
// abstract member 'childFunc' from class 'Program'.
}

Hope that helps.  Good luck!


text:
Q: How to change the color of overscroll edge and overscroll glow How to Change color of over-scroll edge and over-scroll glow or how to change the white color (default color) of android release 5.0 lollipop?

A: The overscroll glow color inherits the primary color value set by android:colorPrimary in your entire app. But If you need to specify different value simply use android:colorEdgeEffect (only available for API 21 and above).
<style name="MyAppTheme" parent="...">
   <item name="android:colorEdgeEffect">@color/my_color</item>
</style>

A: On LOLLIPOP the edge glow inherits from colorPrimary. After the view is created the edge glow color can only be changed through reflection. This can be useful when you load colors dynamically using Palette.
EDIT: TL;DR: Download the whole class from here:
https://github.com/consp1racy/android-commons/blob/71b5c65689786b1d52d701d81d8c7445495807c3/commons/src/main/java/net/xpece/android/widget/XpEdgeEffect.java
PROGUARD SETUP: If you're going to use this on widgets from support library you need to keep the field names. Quickest way to do it is the following (although still wasteful):
-keepclassmembers class android.support.v4.widget.EdgeEffectCompat {
    <fields>;
}

Create a utility class with the following code:
private static final Class<?> CLASS_SCROLL_VIEW = ScrollView.class;
private static final Field SCROLL_VIEW_FIELD_EDGE_GLOW_TOP;
private static final Field SCROLL_VIEW_FIELD_EDGE_GLOW_BOTTOM;

private static final Class<?> CLASS_LIST_VIEW = AbsListView.class;
private static final Field LIST_VIEW_FIELD_EDGE_GLOW_TOP;
private static final Field LIST_VIEW_FIELD_EDGE_GLOW_BOTTOM;

static {
  Field edgeGlowTop = null, edgeGlowBottom = null;

  for (Field f : CLASS_SCROLL_VIEW.getDeclaredFields()) {
    switch (f.getName()) {
      case "mEdgeGlowTop":
        f.setAccessible(true);
        edgeGlowTop = f;
        break;
      case "mEdgeGlowBottom":
        f.setAccessible(true);
        edgeGlowBottom = f;
        break;
    }
  }

  SCROLL_VIEW_FIELD_EDGE_GLOW_TOP = edgeGlowTop;
  SCROLL_VIEW_FIELD_EDGE_GLOW_BOTTOM = edgeGlowBottom;

  for (Field f : CLASS_LIST_VIEW.getDeclaredFields()) {
    switch (f.getName()) {
      case "mEdgeGlowTop":
        f.setAccessible(true);
        edgeGlowTop = f;
        break;
      case "mEdgeGlowBottom":
        f.setAccessible(true);
        edgeGlowBottom = f;
        break;
    }
  }

  LIST_VIEW_FIELD_EDGE_GLOW_TOP = edgeGlowTop;
  LIST_VIEW_FIELD_EDGE_GLOW_BOTTOM = edgeGlowBottom;
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void setEdgeGlowColor(AbsListView listView, int color) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    try {
      EdgeEffect ee;
      ee = (EdgeEffect) LIST_VIEW_FIELD_EDGE_GLOW_TOP.get(listView);
      ee.setColor(color);
      ee = (EdgeEffect) LIST_VIEW_FIELD_EDGE_GLOW_BOTTOM.get(listView);
      ee.setColor(color);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void setEdgeGlowColor(ScrollView scrollView, int color) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    try {
      EdgeEffect ee;
      ee = (EdgeEffect) SCROLL_VIEW_FIELD_EDGE_GLOW_TOP.get(scrollView);
      ee.setColor(color);
      ee = (EdgeEffect) SCROLL_VIEW_FIELD_EDGE_GLOW_BOTTOM.get(scrollView);
      ee.setColor(color);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

A: If you're using the latest RecyclerView implementation it is pretty straightforward to change the overflow colour programmatically. Use the following code (Kotlin implementation):
recyclerView.edgeEffectFactory = object : RecyclerView.EdgeEffectFactory() {
    override fun createEdgeEffect(view: RecyclerView, direction: Int): EdgeEffect {
        return EdgeEffect(view.context).apply { setColor(color) }
    }
}

Note that this works only for API level 21 (Lollipop) and above. If you know the value at compile time, use the colorEdgeEffect as pointed out by Ahmed.

A: In pre-lollipop the glow effect is actually a Drawable embedded in the OS's resources, you can apply a ColorFilter on that:
public static void changeOverScrollGlowColor(Resources res, int colorID ) {
    try {
        final int glowDrawableId = res.getIdentifier("overscroll_glow", "drawable", "android");
        final Drawable overscrollGlow = res.getDrawable(glowDrawableId);
        overscrollGlow.setColorFilter(res.getColor(colorID), android.graphics.PorterDuff.Mode.SRC_ATOP);

        final int edgeDrawableId = res.getIdentifier("overscroll_edge", "drawable", "android");
        final Drawable overscrollEdge = res.getDrawable(edgeDrawableId);
        overscrollEdge.setColorFilter(res.getColor(colorID), android.graphics.PorterDuff.Mode.SRC_ATOP);
    } catch (Exception ignored) {
    }
}

Calling it once in onCreate is enough.
changeOverScrollGlowColor(getResources(), R.color.colorPrimary);


text:
Q: How to get access to user information by if statement? I am trying to give access to a user for his information by asking him his name and then showing him the details. So how could I do that? Whenever I name, it gives me no access, means I am not allowed to get access. I tried and search a lot but didn't find the right answer.
int list_view(char *name, size_t namesize){
    printf("For person details, please enter the person name and id card number: \n");
    printf("Enter your Name: ");
    if(!fgets(name, namesize, stdin)){
      printf("No access");
      return 0;
     }
    FILE * fr;
    int one_by_one;
    fr = fopen("/home/bilal/Documents/file.txt", "r");
    for (int i=0; i<8; i++){
        printf("\nHere is your ");
        while((one_by_one = fgetc(fr)) != EOF && one_by_one != '\n'){
          printf("%c",one_by_one); /*  display on screen*/
        }
    }
    fclose(fr);
  return 0;
}

A: Assuming that your file has the names and the details of those names in the same line, creating a simple search by name in the file and comparing it to the inputed name. Assuming a line size no larger than 199 characters excluding the name which would be no larger than 99 characters and a single word, here's a sample of a possible implementation:
Live demo
int list_view(char *name, size_t namesize)
{
    char line[200];
    char name2[100];

    printf("For person details, please enter the person name and id card number: \n");
    printf("Enter your Name: ");

    if (!fgets(name, namesize, stdin)){//read name from stdin
        perror("Error while reading!");
        return 0;
    }
    name[strcspn(name, "\n")] = '\0'; //remove \n

    FILE *fr;

    if(!(fr = fopen("/home/bilal/Documents/file.txt", "r"))){ //always check fopen for errors
      perror("Unable to open file");
      return 0;
    }

    while(fscanf(fr, "%99s", name2) == 1) //search name in the file
    {
        if(!strcmp(name2, name)){ //the name is found print the rest of the line
            if(fscanf(fr, "%199[^\n]", line) == 1){
                printf("%s", line);
                fclose(fr);
                return 1;
            }
        }
    }
    fclose(fr);
    return 0;
}

A: if you look at my previous answer to the same question I said you must write
if(!fgets(dob, dobsize, stdin))

see the '!' character in the if


text:
Q: I can't log onto servers I can't get into ANY servers in MCPE. I've tried loads of servers, but I still can't get in! It just says "locating server".

A: Check that your screen name doesn't use any strange characters.
My sons both have a Galaxy tab. While one of them could connect to the Lifeboat Server instantly, the other could not. It was rather frustrating, and an answer was nowhere to be found, an answer that solved the problem that is. So we installed MCPE on my Galaxy tab as well, and tried to connect to the server. It worked in an instant.
So why would two tabs work just fine, while the third one wouldn't? In our case it was my son's screen name that would not allow him to connect to the world. To make sure we were on the right track we changed the screen names on all three tabs, and BINGO, it was the screen name indeed. My son now has a new name, and with that he can connect.

A: From what i've read this is actually because A LOT of servers are purely fake, taken down, full or under construction,
It seems that there is a real issue of servers just being down completely,
I dont think this is a technical issue on your end, it is just significantly harder to find a server that is actually on, Try joining a server that maybe your friends are in and is not full,
If you are on android you can also try clearing the data of the minecraft app which results in the app reverting to a "Fresh" version,

A:
This question is from 2014, but I will answer from my experience in mid-2020.

There are 2 reasons why this could be possible:

*

*The server might have certain bugs and issues still not fixed or mismanaged leading to a bad experience logging in to a server. This happened to me in Lifeboat.

*You have a high ping. In my sorts, playing a game with 300+ ping could be a buggy experience especially logging in to servers. Using ping less than 150 is suitable.


text:
Q: Bootstrap 4 Responsive Card Height for Fixed Aspect Ratio Image

$("#player1Choice").append("");
$("#player2Choice").append("");
#player1Card, #player2Card, #resultsCard {
    max-width: 250px;
    max-height: 250px;
    width: 58%;
    background-color: #140B7B;
    color: #FFFFFF;
}

.userName {
    font-weight: bold;
    height: 45px;
}

#p1Display, #p2Display {
    height: 170px;
}

#p1WL, #p2WL {
    background-color: #140B7B;
    color: #FFFFFF;
    height: 30px;
    margin-bottom: 0;
}

.rpsImage {
    width: 100%;
    height: auto;
}

@media screen and (min-width: 576px) and (max-width: 767px) {

    #player, #status {
        height: 80px;
    }

    #player1Card, #player2Card, #resultsCard {
        max-height: 166px;
    }

    #p1WL, #p2WL {
        font-size: 0.5rem;
        height: 20px;
    }

    .userName {
        font-size: 0.85rem;
        height: 36px;
    }

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Player 1

Player 2

How can I make a card body to have a fixed height without content but be responsive to a fixed aspect ratio image that I add with jQuery at a specific point in my program.  My card is 250px by 250px for a screen that is 992px and larger.  The image size is 243px x 166px and I have used the following CSS to scale it:
.myImage {
    width: 100%;
    height: auto;
}

However, when I change the viewport size for a tablet the height stays at 250px instead of shrinking to the size of the content because I used "max-height: 250px;" to keep the body from collapsing when empty.
Is there any other way to keep the card height at 250px when card body has no content but have it be responsive to the height of the fixed aspect ratio image other than using @media queries for specific breakpoints?
Here is the jsFiddle


text:
Q: Trying to hide burger menu and have text links instead on large screen I'm trying to make this menu collapse at a break-point or media query. The menu currently just has the option of a collapsed menu. I'm trying to add a non collapsed option so the user can actually see the names of the links at full screen. The menu should only collapse on smaller devices. I tried implementing this functionality using bootstrap but with no luck. Bascically I am trying to simply have text links and then when the size of the screen reduces the navbar collapses and the 'burger menu' appears.
CodePen without broken bootstrap implementation.
http://codepen.io/anon/pen/dPaVdO
HTML

      pic

           Hello

               About

               Bye

CSS
body {
  font-family: "Helvetica Neue", Helvetica,arial, sans-serif;
  font-size: 100%;
  margin: 0;
  padding: 0;
}
@media (min-width: 45em) {
  body {
    font-size: 120%;
  }
}
@media (min-width: 65em) {
  body {
    font-size: 130%;
  }
}
@media (min-width: 85em) {
  body {
    font-size: 150%;
  }
}

a {
  text-decoration: none;
}

header {
  position: fixed;
  width: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: block;
  top: 0;
  padding: 0;
  z-index: 8;
  height: 3.5em;
}
header h1#logo {
  color: #fff;
  font-size: 1em;
  margin: 0 !important;
  padding: .4em 1em 0;
  position: absolute;
  display: inline-block;
  vertical-align: middle;
  float: left;
  padding: 1em 0.5em 0;
  top: 0;
}
header nav p {
  font-size: 80%;
  color: #12384E;
  margin: 0 0 -1em;
  padding: 0;
  font-weight: 400;
}
header nav ul {
  margin: 0;
  padding: 0;
  line-height: inherit;
  font-size: inherit;
  visibility: hidden;
  top: -5%;
  width: 100%;
  padding: 0;
  opacity: 0;
  display: table-cell;
  vertical-align: middle;
  -webkit-transform: perspective(600px) rotateX(10deg);
  transform: perspective(600px) rotateX(10deg);
  -webkit-transition: all 0.5s cubic-bezier(0.7, 0, 0.36, 0.63);
  -moz-transition: all 0.5s cubic-bezier(0.7, 0, 0.36, 0.63);
  -o-transition: all 0.5s cubic-bezier(0.7, 0, 0.36, 0.63);
  transition: all 0.5s cubic-bezier(0.7, 0, 0.36, 0.63);
}
header nav ul li {
  list-style: none;
  text-align: center;
}
header nav ul li a {
  display: block;
  color: #fff;
  padding: .5em 0;
  width: 100%;
  display: block;
  font-size: 200%;
  font-weight: 600;
}
header nav ul li a:hover {
  background: rgba(255, 255, 255, 0.8);
}
header nav ul li a:focus {
  outline: 0;
}
header nav ul li a:hover, header nav ul li a:active {
  color: #0e1718 !important;
}
header .nav-background {
  z-index: 99;
  position: fixed;
  top: 0;
  width: 100%;
  height: 100%;
  background: none;
  display: table;
  -webkit-transition: background-color 0.6s cubic-bezier(0.7, 0.01, 0.3, 1);
  -moz-transition: background-color 0.6s cubic-bezier(0.7, 0.01, 0.3, 1);
  -o-transition: background-color 0.6s cubic-bezier(0.7, 0.01, 0.3, 1);
  transition: background-color 0.6s cubic-bezier(0.7, 0.01, 0.3, 1);
}
header #toggle {
  height: 3em;
  z-index: 999;
  padding: 1.5em 1em 0;
  cursor: pointer;
  position: fixed;
  top: 0;
  right: .5em;
  -webkit-transition: padding-top 0.6s cubic-bezier(0.1, 0.01, 0.3, 1);
  transition: padding-top 0.6s cubic-bezier(0.1, 0.01, 0.3, 1);
}
header #toggle:hover {
  transition: top, 0.5s, ease-in-out;
}
header #toggle:hover .menubars:before {
  top: -9px;
}
header #toggle:hover .menubars:after {
  top: 9px;
}

.menubars {
  width: 24px;
  height: 4px;
  margin: 10px 0;
  background: #fff;
  position: relative;
  z-index: 999 !important;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}
.menubars:before {
  top: -8px;
}
.menubars:after {
  top: 8px;
}
.menubars:after, .menubars:before {
  content: '';
  display: block;
  width: 24px;
  height: 4px;
  background: #EC008C;
  position: absolute;
  z-index: -1;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.menubars {
  width: 24px;
  height: 4px;
  margin: .2em 0;
  background: #FFF;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}
.menubars:before {
  top: -8px;
}
.menubars:after {
  top: 8px;
}
.menubars:after, .menubars:before {
  content: '';
  display: block;
  width: 24px;
  height: 4px;
  background: #FFF;
  position: absolute;
  z-index: -1;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.js-open {
  height: 100%;
}
.js-open header {
  margin-top: 0px;
  background: none;
}
.js-open .menubars {
  background: none !important;
}
.js-open .menubars:after {
  top: 0 !important;
  background: #fff !important;
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  transform: rotate(45deg);
}
.js-open .menubars:before {
  top: 0 !important;
  background: #fff !important;
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
.js-open .nav-background {
  background: rgba(27, 128, 167, 0.9) !important;
}
.js-open ul {
  top: 0;
  visibility: visible;
  opacity: 1;
  margin-top: 0;
  -webkit-transform: perspective(600px) rotateX(0deg);
  -moz-transform: perspective(600px) rotateX(0deg);
  -ms-transform: perspective(600px) rotateX(0deg);
  -o-transform: perspective(600px) rotateX(0deg);
  transform: perspective(600px) rotateX(0deg);
}

JS (JQuery)
$("a#toggle").on('click', function(e) {
$('body').toggleClass('js-open');
$('nav').toggleClass('js-open');
    e.preventDefault();
});

$(".nav-background").on('click', function() {
  $('body, nav').removeClass('js-open');
});

A: You'll need to change the display styles/opacity on your desired breakpoint. For example:
@media all and (min-height: 1000px) {
  header nav ul {
    visibility: visible;
    opacity: 1;
  }
  .menubars {
    display: none;
  }
}

Updated pen: http://codepen.io/anon/pen/yyZPGV


text:
Q: Overriding Dart methods with Generics arguments I have this case where I am extending from a super class with methods being typed using Generics as the following:
Models
abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}

Controllers
abstract class A {
   T getDoc<T extends SuperClass>(T doc);
}

class B extends A {
   T getDoc<T extends SubClass>(T doc) {     //<================ Error
       //....
    }
}

Basically class B will only deal with a SubClass model and any class that extends it. Extending SuperClass is not enough. It's a way to enforce the type usage. I could add a helper function that will check the type for each method within class B (doc is SubClass) but seems like a lot repetition.
But the above architecture fails when overriding the method getDoc in class B saying that it isn't a valid override although SubClass is a SuperClass. How can I achieve something like this? Or is there a better way of doing it? Appreciate any pointers :)

A: I have finally a found a way :)
So I wanted the class B's methods to accept exclusively types that extend SubClass, but class A method's signature expects parameters extending class SuperClass.
To go about this I did the following:
Models
abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}

Controllers
abstract class A<K extends SuperClass> {
   T getDoc<T extends K>(T doc);
}

class B extends A<SubClass> {
   T getDoc<T extends SubClass>(T doc) {
          //.......
    }
}

A: can you use covariant modifier.
In your example:
abstract class A {
   T getDoc<T extends SuperClass>(covariant T doc);
}

Check: https://github.com/dart-lang/sdk/blob/master/docs/language/informal/covariant-overrides.md

A: You can not narrow the generic type argument. Class B guaranties (by extending class A), that it will/can handle all type arguments (and sub types!), that class A can handle. Consider the following situation:
class OtherSubClass extends SuperClass {
  //....
}

void main() {
  var b = B();
  b.getDoc(OtherSubClass());
}

What would you expect to happen? Class B is not able to handle objects of type OtherSubClass, so it breaks the contract with class A.


text:
Q: codeigniter href with php variable doesn't work i am trying to change the login button on my page to a logout button when someone is logged in.
$logged_in = $this->session->userdata('logged_in');
if ($logged_in) {

    $data['Lbutton'] = '

    <button class="login3"><?php echo anchor("pages/logout", "Logout"); ?></button>

';
} else {
    $data['Lbutton'] = '

    <button class="login3"><a href= <?php echo base_url()?>index.php/login>login    </button>

';
}

and this is my view:
<?php echo $Lbutton ?>

A: This is Answer:
if ($logged_in)
{
    $data['Lbutton'] = '

    <button class="login3">'.anchor("pages/logout", "Logout").'</button>

';
}
else
{
    $data['Lbutton'] = '

    <button class="login3">login    </button>

';
}


text:
Q: Access from container to host I have a elasticsearch service in my host.
I can run in my console:
$ curl http://127.0.0.1:9200
{
  "name" : "node00",
  "cluster_name" : "cluster00",
  "cluster_uuid" : "Zk4RzStrTLeSD2TQXReRlA",
  "version" : {
    "number" : "5.0.0",
    "build_hash" : "253032b",
    "build_date" : "2016-10-26T04:37:51.531Z",
    "build_snapshot" : false,
    "lucene_version" : "6.2.0"
  },
  "tagline" : "You Know, for Search"
}

I got my ip address for the docker comunication:
$ sudo ifconfig
docker0   Link encap:Ethernet  HWaddr 02:42:6b:fc:f8:82
          inet addr:172.17.0.1  Bcast:0.0.0.0  Mask:255.255.0.0

Inside container:
root@1e473bd5ca92:~# curl http://172.17.0.1:9200
curl: (7) Failed to connect to 172.17.0.1 port 9200: Connection refused

But if I run this query to internet, I got a valid response:
root@1e473bd5ca92:~# curl 'https://api.ipify.org?format=json'
{"ip":"192.143.241.250"}

How I can access from container to the elasticsearch service from host?

A: It is likely that the Elasticsearch instance on your host is only listening on localhost (127.0.0.1).  Take a look at the network.host setting in your main configuration file (possibly /etc/elasticsearch/elasticsearch.yml, or something similar).  If it looks something like:
network.host:
   - 127.0.0.1

You can explicitly add the Docker bridge interface:
network.host:
  - 127.0.0.1
  - 172.17.0.1

Or you could have it listen on all interfaces (if you are certain that's the behavior you want):
network.host:
  - 0.0.0.0

(reference for this configuration setting)


text:
Q: How to make sticky session works with socket.io (w/ or w/o pm2)? Although the socket.io document said 'sticky session' can make socket.io work with node cluster. I just can't make it work.
I find pm2 had several issues opened against it, the closest solution I can find is this, "force to use websock option only", don't use sticky session at all.
Has anyone had any experience that makes node cluster work with socket.io?
------- update --------
I checked the other two sticky session implementations mentioned here, sticky-session vs socket.io-sticky-session node js library ! Which is better? , find 'sticky-cluster' can do the job.
Another lesson I learned is that sticky-session doesn't work well with pm2 cluster, e.g. confirm from https://github.com/uqee/sticky-cluster/issues/26. So don't use pm2 cluster mode when using socket.io(or use 'websocket' transport only).
The 'sticky-session' implementation mentioned in socket.io document actually works too. If anyone needs more explanation with code sample, please check here https://github.com/elad/node-cluster-socket.io !
I leave my question open because I still like to see if there are other inputs.


text:
Q: potential downside of setting UseTaskFriendlySynchronizationContext=true? ASP.Net applications originally created under .NET 4.0 and later ported to .NET 4.5 in Visual Studio will still run using the legacy ASP pipeline unless you remember to add one of these to your web.config:
<appSettings>
    <add key="UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>

or:
<system.web>
    <httpRuntime targetFramework="4.6.1" />
</system.web>

I have a couple of question here:

*

*if neither of these settings are present, but if I have recompiled my
application as a .NET 4.5 (say) project and used new classes like
System.Web.HttpClient, is my application running under .NET 4.0, .NET
4.5, or some hybrid environment?

*I know there are some nasty deadlocks that can happen if I use the
legacy ASP pipeline, call an async method like
HttpClient.SendAsync(), and block on the result with Task.Result() or
something similar.  But are there any risks to taking an application
that is (seemingly) working ok and adding either of the two settings
mentioned above?  I'm interested in the specific risks associated with
each setting, and how to assess them based on the characteristics of
my application.

*the appSetting "aspnet:AllowAsyncDuringSyncStages" with value false will do some checking (https://msdn.microsoft.com/en-us/library/hh975440%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396) that can give you some confidence that your old application won't break if you move it from the legacy ASP pipeline to the new one.  Has anyone had any experience with this?


text:
Q: create a three dimension matrix from a numpy array python the title essentialy, i have this array
       i   j  d  Uijd
0      1   1  0     1
1      1   1  1     1
2      1   1  2     2
3      1   1  3     1
4      1   1  4     1
...   ..  .. ..   ...
1570  15  15  2     1
1571  15  15  3     1
1572  15  15  4     1
1573  15  15  5     0
1574  15  15  6     2

i and j are origin and destiny respectively, and d is the day, i want to make a three dimension matrix and call it like U[i,j,d], but i don't know how. I tried using pandas but i didnt know how to use it
Im pretty new to python so im clueless
thanks in advance

A: Assuming a pandas DataFrame as input, sorted and non missing indices, you should be able to reshape using numpy:
U = df['Uijd'].to_numpy().reshape(15, 15, 7)

For a more generic method, you can extract the shape from the DataFrame using nunique:
U = df['Uijd'].to_numpy().reshape(df[['i', 'j', 'd']].nunique())

Alternative
If you really want to be able to run U[i, j, d], or to handle missing combinations, an alternative could be to set up an empty array and to assign the values:
U = np.zeros(df[['i', 'j', 'd']].max()+1, dtype=df['Uijd'].dtype)

U[tuple(zip(*df[['i', 'j', 'd']].values))] = df['Uijd']

U.shape
# (16, 16, 7)

U[15, 15, 6]
# 2


text:
Q: Why doesn't ssh always ask me to verify the server's key fingerprint? Sometimes, when I connect over SSH to a server that is not in my known hosts file, ssh gives me the message:

The authenticity of host '[domain] ([ip_address])' can't be established.
  RSA key fingerprint is [fingerprint].
  Are you sure you want to continue connecting (yes/no)?

If I select 'yes', then I get the message:

Warning: Permanently added '[domain]' (RSA) to the list of known hosts.

But for some other servers, (e.g. github.com) I am not prompted to continue, and instead I immediately get the following message, which is phrased slightly differently:

Warning: Permanently added the RSA host key for IP address '[ip_address]' to the list of known hosts.

What causes this difference in behaviour? And more importantly, when I am not prompted, do I need to manually check the key that has been added to the known_hosts file before continuing to work with the server?
In both cases I am authenticating via public-key. I'm running OS X 10.10.3, using the system-installed OpenSSH.

A: This is probably caused by the fact that these sited have their ssh fingerprint stored in DNS so they do not bother users with verifying the keyse anymore.
The feature is called SSHFP record. You can verify this using ssh-keygen -r github.com

A: Turns out I'm just an idiot.
Whilst, as Jakuje states, SSHFP does allow sites to store their public key fingerprint in their DNS records, in this instance the key was already in the known-hosts file, under the domain name, (which I discovered by adding the -v debug flag to my ssh command).
As the informational message I received explains, a new line was being added to the file for the IP address being used.


text:
Q: Woocommerce - Disable image change on variation select Is there a way to disable image change on variation select of a variable product?
I know that you can simple remove the image from variation but in my case this isn't an option because i need the variation images.
Any help is appreciated.

A: I'm posting a solution, not the perfect one, but is something.
In WooCommerce/assets/js/frontend/add-to-cart-variation.min file you can comment i.$form.wc_variations_image_update(a) and this will make variation image update on selection.


text:
Q: How to change the corner positions of UIImageView? I want to show a bellow image using UIImageView.

is it possible to show by UIImageView or any other way we can show it.
Please help me.

A: You need following type of design from your designer :

In above image. White part inside the red box will be transparent. And then you can set this image to UIImageView


text:
Q: Problem about absolute value
$$\begin{align*}
|x|=x &\text{if }x\geq 0\\
|x|=-x &\text{if }x\lt 0.
\end{align*}$$
  Show that $|xy|=|x||y|$.

I try to prove it as follows:
$|xy|=xy$ if $xy\geq 0$,
but $xy\geq 0$ if and only if $x\geq 0$ and $y\geq 0$.
Since $x\geq 0$ and $y\geq 0$, then
$x=|x|$ and $y=|y|$
hence from $|xy|=xy$
we have $|xy|=|x||y|$.
Am I correct?
How can I  show  the following two cases?
i. Show that $|x+y|\leq |x|+|y|$.
ii. If $y\gt 0$ and $-y\leq x \leq y$, then $|x|\lt y$

A: *

*No, you are not correct. It is false that $xy\geq 0$ if and only if $x\geq 0$ and $y\geq 0$. For example, if $x=-1$ and $y=-1$, then $x\lt 0$, $y\lt 0$, and $xy = (-1)(-1) = 1\geq 0$. So your claim is incorrect, and thus your argument is incorrect. There are other possibilities, and you need to consider them too.

*Even if your argument were correct for that part, you would not be done yet. You only considered the case in which $xy\geq 0$. What if $xy\lt 0$? You also need to do that case.

*The last statement is incorrect. For example, if $x=y$, then $-y\leq x\leq y$ is true, but $|x|\lt y$ is false.

*To show (i), consider the different cases. What happens if $x$ and $y$ are both positive? If $x$ and $y$ are both negative? If $x$ is positive and $y$ negative and $x+y\geq 0$? If $x$ is positive, $y$ is negative, and $x+y\lt 0$? If $x$ is negative and $y$ positive?

*To show (a corrected version of) (ii), consider the cases. What happens if $0\leq x\leq y$? What happens if $-y\lt x\lt 0$?


text:
Q: Unable to connect to any of the specified MySQL hosts during ASP.net Azure deployment In my ASP.net Web App, I built a MySQL database using MySQL workbench and connected it to Azure through "Azure for MySQL Database" resource group.
The following is the connection string of the database written in Web.config

<add name ="AzureCon" connectionString="Server={myserver}; Port=3306; Database={mydatabase}; Uid={myuser}; Pwd={mypassword}; SslMode=Preferred;"/>

I call the connection string using the following code

string CoString = ConfigurationManager.ConnectionStrings["AzureCon"].ConnectionString;

However, when I publish the web app using Azure, the only error I get is:

Unable to connect to any of the specified MySQL hosts

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySqlConnector.MySqlException: Unable to connect to any of the specified MySQL hosts.

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:
[MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
   MySqlConnector.Core.<ConnectAsync>d__68.MoveNext() +1567
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +26
   MySqlConnector.Core.<GetSessionAsync>d__10.MoveNext() +2632
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +27
   MySqlConnector.Core.<GetSessionAsync>d__10.MoveNext() +3745
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
   System.Threading.Tasks.ValueTask`1.get_Result() +121
   MySqlConnector.<CreateSessionAsync>d__115.MoveNext() +696
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
   MySqlConnector.<OpenAsync>d__27.MoveNext() +977
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
   MySqlConnector.MySqlConnection.Open() +61
   Hangfire.MySql.MySqlStorage.CreateAndOpenConnection() +49
   Hangfire.MySql.MySqlStorage..ctor(String connectionString, MySqlStorageOptions storageOptions) +140
   CoPro.<GetHangfireServers>d__9.MoveNext() in C:\Users\smir\Desktop\Files and Folders\Programming\C#\CoPro\CoPro\Startup.cs:22
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +76
   Hangfire.HangfireAspNet.StartInstances(Func`1 configuration) +130
   Hangfire.HangfireAspNet.Use(Func`1 configuration) +13
   Hangfire.HangfireAspNet.UseHangfireAspNet(IAppBuilder builder, Func`1 configuration) +21
   CoPro.Startup.Configuration(IAppBuilder app) in C:\Users\smir\Desktop\Files and Folders\Programming\C#\CoPro\CoPro\Startup.cs:37

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +168
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +105
   Owin.Loader.<>c__DisplayClass19_1.<MakeDelegate>b__0(IAppBuilder builder) +66
   Owin.Loader.<>c__DisplayClass9_0.<LoadImplementation>b__0(IAppBuilder builder) +123
   Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass5_0.<InitializeBlueprint>b__0(IAppBuilder builder) +81
   Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +445
   Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +119
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +91
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +522
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +176
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +219
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +304

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +659
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +89
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +189

I'm using no other database or connection.
As in Azure resource group, I have updated the Firewall security and added the "allow all" rule for all IPv4 addresses.
MySQL works fine locally.
Here's my firewall settings in the Azure Database for MySQL server

Here's the "Users and Privileges" tab in my connection in MySQL Workbench

Note: The problem was there even before connecting MySQL to Azure


text:
Q: How to convert this array using Hash Class in CakePHP? I have this array:
array(
    (int) 0 => array(
        'region_id' => array(
            (int) 0 => '19'
            (int) 1 => '23'
        )
    )
)

I would like to transform it, in:
array(
    (int) 0 => array(
        'region_id' =>  '19'
    ),
    (int) 1 => array(
        'region_id' =>  '23'
    ),
)

I read there is a magic class in cakephp (Hash).
Can I use it to transform the array or do I have to do it manually?

A: A good starting point is
$foo = array(
     0 => array(
                 'region_id' => array(
                     0 => 19,
                     1 => 23
                 )
             )
        );
debug(Hash::extract($foo, '{n}.region_id.{n}'));

Which returns
array(
    (int) 0 => (int) 19,
    (int) 1 => (int) 23
);

Your next job is to rename the array keys.

A: Here is your required result, but yes i have used both cake Hash and manual php functions:
May you like this:
    $result = Hash::extract($foo, '{n}.region_id.{n}');
    $result = array_chunk($result,1);
    $required_result = array();
    foreach($result as $k => $v){
    foreach($v as $k1 => $v1){
      $required_result[$k]['region_id'] = $v1;
    }
    }
    pr($required_result);exit;


text:
Q: Textbox cannot empty or enter digit 0 c# i use this code :
 private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 13)
        {
            if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Length == 0)
            {
                MessageBox.Show("Textbox Cannot Empty or digit 0");
                textBox5.Focus();
            }
            else
            {
                MessageBox.Show("Success!");
            }
            e.Handled = true;
        }
    }

when I empty the textbox appears messagebox I expected . but when I enter the number/digit "0" appears messagebox success ? for validation i used numeric. for validation I only want to use the numbers 1-9. anybody can help me?

A: If you want to validate numbers and allow only integers between 1 and 9, you should use int.TryParse:
if (e.KeyChar == 13)
{
    int number;
    if(int.TryParse(textBox5.Text, out number) && number >= 1 && number <= 9)
    {
        MessageBox.Show("Success!");
    }
    else
    {
        MessageBox.Show("Textbox must contain an integer between 1 and 9");
        textBox5.Focus();
    }
    e.Handled = true;
}

Side-note: || textBox5.Text.Length == 0 is redundant since string.IsNullOrWhiteSpace(textBox5.Text) checks that already.

A: Your problem is, that IsNullOrWhiteSpace checks only for null, not for the char '0'. If you want to check the digit too, you need to check in addition for textBox5.Text.Equals("0"):
if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Equals("0"))
{
    MessageBox.Show("Textbox Cannot Empty or digit 0");
    textBox5.Focus();
}
else
{
    MessageBox.Show("Success!");
}
e.Handled = true;

Edit: Here's a .NET Fiddle

Q:

what if the digits entered are 00000 ??

A:

*

*You can use int.TryParse as in the suggestion of Tim Schmelter

*Or you can use the following Regex for vaidation: \^0*$\
Again the .NET Fiddle
Here you need: using System.Text.RegularExpressions;
if (string.IsNullOrWhiteSpace(textBox5.Text) || Regex.Match(textBox5.Text, "^0*$").Success)
{
    MessageBox.Show("Textbox Cannot Empty or digit 0");
    textBox5.Focus();
}
else
{
    MessageBox.Show("Success!");
}
e.Handled = true;

A: if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Length == 0)
            {
                MessageBox.Show("Textbox Cannot Empty or digit 0");
                textBox5.Focus();
            }
            else
            {
                MessageBox.Show("Success!");
            }

In this piece of code you're checking if the text length is 0
// "" will have length 0
// "0" will have length 1

If you want to check if you have the digit 0 in that box you need to check the following:
if (string.IsNullOrWhiteSpace(textBox5.Text) ||
    textBox5.Text == "0")

textBox5.Text.Length == 0 // you don't need this anymore if youre using IsNullOrWhiteSpace as IsNullOrWhiteSpace checks for null, string.Empty, white spaces

Of course the most beautiful way to check that is to try to parse textBox5.Text and to see if you get a digit between 1 and 9 using the following code:
int.TryParse(textBox5.Text, out number) && number > 0 && number < 10

A: private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string[] removeCaracter = { "0",... };
            foreach (var item in removeCaracter)
            {
                textBox5.Text = textBox5.Text.Replace(item, "");
                textBox5.SelectionStart = textBox5.Text.Length ;
                textBox5.SelectionLength = 0;
            }
        }


text:
Q: Piping between multiple child processes I'm trying to process input through different child process from one parent. I can make it though the first 3 children, but after that, I can't seem to get any input into or anything of out sort.
Here is my code.
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>

int main(int argc, char** argv)
{
pid_t pid;
int  pipes_1[2];
int pipes_2[2];
pipe(pipes_1);
pipe(pipes_2);

switch(pid=fork())
  {
  case 0:
    dup2(pipes_1[0], 0);//copy stdin onto pipe 1 read
    dup2(pipes_2[1], 1);//copy stdout onto pipe 2 write
    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);

    execlp("sed", "sed","s/[^a-zA-Z]/ /g", "test.txt", (char*)NULL);

    break;

  default:
    break;
  }

switch(pid = fork())
  {
  case 0:
    dup2(pipes_2[0],0); //copy std onto pipes 2 read
    dup2(pipes_1[1],1);
    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);

    execlp("tr", "tr", "[A-Z]", "[a-z]", (char*)NULL);

    break;
  default:

    break;
  }
switch(pid=fork())
  {
  case 0:
    dup2(pipes_1[0], 0);
    dup2(pipes_2[1], 1);
    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);

    execlp("awk", "awk", "{for(i = 1; i <= NF; i++) {print $i;}}", (char*)NULL);
    break;
  default:

    break;
  }

switch(pid=fork())
  {
  case 0:
    dup2(pipes_2[0], 0);
    //dup2(pipes_1[1], 1);
    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);
    execlp("sort", "sort", (char*)NULL);
  default:
    break;
    }
wait();
return 0;
}

I know the formatting is bad. But can you see what I'm doing wrong? I think it may have something to do with only using two pipes.
EDIT: Updated code with 4 pipes.
int main(int argc, char** argv)
{
pid_t pid;
int  pipes_1[2];
int pipes_2[2];
int pipes_3[2];
int pipes_4[2];
 pipe(pipes_1);
pipe(pipes_2);
pipe(pipes_3);
pipe(pipes_4);

switch(pid=fork())
  {
  case 0:
    dup2(pipes_1[0], 0);//copy stdin onto pipe 1 read
    dup2(pipes_2[1], 1);//copy stdout onto pipe 2 write
    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);

    execlp("sed", "sed","s/[^a-zA-Z]/ /g", "test.txt", (char*)NULL);

    break;

  default:
    break;
  }

switch(pid = fork())
  {
  case 0:
    dup2(pipes_2[0],0); //copy std onto pipes 2 read
    dup2(pipes_3[1],1);
    close(pipes_3[0]);
    close(pipes_3[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);

    execlp("tr", "tr", "[A-Z]", "[a-z]", (char*)NULL);

    break;
  default:

    break;
  }
switch(pid=fork())
{
case 0:
  dup2(pipes_3[0], 0);
  dup2(pipes_4[1], 1);
  close(pipes_3[0]);
  close(pipes_3[1]);
  close(pipes_4[0]);
  close(pipes_4[1]);

  execlp("awk", "awk", "{for(i = 1; i <= NF; i++) {print $i;}}", (char*)NULL);
  break;
default:

  break;
  }*/

switch(pid=fork())
{
case 0:
  dup2(pipes_4[0], 0);
  //dup2(pipes_1[1], 1);
  close(pipes_4[0]);
  close(pipes_4[1]);
  //close(pipes_2[0]);
  //close(pipes_2[1]);
  execlp("sort", "sort", (char*)NULL);
default:
  break;
  }
wait();
return 0;
}

A: You seem to have a pipeline:
sed … | tr … | awk … | sort

You create just two pipes, where three are needed.  Create the third pipe and handle it correctly, and you'll be OK.

Adapting second code. Note that only three pipes are needed for four processes (and in general N-1 pipes are needed for N processes).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

static inline void error(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void)
{
    int pid;
    int pipes_1[2];
    int pipes_2[2];
    int pipes_3[2];
    pipe(pipes_1);
    pipe(pipes_2);
    pipe(pipes_3);

    if ((pid = fork()) == 0)
    {
        dup2(pipes_1[1], 1);
        close(pipes_1[0]);
        close(pipes_1[1]);
        close(pipes_2[0]);
        close(pipes_2[1]);
        close(pipes_3[0]);
        close(pipes_3[1]);
        execlp("sed", "sed", "s/[^a-zA-Z]/ /g", "test.txt", (char *)NULL);
        error("Failed to exec sed");
    }
    printf("sed:  %d\n", pid);

    if ((pid = fork()) == 0)
    {
        dup2(pipes_1[0], 0);
        dup2(pipes_2[1], 1);
        close(pipes_1[0]);
        close(pipes_1[1]);
        close(pipes_2[0]);
        close(pipes_2[1]);
        close(pipes_3[0]);
        close(pipes_3[1]);
        execlp("tr", "tr", "[A-Z]", "[a-z]", (char *)NULL);
        error("Failed to exec tr");
    }
    printf("tr:   %d\n", pid);

    if ((pid = fork()) == 0)
    {
        dup2(pipes_2[0], 0);
        dup2(pipes_3[1], 1);
        close(pipes_1[0]);
        close(pipes_1[1]);
        close(pipes_2[0]);
        close(pipes_2[1]);
        close(pipes_3[0]);
        close(pipes_3[1]);
        execlp("awk", "awk", "{for(i = 1; i <= NF; i++) {print $i;}}", (char *)NULL);
        error("Failed to exec awk");
    }
    printf("awk:  %d\n", pid);

    if ((pid = fork()) == 0)
    {
        dup2(pipes_3[0], 0);
        close(pipes_1[0]);
        close(pipes_1[1]);
        close(pipes_2[0]);
        close(pipes_2[1]);
        close(pipes_3[0]);
        close(pipes_3[1]);
        execlp("sort", "sort", (char *)NULL);
        error("Failed to exec sort");
    }
    printf("sort: %d\n", pid);

    close(pipes_1[0]);
    close(pipes_1[1]);
    close(pipes_2[0]);
    close(pipes_2[1]);
    close(pipes_3[0]);
    close(pipes_3[1]);

    int status;
    int corpse;
    while ((corpse = wait(&status)) > 0)
        printf("PID %d died 0x%.4X\n", corpse, status);

    return 0;
}

Sample input:
Happy Go Lucky!
PENULTIMATE DESTINY@
missing all upper-case=
What gives?
Digital 023123098 Diarrhea

Sample output:
sed:  74841
tr:   74842
awk:  74843
sort: 74844
PID 74841 died 0x0000
PID 74842 died 0x0000
PID 74843 died 0x0000
all
case
destiny
diarrhea
digital
gives
go
happy
lucky
missing
penultimate
upper
what
PID 74844 died 0x0000

The process ID information is primarily diagnostic.  If you pipe the output of the program to a filter, you will get different output (because of buffering, etc), but the difference is in the sequence in which the sorted data appears vs the diagnostics.  Print the diagnostics to standard error, or add a fflush(stdout) after each printf() and you'll get something similar to the shown output more routinely.


text:
Q: Display Time in AM PM from Model with DataAnnotations I am trying to display a Sql Server time field in AM and PM. It displays correcly in edit mode but not in list mode.
Model:
    public class HMSappointmentMetaData
{
    public int ID { get; set; }
    [Required(ErrorMessage = "Rep Name is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string Rep { get; set; }
    [Required(ErrorMessage = "Customer Name is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string Name { get; set; }
    [Required(ErrorMessage = "Address is required")]
    [StringLength(100, ErrorMessage = "Max length is 100")]
    public string Address { get; set; }
    [Required(ErrorMessage = "City is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string City { get; set; }
    [Required(ErrorMessage = "Zip is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string ZipCode { get; set; }
    [Required(ErrorMessage = "County is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string County { get; set; }
    [Required(ErrorMessage = "Home Phone is required")]
    [StringLength(10, ErrorMessage = "Max length is 10")]
    public string HomePhone { get; set; }
    [Required(ErrorMessage = "Mobile Phone is required")]
    [StringLength(10, ErrorMessage = "Max length is 10")]
    public string CellPhone { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string OwnHome { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string HaveAttic { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string AvgElectric { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string SummerSpike { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string TriedAny { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string InsulationType { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string InsulationAge { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string LastPaint { get; set; }
    [Required(ErrorMessage = "Question is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string Married { get; set; }
    public string Spouse { get; set; }
    [Required(ErrorMessage = "Occupation is required")]
    [StringLength(50, ErrorMessage = "Max length is 50")]
    public string Job { get; set; }
    public string SpouseJob { get; set; }
    public string RetireFrom { get; set; }
    public string SpouseRetireFrom { get; set; }
    [Required(ErrorMessage = "Appointment Date is required")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> Date { get; set; }
    [Required(ErrorMessage = "Appointment Time is required")]
    [DataType(DataType.Time)]
    [DisplayFormat(DataFormatString = "{0:hh\\:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.TimeSpan> Time { get; set; }
    [DisplayFormat(DataFormatString = "{0:hh\\:mm tt}")]
    public System.TimeSpan? TimeForDisplay { get { return (Time.HasValue) ? (System.TimeSpan?)DateTime.Now.TimeOfDay.Add(Time.Value) : null; } }
    public HMSappointmentMetaData()
    {
        Time = new TimeSpan(14,30,0);
    }

    [DataType(DataType.MultilineText)]
    public string Comments { get; set; }
    public string CreditScore { get; set; }
}

List View:

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayNameFor(model => model.City)

            @Html.DisplayNameFor(model => model.Date)

            @Html.DisplayNameFor(model => model.Time)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.City)

                @Html.DisplayFor(modelItem => item.Date)

                @Html.DisplayFor(model => model.TimeForDisplay)

                @Html.ActionLink("Notes", "Index", "AdminNotes", new { AppointmentID = item.ID }, null) |
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })

    }

This results in 24 hr time (14:30)
Edit View:
@Html.EditorFor(model => model.Time)

This displays the correctly formatted time(2:30 PM).

A: I know its not ideal but without little bit of extra work I could not get it working so here are the options
Option 1
Use a DisplayTemplate and format manually.
Option 2 -- I like this better.
Add this new property to your ViewModel
[DisplayFormat(DataFormatString = "{0:hh\\:mm tt}")]
public DateTime? TimeForDisplay
{
  get { return (Time.HasValue)? (DateTime?)DateTime.Today.Add(Time.Value):null;}
}

use this new Property for Display Only in the view as follows
@Html.DisplayFor(model => model.TimeForDisplay)

Here is the Demo Link


text:
Q: How to call the value when ng-model with ng-repeat is used? Angular JS I have a problem of ng-model not geting called in controller if I use ng-repeat. As you can see below, in sports section, I get the sports value undefined when the form is submitted in controller however for demands, I get whatever I input into the field meaning it gets the value.
I tried to identify by id however it does not work as well.
<form ng-submit="sendDetails(sports, demands)" ng-class="form-horizontal" enctype="multipart/form-data">

        Sports:
        <input class="form-control" ng-model="sports" ng-repeat="sports in selectedSports" type="text" disabled/>

        <input class="form-control" ng-model="demands" type="text"/>

        <button class="btn btn-default" type="submit">Submit</button>

</form>

angular.factory('sportsFactory', function($http) {
return {
    postAdministrationEntries: function ($sports, $demands){
        var fd = new FormData();
        fd.append('sports', $sports);
        fd.append('demands', $demands);
        return $http.post('/sendDetails', fd,{
        headers: { 'Content-Type': undefined }
        });
    }
}

Controller
$scope.sportsValues =[];
$scope.sendDetails = function($sports, $demands){
    if($demands.length > 0 ){
        var sendDetailsPromise = sportsFactory.sendDetails($sports, $demands);
        sendDetailsPromise.success(function (data){
            $sportsValues = data;
};

A: It's probably because each loop through you are assigning the same model each time. You need to use the $index of the loop in combination with the model:
<input class="form-control"
  ng-model="sports[$index]"
  ng-repeat="sports in selectedAttributes track by $index"
  type="text" disabled />

Although I'm sure you realise that by being disabled, the input is never going to actually be changed from the model you give it (assuming it's not empty).

A: The most common way to work with an array of objects, is to have the ng-model use a property of each object:

angular.module("app",[])
.controller("ctrl", function($scope) {
  $scope.itemList = [
    {name: 'apple', value: 11},
    {name: 'orange', value: 22},
    {name: 'peach', value: 33},
  ];
})

ng-repeat DEMO

       {{item.name}} <input ng-model="item.value" />

    {{itemList | json}}