text:
Q: grep float with percent sign in R I have long strings containing various text and numeric data like this
a <- "$3,295,000; 8 Units; 4.08% Cap Rate; 9,360 SF Bldg;"
and I would like to be able to extract the percentage, in this case 4.08%.
How can I match this pattern with grep()?

A: You can use a non-greedy match in sub for this:
sub('.*?([0-9.]+%).*', '\\1', a)
[1] "4.08%"

This will only match the first instance of the pattern in the string.
The .*? is non-greedy, so it won't "suck up" characters in the following pattern, which matches what you want.

A: We can use str_extract
library(stringr)
str_extract_all(a, "[0-9.]+%")[[1]]
#[1] "4.08%"

If we only need to match the first instance, use str_extract instead of str_extract_all.  Though the other answer also does the same thing, it is better to use str_extract_all for multiple cases.

grep is used to return the index of a string whether it has a particular pattern or not.  Suppose if we use grep, it will return the index as 1 (as there is only one element in the vector and it matches the pattern)
grep("[0-9.]+$", a)
#[1] 1

For extracting substring either str_extract or gsub (from base R can be used.

A: The pattern you should be using is (?:[0-9]{1,2}(?:\.[0-9]{1,2})?%)
It matches Upto 2 digits . Upto 2 digits %
Regex101 Demo


text:
Q: Why exclude clause not working as expected.. powershell? I have a powershell script designed to go through some backup files, archive the month end backup(if its the first of the month) and delete anything older than 9 days after that.  I'm trying to tell it to exclude the archive folder but it seems to be ignoring that and I'm unsure why.. kind of a noob to powershell.
I've tried using -notlike $Exlcude+% I've tried -notmatch -NE  .. I even tried notcontains even though I knew that wouldn't work.. I tried applying the $exclude to every portion of the code where that folder might be accessed and its still making a copy of it.
#If first of the month copy latest backups to Monthly Backup Folder - will copy full folder path
PARAM($BackupPath="\\SomeServer\sqltestbackups\",
$Exclude= "\\SomeServer\sqltestbackups\Archive")

   #Grab a recursive list of all subfolders
$SubFolders = dir $BackupPath -Recurse | Where-Object {$_.PSIsContainer} | ForEach-Object -Process {$_.FullName}

#Iterate through the list of subfolders and grab the first file in each

$Year = (get-date).Year
$Month = (get-date).Month
$StartOfMonth = Get-Date -Year $Year -Month $Month -Day 1
$Today = (Get-Date).day
$Date = (GET-DATE).AddDays(-9)
$PrevMonth = (GET-DATE).year.ToString()+(Get-Culture).DateTimeFormat.GetMonthName((Get-Date).AddMonths(-1).month)
$Destination=$Exclude + "\" + $Prevmonth +"\"

IF (!(Test-Path -path $destination)) {New-Item $destination -Type Directory}

IF($Today -eq '5')
{
$Path = $BackupPath #Root path to look for files
$DestinationPath = $Destination #Remote destination for file copy

#Grab a recursive list of all subfolders
$SubFolders = dir $Path -Recurse | Where-Object {$_.PSIsContainer -and $_.DirectoryName -notmatch $Exclude} | ForEach-Object -Process {$_.FullName}

#Iterate through the list of subfolders and grab the first file in each
ForEach ($Folder in $SubFolders)
    {
    $FullFileName = dir $Folder | Where-Object {!$_.PSIsContainer -and $_.DirectoryName -notmatch $Exclude} | Sort-Object {$_.LastWriteTime} -Descending | Select-Object -First 1

    #For every file grab it's location and output the robocopy command ready for use
    ForEach ($File in $FullFileName)
        {
        $FilePath = $File.DirectoryName
        $ArchFolder = $File.DirectoryName
        $ArchFolder=$ArchFolder.Replace($BackupPath,"")+"\"
        $FinalPath=$destinationPath+$ArchFolder
        $FileName = $File.Name
        robocopy $FilePath $FinalPath $FileName /A-:SH /R:6 /W:30 /Z
        }
    }
}

# Delete files older than 9 days that are not contained within the month end folder
Get-ChildItem $BackupPath -Recurse |
  Where-Object { !($_.PSIsContainer) -and
                   $_.LastWriteTime -lt $Date -and
                   $_.Directory -notlike $Exclude+"%" } |
    Remove-Item

The code works except for the copy month end portion.. in this portion it is including the archive folder and I end up with it copying the previous month.. the script is designed to put the files in archive/YM/FullPath of backup so what is happening is its going Archive/YM/ARchive/YM/FullPath even though I'm trying SO HARD to exclude this path from the folders.
Example of whats going wrong with the robocopy
Source : \SomeServer\sqltestbackups\ARCHIVE\2019March\SomeOtherServer\SQLBackups\SomeDatabase\master\
Dest : \SomeServer\sqltestbackups\Archive\2019March\ARCHIVE\2019March\SomeOtherServer\SQLBackups\SomeDatabase\master\

A: the type DirectoryInfodoes not have a property DirectoryName. Try property BaseName instead.
# dir, gci are aliases for Get-ChildItem
Get-ChildItem $Path -Recurse `
    | Where-Object { $_.PSIsContainer -and $_.BaseName -notmatch $Exclude }

works.
To see which types are returned and which members there are type
Get-ChildItem .\ | Where-Object { $_.PSIsContainer } | ForEach-Object { $_.GetType() }
# and
Get-ChildItem .\ | Where-Object { $_.PSIsContainer } | Get-Member

But be careful: You will get a lot of output on directories with many files and subdirectories.
Also have a look at the answer How can I exclude multiple folders using Get-ChildItem -exclude? on stackoverflow. This answer comes with lots of elegant solutions for PowerShell from v1.0 to v5.0.

A: problem was
$Exclude= "\\SomeServer\sqltestbackups\Archive" I needed to double up the \s to be

$Exclude= "\\\\SomeServer\\sqltestbackups\\Archive"

after doing this the script worked fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is $x+I$ a root? Let $K$ be a field, let $f(x)\in K[x]$ be irreducible, and let $I=(f(x))$. Why is it the case that $f(x+I)=0$? Here we are assuming $x+I\in K[x]/I$

A: Suppose $f(x) = \sum^n_{i+1}a_ix^i$. Notice that $f(x+I) = {\sum^n_{i=1}}a_i(x+I)^i = \sum^n_{i+1}a_ix^i +I = I$ because $f(x) \in I$ and $I$ is zero in $K[x]/I$ because $aI = I$ for all $a \in K[x]$.


text:
Q: How to validate input text length in material input? I am developing an application using angular dart. I am using angular dart material input for getting input from user.
I have a multiline text input for which I use material input and type="text".
I have made this field "required" but the problem is when the user enters white space or enter, the "required" is gone. I need a attribute where i can specify a constraint that at least one non-white space character must be entered.
How to achieve this?
Here is my code where I have used material input:
<material-input
    ngControl="textAnswer" [(ngModel)]="answer" multiline
    type="text" label="Your answer" required>
</material-input>

A: As per documentation you can use all input elements attribute with it.

All of the attributes that can be used with normal <input> and <textarea> elements can be used on elements inside <mat-form-field> as well

So use HTML5 pattern attribute to match the custom pattern(regular expression).
<material-input
    ngControl="textAnswer" [(ngModel)]="answer" multiline
    pattern="[\s\S]*\S[\s\S]*"
    type="text" label="Your answer" required>
</material-input>

[\s\S]*\S[\s\S]* will help to match a string with at least one non-space character.
NOTE : To include all other character use [\S\s] since . doesn't include a newline character.


text:
Q: Should I use GregorianCalendar or Date for a birthday field? I'm a little bit confused about using the class GregorianCalendar and Date.
What is the difference?
For instance: I have a field in a Person object that represents the date he was born.
Do I have to use Date or GregorianCalendar?
What is the best use for them?

A: If you were writing down the details on paper, would you write down the date of birth as a date, or would you write down a calendar with a circle around the date?
You would write down the date. Date is a concrete date. Calendar is a tool for working with dates.

A: I would use Date to represent the date of birth.
Use Calendar (and child classes) to manipulate dates.

A: Both Date and Calendar classes suffer from poor APIs. You should use the Joda Time library instead.


text:
Q: I cannot understand the usage of Descriptor the declaration:
%macro Descriptor 3
dw  %2 & 0FFFFh
dw  %1 & 0FFFFh
db  (%1 >> 16) & 0FFh
dw  ((%2 >> 8) & 0F00h) | (%3 & 0F0FFh)
db  (%1 >> 24) & 0FFh
%endmacro

the usage:
DA_DRW      EQU 92h

LABEL_GDT:         Descriptor    0,              0, 0
LABEL_DESC_TEST:   Descriptor 0500000h,     0ffffh, DA_DRW
LABEL_DESC_VIDEO:  Descriptor  0B8000h,     0ffffh, DA_DRW

I just started to study nasm yesterday, and please answer it a little detailed...

A: A macro amounts to compile-time text substitution. In this case you've got a macro named Descriptor which takes 3 arguments. Each usage of the macro will be substituted for the macro body, with %n being replaced with the n:th argument.
For example:
LABEL_DESC_TEST:   Descriptor 0500000h,     0ffffh, DA_DRW

Will expand to:
LABEL_DESC_TEST: dw  0ffffh & 0FFFFh
                 dw  0500000h & 0FFFFh
                 db  (0500000h >> 16) & 0FFh
                 dw  ((0ffffh >> 8) & 0F00h) | (DA_DRW & 0F0FFh)
                 db  (0500000h >> 24) & 0FFh


text:
Q: Display images of cards from a file I need to code my program to randomly select three cards from a deck of cards.  The images are in a folder on my desktop.  I then display the images of the cards.  My program runs fine as far as reading from the file and then randomly picking 3 cards out of the 52.  I have the program printing the 3 random cards in the output.  But I can not see the images of the cards when the java window opens up on my computer.  It displays a small line that just continuously repeats.  So I think it is trying to display the cards but I have something wrong somewhere that is keeping the whole card(s) from displaying.
    Thanks in advance for your help!
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class DisplayThreeCards {

    public static void main(String[] args) {

        // File location
        File folder = new File("//Users//macuser//Desktop//DeckOfCards");
        File[] fileList;
        fileList = folder.listFiles();

        // Generate random card.  Uses the Math.rand() function.
        // The '%' operator is used to make sure the random is between 0-52.
        int randomCard = (int) (Math.random() * 1000);
        System.out.println(fileList[randomCard % 52].getAbsolutePath());

        // Print the filename.
        // Card 1
        System.out.println(fileList[randomCard % 52].getName());
        randomCard = (int) (Math.random() * 1000);
        // Card 2
        System.out.println(fileList[randomCard % 52].getName());
        randomCard = (int) (Math.random() * 1000);
        // Card 3
        System.out.println(fileList[randomCard % 52].getName());
        randomCard = (int) (Math.random() * 1000);

        try {
            ImageFrame frame = new ImageFrame(fileList[randomCard % 52].getAbsolutePath());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        } catch (Exception E) {

        }

        // Create a window for the card images to be displayed
        class ImageFrame extends JFrame {

            public ImageFrame(String name) {
                setTitle("ImageTest");
                setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

                ImageComponent component = new ImageComponent(name);
                add(component);
            }

            public static final int DEFAULT_WIDTH = 300;
            public static final int DEFAULT_HEIGHT = 300;
        }

        class ImageComponent extends JComponent {

            private static final long serialVersionUID = 1L;
            private Image image;

            public ImageComponent(String name) {
                try {
                    File image2 = new File(name);
                    image = ImageIO.read(image2);
                } catch (IOException e) {
                }
            }

            @Override
            public void paintComponent(Graphics g) {
                if (image == null) {
                }
                int imageWidth = image.getWidth(this);
                int imageHeight = image.getHeight(this);

                g.drawImage(image, 50, 50, this);

                for (int i = 0; i * imageWidth <= getWidth(); i++) {
                    for (int j = 0; j * imageHeight <= getHeight(); j++) {
                        if (i + j > 0) {
                            g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j * imageHeight);
                        }
                    }
                }

            }
        }
    }
}


text:
Q: Java Exception handling I would like to know what happens in java if a method call signature has a exception but there is no try catch block in the method
what happens when a exception happens at runtime.
public void someMethod (Collection<file> files) throws Exception
for(File f : files) {
    process(f);
}

A: A method's throwing an exception is a separate concept from having code in a method that catches an exception:
Exceptions thrown inside a try/catch are eligible to be caught by catch blocks on that construct.
When a method declares it throws one or more exceptions, then that type of exception may be thrown out of that method to be caught by another. Note that unchecked exceptions don't need to be declared. They just go their merry way without letting anyone know what's up.

A: There are two thing in java exception handling mechanism

*

*Exception Throwing

*Exception handling (with a catch() block).

In this case your someMethod()throws an exception. If any method use this method then it has to catch and handle the exception. If the calling method of someMethod() does not handle the exception then any one method in the method call hierarchy must catch() and handle the exception.

A: Then the exception thrown will be propagated to the method caller and the method caller have to deal with it (either catch it or declare itself that it will throw exception).

A: an exception is just another type of return for a function. if you don't catch it in this function, it will be passed to the next. and if that function cant catch it, then that function will also pass the exception to the function which called it and the chain goes on until you finally reach a catch block for it where it is handled or the jvm prints its stack trace through system.out.
Hope this helps!


text:
Q: Extending function with local maximum in a bounded smooth domain. Let $\Omega \subset \mathbb{R}^{N}$ be a bounded $C^{2}$-domain. Take $V$ as a subset of $\Omega$ and define a smooth function $\phi$ such that $\phi \in C^{2}(\overline{V})$ and attains a local maximum at $x_{*} \in V$ but not on $\partial V$. Can we extend $\phi$ such that it becomes a $C^{2}(\overline{\Omega})$ function and still attains its maximum at $x_{*}$?
Intuitively, it seems doable at least in $\mathbb{R}$ and $\mathbb{R}^{2}$ but I would like a rigorous explanation of how to extend $\phi$ into the original domain.


text:
Q: UIBarButtonItem with custom view fill toolbar evenly I am trying to add 6 UIBarButtonItem with a custom view (UIButton) and I want each button to fill the height and be the same width as the other buttons while filling out the toolbar. With the following code, I got close, but theres a space at the beginning and the end of the toolbar. What am I doing wrong?  Removing the first and last spacer makes the space at the beginning and the end even larger, and removing all the spacers has huge gaps between each UIBarButtonItem
override func viewDidLoad() {
    let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let b1 = UIBarButtonItem(customView: one)
    let b2 = UIBarButtonItem(customView: two)
    let b3 = UIBarButtonItem(customView: three)
    let b4 = UIBarButtonItem(customView: four)
    let b5 = UIBarButtonItem(customView: five)
    let b6 = UIBarButtonItem(customView: six)

    toolbarButtons = [spacer, b1, spacer, b2, spacer, b3, spacer, b4, spacer, b5, spacer, b6, spacer]

    setToolbarItems(toolbarButtons, animated: false)
}

private func createBottomButton(number: String) -> UIButton {
    let bottomButton = UIButton(type: UIButtonType.Custom)
    bottomButton.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width / 6, height: 44)
    bottomButton.setTitle(number, forState: UIControlState.Normal)
    return bottomButton
}


text:
Q: How to make multiple asp.net ListView control use same Sorting event handler? In a single webpage, there are four ASP.NET Webeserver ListView controls displaying data from similar collections. At present one separate ListView_Sorting event handler exists for each ListView instance. They all perform the same task. How can I write a single event handler to handle all four _Sorting events?

*

*Protected Sub lvwQualified_Sorting(sender As Object, e As ListViewSortEventArgs) Handles lvwQualified.Sorting

*Private Sub lvwPendDlrResln_Sorting(sender As Object, e As ListViewSortEventArgs) Handles lvwPendDlrResln.Sorting

*Protected Sub lvwUnqualified_Sorting(sender As Object, e As ListViewSortEventArgs) Handles lvwUnqualified.Sorting

*Protected Sub lvwPendingReview_Sorting(sender As Object, e As ListViewSortEventArgs) Handles lvwPendingReview.Sorting
I want to write a single handler like
Protected Sub listView_Sorting(sender As Object, e As ListViewSortEventArgs) Handles ListView.Sorting
Thank you.

A: The Handles clause allows for a list of events to handle, so you just need to add the other events separated by a comma.
You should be able to do something like:
Protected Sub listView_Sorting(sender As Object, e As ListViewSortEventArgs)
Handles lvwQualified.Sorting, lvwPendDlrResln.Sorting, lvwUnqualified.Sorting, lvwPendingReview.Sorting

A: You've got two choices:
Specify the several events you want your Event Handler to handle
Protected Sub ListView_Sorting(sender As Object, e As ListViewSortEventArgs) Handles lvwQualified.Sorting, lvwPendDlrResln.Sorting, lvwUnqualified.Sorting, lvwPendingReview.Sorting
    ...
End Sub

Specify your Event Handler to your ListViews OnSorting methods
Protected Soid ListView_Sorting(sender As Object, e As ListViewSortEventArgs)
    ...
End Sub

And then:
<asp:ListView ID="lvwQualified"
        OnSorting="ListView_Sorting"
        runat="server" />

<asp:ListView ID="lvwPendDlrResln"
        OnSorting="ListView_Sorting"
        runat="server" />

...


text:
Q: How to parse values from a JSON field that is also a JSON? I have a JSON that has one field that in itself contains another JSON. I am having trouble parsing values from this embedded JSON. I am using SwiftyJSON and can extract the embedded JSON as JSON type (swiftyJSON type). But I am unable to do anything with it further to get values from the embedded JSON.
thisjson[0]["MESSAGE_JSON_BODY"] will return a JSON type.
thisjson[0]["MESSAGE_JSON_BODY"].string will convert this JSON to string.
Now I need help parsing fields from MESSAGE_JSON_BODY JSON. How to parse the fields in the embedded JSON?

A: I figured out one way to solve this problem myself, here I print out the field value for  "fieldkey":
            if let stringdata: String = thisjson[0]["MESSAGE_JSON_BODY"].string{
                var data: NSData = stringdata.dataUsingEncoding(NSUTF8StringEncoding)!
                let msgjson = JSON(data: data)
                println(msgjson["fieldkey"])
            }


text:
Q: How do I resolve the "Crypt Kicker" exercise proposed in "Programming Challenges (The Programming Contest Training Manual)"? "Programming Challenges (The Programming Contest Training Manual)" is probably one of the nicest exercises book on algorithms.
I've resolved the first 11 exercises, but now I am stuck with "Crypt Kicker" problem:

Crypt Kicker
  A common but insecure method of encrypting text is to permute the letters of the alphabet.
  In other words, each letter of the alphabet is consistently replaced in the text by some other letter. To ensure that the encryption is reversible, no two letters are replaced by the same letter.
Your task is to decrypt several encoded lines of text, assuming that each line uses a different set of replacements, and that all words in the decrypted text are from a dictionary of known words.
Input
  The input consists of a line containing an integer n, followed by n lowercase words, one per line, in alphabetical order. These n words compose the dictionary of words which may appear in the decrypted text.
  Following the dictionary are several lines of input. Each line is encrypted as described above.
There are no more than 1,000 words in the dictionary. No word exceeds 16
  letters. The encrypted lines contain only lower case letters and spaces and
  do not exceed 80 characters in length.
Output
  Decrypt each line and print it to standard output. If there are multiple solutions, any one will do.
  If there is no solution, replace every letter of the alphabet by an asterisk.
Sample Input 6
    and
    dick
    jane
    puff
    spot
    yertle
bjvg xsb hxsn xsb qymm xsb rqat xsb pnetfn
    xxxx yyy zzzz www yyyy aaa bbbb ccc dddddd
Sample Output
   dick and jane and puff and spot and yertle ...

What strategy should I to take in order to resolve this exercise? I was thinking to a classic and brutish backtracking solution, but I am trying avoid that until I find something more intelligent.
PS: This is not homework related, I am just trying to improve my overall skills.

A: KeyArray will hold the replacement table.

*

*Start with an empty KeyArray, this is version 0

*Match longest encrypted word to longest dictionary word and add to KeyArray
(if there are two longest, pick any), this is version 1.

*Decrypt some letters of the next longest crypted word.

*Check if the decrypted letters match the letter in the same
position in any dictionary word of the same length.

*If none matches, go back to version 0 and try another word.

*If some letters match, add the rest of the letters to KeyArray, this is version 2.

*Decrypt some letters of the next longest crypted word.

*Check if the decrypted letters match the letter in the same
position in any dictionary word.

*If none matches, go back to version 1 and try another word

*If some letters match, add the rest of the letters to KeyArray, this is version 3.

Repeat until all words are decrypted.
If at version 0 none of the longest words creates a partial decrypt in
shorter words, very probably there is no solution.

A: A minor optimization could be done by enumerating possibilities before the backtracking run. In Python:
dictionary = ['and', 'dick', 'jane', 'puff', 'spot', 'yertle']
line = ['bjvg', 'xsb', 'hxsn', 'xsb', 'qymm', 'xsb', 'rqat', 'xsb', 'pnetfn']

# ------------------------------------

import collections

words_of_length = collections.defaultdict(list)

for word in dictionary:
  words_of_length[len(word)].append(word)

possibilities = collections.defaultdict(set)
certainities = {}

for word in line:
    length = len(word)
    for i, letter in enumerate(word):
        if len(words_of_length[length]) == 1:
            match = words_of_length[length][0]
            certainities[letter] = match[i]
        else:
            for match in words_of_length[length]:
              possibilities[letter].add(match[i])

for letter in certainities.itervalues():
    for k in possibilities:
        possibilities[k].discard(letter)

for i, j in certainities.iteritems():
    possibilities[i] = set([j])

# ------------------------------------

import pprint
pprint.pprint(dict(possibilities))

Output:
{'a': set(['c', 'f', 'o']),
 'b': set(['d']),
 'e': set(['r']),
 'f': set(['l']),
 'g': set(['f', 'k']),
 'h': set(['j', 'p', 's']),
 'j': set(['i', 'p', 'u']),
 'm': set(['c', 'f', 'k', 'o']),
 'n': set(['e']),
 'p': set(['y']),
 'q': set(['i', 'j', 'p', 's', 'u']),
 'r': set(['j', 'p', 's']),
 's': set(['n']),
 't': set(['t']),
 'v': set(['c', 'f', 'o']),
 'x': set(['a']),
 'y': set(['i', 'p', 'u'])}

If you have some single-element possibilities, you can eliminate them from the input and rerun the algorithm.
EDIT: Switched to set instead of list and added printing code.

A: I actually tried a rather different approach. I built a trie from the dictionary words. Then I walk through the trie and the sentence together recursively (traversing the trie in a DFS).
At each space I make sure I hit the end of a word in the trie and if so I loop back to the root. Along the way I keep track of the letter assignments I've made so far. If ever I have an assignment that contradicts a prior assignment I fail and unravel the recursion to the point I can make the next possible assigment.
It sounds tricky but it seems to work quite well. And it is really not that hard to code up!

A: Another possible optimization, if you have "enough" text to deal with and you know the text's language, you can use letter frequencies (see : http://en.wikipedia.org/wiki/Letter_frequency). This is of course a very approximative approach when dealing with 6 / 7 words but will be the fastest way if you have a few pages to decode.
EDIT : about Max's solution, you could try to extract some characteristics of the word, too, such as repeating letters. Obviously, remarking that puff in the dictionary and qymm in the encrypted text are the only four letter words ending with a double letter gives a straight answer for 3 of the letters. In more complex scenarios, you should be able to narrow the possibilities for each letter couple.

A: Here is a Java implementation with more refinements to the algorithm proposed by @Carlos Gutiérrez.
Crypt Kicker Algorithm and Solution, what went wrong?

*

*The refinement is to add a word pattern to reduce the search space for words. For example, words "abc" and "her" have the same pattern while "aac" and "her" don't as a three distinct letters word would not match a tow letters distinct word.

*Moreover, the algorithm can be implemented recursively which is more intuitive and sensible.


text:
Q: How to truncate a number with two positions after the decimal point in python? I would like to truncate a number with only two positions after decimal point and return this number. But when I use the string format as float(" % .2f" % number), it returns 1.0 when the given number is like 1.0000. How could I resolve this problem? Thanks a lot.
It seems like my description was not clear enough. Let me take the 1.0005 as an example. I would like to return the number 1.00 with only two positions after the decimal point, rather than a string "1.00". So I choose to use string format to truncate the original number 1.0005 to a string "1.00" which satisfies the requirement of decimal points but it is still a string, I would like to return a number. So I use the float to convert it to a float number, but it seems like float() in gonna truncate the number to 1.0.


text:
Q: How to split string at fixed numbers of character in clojure? I'm new in clojure. I'm learning about splitting string in various ways. I'm taking help from here:
https://clojuredocs.org/clojure.string/split
There is no example to split string at fixed number of character.
Let a string "hello everyone welcome to here". I want to split this string after every 4th char, so the output (after split) should be ["hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re"]. Note that white space is consider a char.
can anyone tell me, how can I do this? Thanks.

A: (->> "hello everyone welcome to here"
     (partition-all 4)
     (map (partial apply str)))

A: With transducers:
(def sample "hello everyone welcome to here")

(into [] (comp (partition-all 4) (map #(apply str %))) sample)

Slower than the other examples though :).

A: you could use re-seq:
user> (def s "hello everyone welcome to here")
#'user/s

user> (re-seq #".{1,4}" s)
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")

or partition the string, treating it as a seq:
user> (map (partial apply str) (partition-all 4 s))
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")


text:
Q: How do you get the solutions for screen width and height working? Many people have asked how to get screen width and height in vb.
The answers included using My.Computer.Screen.Bounds, Screen.PrimaryScreen.Bounds, System.Windows.SystemParameters.PrimaryScreenWidth, etc.
But for me, they all come back undefined.
One said I want the Screen class located at System.Windows.Forms.Screen. I added a reference to system.windows.forms. Didn't work. Is that something to import? That didn't work either.
Do I import something? Add a reference? Inherits?
And many solutions use javascript. It's easy to get screen width and height with javascript. But the timing is wrong. I want the screen size before I generate my VB code. But I have to put my javascript in an "onload=", which makes it run AFTER the VB code is generated.
The only way I've found is to let the javascript determine the dimensions, then redirect, passing these values as parms. And that's not bullet proof.
There must be a simpler way.
I've never found a COMPLETE example, including declarations, even on the microsoft pages, that works.
Thanks in advance.

A: My.Computer.Screen.Bounds, etc are only valid for WinForms applications. You are using a Web application framework so this is not valid.
The only way to determine this is to use something that runs on the client e.g. Javascript as you have mentioned. I suggest you have a look at this question: Get the size of the screen, current web page and browser window
I suppose the question really is what are you trying to achieve as there is probably a better way of doing it


text:
Q: No such file or directory - Handling Special Characters Inroduction
A client is complaining that specific files cannot be processed that contain special characters such as "García" with an accented í. On my own machine and my own server everything works fine using the same filenames.
Therefore I suspect it could be an OS/filesystem/configuration/JVM issue.
Overview of App Steps:

*

*is to download them and write them to disk from the pop3 server.

*Process files and move them plus other stuff.

Questions

*

*How can I deal with this without change the file names?

*If I do have to change the names, is there a library to do it?

Stacktrace
2016-06-02 15:05:29.178 - [MapperUtils ] - [ERROR] - emailmonitoring.services.mappers.MapperUtils
        java.io.FileNotFoundException: /tomcat/data/inbox/1464710346000_03c2eef8-f224-4b45-9a2f-d5aade3e642a/Garc??a.pdf (No such file or directory)
        at java.io.FileInputStream.open(Native Method) ~[na:1.6.0_45]
        at java.io.FileInputStream.<init>(FileInputStream.java:120) ~[na:1.6.0_45]
        at org.apache.commons.io.FileUtils.doCopyFile(FileUtils.java:1138) ~[commons-io-2.4.jar:2.4]
        at org.apache.commons.io.FileUtils.doCopyDirectory(FileUtils.java:1428) ~[commons-io-2.4.jar:2.4]
        at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1389) ~[commons-io-2.4.jar:2.4]
        at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1261) ~[commons-io-2.4.jar:2.4]


text:
Q: How to change parent of a node in django-mptt I m using django-mptt (Ver 5.5) django-mptt.github.io/django-mptt/
I have a tree structure as:
+Object Oriented
|----Java
+Procedural
|----Python
|----PHP
|----B
|----C

now i want to restructure the tree , by changing the parent of Python and PHP node to Object Oriented, to look as:
 +Object Oriented
|----Java
|----Python
|----PHP
+Procedural
|----B
|----C

i have tried this by changing the parent attribute of node as
>>>oo=Nodes.objects.get(name='Object Oriented')
>>>py=Nodes.objects.get(name='Python')
>>>py.parent=oo

After doing this i get:
>>>py.parent==oo
True
>>>py.get_ancestors(ascending=False, include_self=False)
[<Nodes : 'Procedural'>]

Even the inbuilt-methods such as:
py.move_to(oo,'first-child')

doesn't seems to work for me.
if more clarification is required my model is:
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Nodes(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        return self.name

    class MPTTMeta:
        order_insertion_by = ['name']

kindly tell me a way to change the parent.


text:
Q: How do I verify logged in user account against SQL Sever So, I'm trying to incorporate some kind of authentication into my WPF Application.
Currently, the application connects to a SQL Server, retrieves data from the database, inserts data into the database and updating data in the database. It works as intended.
What I would like to do next is when the Application starts up it checks whether the logged in user has permission to connect to and interact with the Server - and then deny access to the application or certain parts of it.
My SQL Server is using Windows Authentication for authentication, and the users will be on the same network and domain that will be connecting to the SQL Server.
I'm not very familiar with Windows Authentication and how it would work in my Application, so any help/examples/point in the right direction would greatly be appreciated.
[EDIT]:
Thanks to Jan W who pointed me in the direction of checking the username against the server in the SQL layer with IS_MEMBER, I stumbled upon HAS_DBACCESS.
With a little bit of playing around, I created this function to check if the current user has access to the Database. If not, I disable what I need to in the application or give the user a message that they have not got permission:
Private Shared Function HasDBAccess(connectionString As String) As Boolean
    Dim command As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand
    Dim reader As Data.SqlClient.SqlDataReader

    Dim conn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(connectionString)
    command.CommandText = "SELECT HAS_DBACCESS ('yourdatabasenamehere')"
    command.CommandType = Data.CommandType.Text
    command.Connection = conn

    conn.Open()

    reader = command.ExecuteReader()

    If reader.HasRows Then
        Do While reader.Read()
            Dim hasAccess As Integer = reader.GetInt32(0)
            Select Case hasAccess
                Case 1
                    Return True
                Case 0
                    Return False
            End Select
        Loop
    End If

    conn.Close()
End Function

Thanks Jan :)

A: First of all I think what you're after is to implement authorization not authentication. Authentication is already done by domain controller in your network.
Authentication versus Authorization
There is a lot of different approaches to the problem you are trying to solve depending on your business needs. I could imagine that you could have different acces roles defined as Domain Groups in your AD. Then you could check against AD if the user interacting with your application is a member of a group or not. It can be done in the application layer (How to check if a user belongs to an AD group?) or in the SQL layer (https://msdn.microsoft.com/en-us/library/ms186271.aspx)
Regards
Jan

A: Take a look at this:
WPF: Implementing Custom Authentication And Authorization
But I did it in this way:
CodeProject: Implement UI Element Authorization in WPF


text:
Q: $\Delta_0$-formula How do I write a $\Delta_o$-formula $\phi(X,R)$ equivalent (in basic set theory) to "$(X,R)$ is a linear ordering"?
I think I need to represent $(X,R)$ is a linear ordering in first order terms first but I'm not sure how to.

A: This is actually going to be easier than it may look; the trick is that all the quantifiers we want to use are secretly bounded by $R$, and we're "given" that up front.

Let me focus on one particular aspect - the comparability requirement

$(*)$ For any $a,b\in X$, either $aRb$ or $bRa$ or $a=b$.

The initial clause - "For any $a,b\in X$" - is just a bounded quantifier, "$a=b$" doesn't have any quantifiers at all, and "$aRb$" is going to be exactly as hard to deal with as "$bRa$." So let's try to express "$aRb$" using only bounded quantifiers.
Remember that the relation $R$ is really a subset of $X^2$. So "$aRb$" is really just $$\langle a,b\rangle\in R.$$ And - using the Kuratowski notion of pairing - that is shorthand for $$\{\{a\},\{a,b\}\}\in R.$$ And this takes us to the key trick: the natural way to try to express this is to build $\langle a,b\rangle$ up from $a$ and $b$ somehow, but set theory doesn't have any function symbols so that doesn't work. The obvious way to express $\langle a,b\rangle\in R$ involves introducing a "dummy" variable for $\langle a,b\rangle$, but that takes an unbounded quantifier.
Instead, we search within the relation $R$: we have $\langle a,b\rangle\in R$ iff there is some $x\in R$ such that

*

*$x$ has two elements, that is, $\exists y,z\in x(y\not=z)\wedge\forall u,v,w\in x(u=v\vee v=w\vee u=w)$;

*one of the elements of $x$ is $\{a\}$, that is, $\exists y\in x(a\in y\wedge\forall z\in y(z=a))$; and

*the other element of $x$ is $\{a,b\}$, that is, $\exists y\in x(a\in y\wedge b\in y\wedge\forall z\in y(z=a\vee z=b))$.
All of that only involved bounded quantifiers.

What's left to do?
Well, first of all we need to express "$R\subseteq X^2$" using only bounded quantifiers (really we should have done that first). Next, we have the antisymmetry and transitivity requirements. But all of this will use the "bounding-in-$R$" trick above: that we can talk about elements of $R$ being ordered pairs of elements of $X$ by using quantifiers bounded - at worst - by $R$ itself.


text:
Q: Efficient Image Normalization in Halide I've discover Halide (the language), a few weeks ago and I actually enjoy trying to optimize some parts of my code with it, nonetheless, I struggle to find an optimized implementation of a very basic image processing task: Normalization
Basically, If I is my grayscale Image, I just want:
I_norm = (I - min(I)) / (max(I) - min(I))

I've managed to come up with this code (Python API of halide but hopefully in C++ it is similar)
def normalize(input: hl.Buffer, height: int, width: int):
    low, high, norm_output = hl.Func('low'), hl.Func('high'), hl.Func('norm_output')
    x, y = hl.Var('x'), hl.Var('y')
    dom = hl.RDom([(0, width), (0, height)])

    low[hl._0] = hl.minimum(input[dom.x, dom.y])
    high[hl._0] = hl.maximum(input[dom.x, dom.y])

    norm_output[x, y] = (input[x, y] - low[0]) / hl.f32(high[0] - low[0])

    low.compute_root()
    high.compute_root()
    norm_output.compute_root().parallel(y).vectorize(x, 8)

    return norm_output

This piece of code works quite well (and it is the fastest I could come up with...), but as soon as I use it in a pyramid, let's say I'm doing this:
def get_structure(pyr: List, h: int, w: int, name: str) -> List:
    structure = [hl.Func('%s_%i' % (name, i)) for i in range(len(pyr))]
    norm_structure = [hl.Func('norm_%s_%i' % (name, i)) for i in range(len(pyr))]

    for lv, layer in enumerate(pyr):
        structure[lv][x, y] = some_function(layer)[x, y]  # return un-normalized "matrix"

    # apply my normalization function
    for lv, layer in enumerate(pyr):
        norm_structure[lv] = normalize(structure[lv], h, w)

    return norm_structure

Then everything becomes so slow....
Indeed, if I comment the line:
for lv, layer in enumerate(pyr):
    norm_structure[lv] = normalize(structure[lv], h, w)

and return structure instead. My overall pipeline run in under 40ms...
As soon as I put the normalization, it sky-rocket to **0.
So the question is, how can we compute efficiently a normalization in Halide? Like we can do lot's of very complex stuff very efficiently but a simple normalization on the whole domain... ?
Note: I've also added scheduling, for example:
for lv in range(len(pyr)):
    norm_structure[lv].compute_root().parallel(y, 4).vectorize(x, 4)

in get_structure(), but obviously it doesn't improve anything
Also, I'm not satisfied with my code, in the sense that In the best halide code that I've found I'm looping twice to get the min and then the max and finally compute the normalization,
will If I was doing that by myself I would maintain 2 variables for min and max in one loop
Note also that I've spend a lot of time to find how to optimize my code, be it through the official halide apps on Github or elsewhere but I didn't find anything to help build that simple function efficiently...
So, Thank you, in advance for the help!


text:
Q: Cropping face in matlab I need a Matlab code that will crop the face from an image of person. I have been searching google for past 3 days but unable to find a code that works correctly. Can someone please tell me how to do it.

A: You may read about wavelets, I don't believe you were "searching google for 3 days".
Image Processing using Gabor Filter

In case you have license to the vision toolbox:
% Create a cascade detector object.
faceDetector = vision.CascadeObjectDetector();

% Read a video frame and run the detector.
videoFileReader = vision.VideoFileReader('visionface.avi');
videoFrame      = step(videoFileReader);
bbox            = step(faceDetector, videoFrame);

% Draw the returned bounding box around the detected face.
videoOut = insertObjectAnnotation(videoFrame,'rectangle',bbox,'Face');
figure, imshow(videoOut), title('Detected face');

The code above will output the following detection. Please note that the algorithm doesn't recognize the 2 faces in the picture behind the Mathwork engineer nor his own face on the lcd screen to his right:


text:
Q: cocos2d-html5 menuItem callback i'm new on Cocos2d-html5. i'm making some samples and i can't run a menu item callback.
Menu item sprite is drawed on canvas but doesn't working
can someone help me.
var primeraEscena = cc.Scene.extend({
onEnter:function(){
    this._super();
    var layer = new Escenas();
    layer.init();
    this.addChild(layer);
}
})

var Escenas = cc.Layer.extend({
init:function()
{
    this._super();
    try{
    var layer1 = cc.LayerColor.create(new cc.Color4B(255, 255, 255, 255), 600, 600);
    layer1.setAnchorPoint(new cc.Point(0.5,0.5));

    var botonImg = cc.Sprite.create("img/greencircle.png", cc.rect(0, 0, 40, 40));
    var botonImg2 = cc.Sprite.create("img/greencircle.png", cc.rect(1, 0, 40, 40));
    var botonImg3 = cc.Sprite.create("img/greencircle.png", cc.rect(2, 0, 40, 40));
    var boton = cc.MenuItemSprite.create(botonImg, botonImg2,botonImg3, this.func, this);
    try{
        boton.setEnabled(true)
    }catch(e){
        alert(e)
    }
    var menu = cc.Menu.create(boton, null);
    menu.setEnabled(true)
    menu.alignItemsVerticallyWithPadding(10);
    this.addChild(menu);
    }catch(e){alert(e)}

    return true;
},
func:function(){
    alert("Wiiii")
}

});

Thank you

A: I think you missed calling setTouchEnabled for the layer
this.setTouchEnabled(true);

For more details, you can find samples here: http://cocos2d-x.org/npm/ccmenu/index.html


text:
Q: Some combo of Rails 3.2.8+ & MySQL not playing well together We are in the process of upgrading to Ruby 1.9.3 from 1.8.7 plus trying to update Rails from 3.2.1 to 3.2.8 or 9.  Our app works with Ruby 1.9.3-p327 and Rails 3.2.1, but as soon as I upgrade Rails to any higher version, I start seeing MySQL errors:
(0.2ms)  BEGIN
  SQL (0.5ms)  INSERT INTO `orders` (`cancelled_at`, `completed_at`, `created_at`, `customer_id`, `refunded_at`, `updated_at`, `uuid`, `website_id`, `workflow_state`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?)' at line 1: INSERT INTO `orders` (`cancelled_at`, `completed_at`, `created_at`, `customer_id`, `refunded_at`, `updated_at`, `uuid`, `website_id`, `workflow_state`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
   (0.1ms)  ROLLBACK
Completed 500 Internal Server Error in 194ms

ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?)' at line 1: INSERT INTO `orders` (`cancelled_at`, `completed_at`, `created_at`, `customer_id`, `refunded_at`, `updated_at`, `uuid`, `website_id`, `workflow_state`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)):
  app/controllers/search_controller.rb:231:in `build_new_order'
  app/controllers/search_controller.rb:432:in `add_to_cart?'
  app/controllers/search_controller.rb:37:in `new'

And all we're doing is a basic:
@order = Order.create! @website

If we just call Order.new or Order.create and check the validity of @order, it passes (@website is also valid).  Call save!, we get the MySQL error.  We can run the same Order.create! in the console and it passes!!
Also, once we see see the error, then the whole site errors.  We've seen some issues with Workflow and have 'downgraded' it to 0.8.1.  I've tried different versions of MySQL2 (currently using 0.3.11).  I've tried using activerecord-mysql2-adapter instead and the site blows up completely.  I haven't tried a different version of Paper Trail (currently using 2.6.4) and maybe I'm concentrating too much on the model since it works on in the console.  However, the controller does work until we try to add something to the cart and create an Order.
Searching the web, rails website, workflow, mysql2 and stack overflow hasn't turned up anything.
Has anyone else ran into something similar?  Any other suggestions would be appreciated.  Thanks!
EDIT:
The release notes for 3.2.2 say "Query cache instrumentation includes bindings in the payload".  So I searched for 'cache instrumentation' and found this:
https://github.com/orslumen/record-cache/issues/21

A: After removing record-cache, everything works as expected.  We were only using it on one model so we didn't lose much performance.  And strange enough, it wasn't on our Order model but our Product model.


text:
Q: Multidimensional (Fredholm) integral equation (of first kind) Suppose,
\begin{align*}
g(t_1,t_2)=\int f(s) \left[K_1(t_1,t_2,s)h(t_1) + K_2(t_1,t_2,s)\right]ds %\\
%g(t_1,t_2)=\int f(s) \left[K_1(t_1,t_2,s) + K_2(t_1,s)h(t_2)\right]ds
\end{align*}
The problem is to solve for $f(s)$ and $h(t_2)$, given the continuous kernel functions $K_1(t_1,t_2,s)$ and $K_2(t_1,t_2,s)$ and the function $g(t_1,t_2)$.
I am interested (1) in solutions to $f(s)$ in this multidimensional (Fredholm) equation (of the first kind), (2) is the solution to $f(s)$ unique, and (3) more generally, are there good references to integral equations when there is more than one unknown function and $g(\cdot)$ is multimdimensional.
Note: I am only interested in solutions to $f(s)$ i.e. $h(t_1)$ is an unknown nuisance function.
Here is my attempt at a solution that I'm not sure how to make rigorous (and if it's correct). Assume there exists $L_2(t_1,t_2,w)$ such that for all $f(\cdot)$, we have
$$\int  \int f(s) L_2(t_1,t_2,w) K_2(t_1,t_2,s)dt_2ds=f(w)$$
Then,
\begin{align*}
\int L_2(t_1,t_2,w) g(t_1,t_2) dt_2&= \int L_2(t_1,t_2,w) \int f(s) K_1(t_1,t_2,s)h(t_1) dt_2d_s \\
& \qquad \qquad + \int  \int f(s) L_2(t_1,t_2,w) K_2(t_1,t_2,s)dt_2ds \\
&=\int L_2(t_1,t_2,w) f(s) K_1(t_1,t_2,u)h(t_1)dsdt_2 + f(w) \qquad (*)
\end{align*}
Normalize $h(0)=1$ and let $K_3(w,u)=\int L_2(0,t_2,w) K_1(0,t_2,u)h(0)dt_2$. Then,
\begin{align*}
\int L_2(0,t_2,w) g(0,t_2) dt_2
&=\int L_2(0,t_2,w) f(u) K_1(0,t_2,u)h(0)dudt_2 + f(w) \\
&=\int f(u) K_3(w,u)du + f(w)
\end{align*}
which is a Fredholm equation of the second kind and can be solved using standard techniques.
I don't know how to make (*) rigorous.


text:
Q: How to make editable rows efficiently? I've a query, im using js to make a table tds editable. Im able to do this with individual methods on edit button .
I want to know what will be more efficient way to code this so that each edit onclick make that particular row only and in future if I increase table rows , it should be able to do it.
Right now im assigning id to the tr and targeting its row items , which is working but seems to be inefficient.
something like
var toBeEdited = document.getElementById('first-tr').getElementsByTagName('td');
  for (let i = 0; i < toBeEdited.length; i++) {
    toBeEdited[i].setAttribute('contenteditable', 'true');
  }

Here's the reference code for example
https://jsfiddle.net/karantewari/jyx2k7cv/3/
Thanks in advance :)

A: Update onclick="makeEditable(this)" on element. Here this will be the current td element object.
Use one parameter with function as makeEditable = (td) => {...
And use var toBeEdited = td.parentElement.parentElement.getElementsByTagName('td'); for fetching respective tr childs.

makeEditable = (td) => {
  var toBeEdited = td.parentElement.parentElement.getElementsByTagName('td');
  for (let i = 0; i < toBeEdited.length; i++) {
    if (toBeEdited[i].getElementsByTagName('button').length == 0) {
      toBeEdited[i].setAttribute('contenteditable', 'true');
    }
  }
}

      Header 1
      Header 2

      Name
      Location 1

        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-first-tr" onclick="makeEditable(this)">
                          Edit
                        </button>

      Name 2
      Location 1

        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-second-tr" onclick="makeEditable(this)">
                          Edit
                        </button>

      Name 3
      Location 3

        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-third-tr" onclick="makeEditable(this)">
                           Edit
                        </button>

A: Checkout the below snippet, we can edit the td on clicking edit and edit feature will be disabled on focus out of the content editable item

makeEditable = function(){
var el = event.target.parentElement.parentElement;
Object.keys(el.children).forEach(function(i){
  el.children[i].setAttribute('contenteditable', true);
  el.children[i].setAttribute('onblur', 'disableEdit()');
});
}
disableEdit = function(){
var el = event.target.parentElement;
Object.keys(el.children).forEach(function(i){
  el.children[i].removeAttribute('contenteditable', true);
});
}

                      Header 1
                      Header 2

                      Name
                      Location 1

                        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-first-tr" onclick="makeEditable()">
                          Edit
                        </button>

                      Name 2
                      Location 1

                        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-second-tr" onclick="makeEditable()">
                          Edit
                        </button>

                      Name 3
                      Location 3

                        <button type="button" class="btn btn-icon btn-default btn-outline" title="Edit" id="edit-third-tr" onclick="makeEditable()">
                           Edit
                        </button>


text: Q: blocking a process in python I'm confused about what happens when a process is being blocked waiting for an event. I didn't find technical documentation about such. (i.e.) like that of the socket library when a server is receiving connections from clients with the accept() method. If there'd been no pending connections the process is blocked until it receives one. Is there a library that is used for doing this?


text:
Q: Why in MS-SQL-SERVER documentation BETWEEN has lower precedence than AND? Documentation shows that the AND operator has higher precedence than ALL, ANY, BETWEEN, IN, LIKE, OR, and SOME.
How can the AND operator, that is used to combine conditions,have higher precedence than operators such as IN, BETWEEN, and LIKE that are used within conditions? It seems impossible to combine conditions before the conditions have been evaluated individually.
What would that mean?

A: Thanks to Jeroen Mostert, Martin Smith and allmhuran for the clarification.
The crucial point to understand is that : the "evaluation" in the documentation is really with respect to parsing, not actual execution.
Suppose having the following table
Test
[col1, col2, col3]
1      2     'a'
0      4     'e'
0      2     'f'

The following query is then executed against the above table:
SELECT *
FROM Test
WHERE col3 LIKE 'a%' AND col1*col1*col1<>0 AND col2/col1>0;

Now the Operator Precedence doesn't determine the evaluation order of conditions, but, as Martin Smith said in his comment, it is just about where the implied parentheses would go.
In this case the two AND have the same precedence and the query is parsed in one of the two following ways:
(col3 LIKE 'a%' AND col1*col1*col1<>0) AND col2/col1>0  (1)

or
col3 LIKE 'a%' AND (col1*col1*col1<>0 AND col2/col1>0)  (2)

(in my case the first one (1)) and then the optimizer (always in my case!!) chooses to execute the division col2/col1>0 first and a division by zero error is thrown.
Keep in mind the declarative nature of SQL:  you say what you want not how it's done:  this is left to the dbms engine which will performs optimizations, create the optimal query plan and execute it returning the desired result.


text:
Q: How to disable binlog in pt-archiver I am archiving the large table using percona's pt-archive utility. But it fills my binary log a lot.
Is there any option to disable the binary logging during the archiving from this utility.
I have read its documentation that we can do something in --analyze option but its not cleared how to define this. Because this option also optimize / analyze the table that i don't want.
can you please provide any working example ?

A: In short you need to add the options b=true and --local
Note that b=true is a DSN option and need to be added after --source or --dest depending on your needs. I will show an example on the bottom of this answer.
You can easily try out with this dummy test:
 CREATE TABLE `dummyids` (
  `ids` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ids`)
) ENGINE=InnoDB ;

insert into dummyids
    select @i := @i + 1 as id
     from (select true union all select true) t0
    join (select true union all select true) t1
    join (select true union all select true) t2
    join (select true union all select true) t3
    join (select true union all select true) t4
    join (select true union all select true) t5
    join (select true union all select true) t6
    join (select true union all select true) t7
    join (select true union all select true) t8
    join (select true union all select true) t9
    join (select true union all select true) t10
    join (select true union all select true) t11
    join (select true union all select true) t12
    join (select true union all select true) t13
    join (select true union all select true) t14
    join (select true union all select true) t15
    join (select true union all select true) t16
    join (select true union all select true) t17
    join (select true union all select true) t18
    join (select true union all select true) t19
;

Now you can check the size of the binlog and last position (it will be the latest binlog pls change your path and binlog name)
# ls -lh /path/to/mysql/data/

# sudo mysqlbinlog mysql-bin.000012 | tail -n 100

Record the position and size of the binlog to compare after running pt archive
pt-archiver --source h=localhost,D=bar,t=dummyids,b=true --local --where "1 = 1" --limit=10000 --progress=50000 --txn-size=50000 --statistics --purge --bulk-delete

Now run the commands to check the size and latest position of the binlog again you should notice they haven't changed.
Hope this helps more people with the same issue.
The options are explained on percona tool manual pt-archiver options


text:
Q: What are the calculations behind the properties in a re-rotated element? I have been playing around with an idea of a contact card type of thing. Apparently hexagons are quite a new trend, but I'd like to keep it a tad simpler, namely: rotated squares. Considering I am quite knowledgeable with HTML and CSS, it wasn't that hard to accomplish this. In a few minutes I came up with this.
HTML

        Queen Elizabeth

CSS
a {
    display: inline-block;
    margin: 50px;
    width: 150px;
    height: 150px;
    transform: rotate(45deg);
    position: relative;
    overflow: hidden;
}

/* Pseudo element for border */
a:after {
    content: "";
    display: block;
    width: 142px;
    width: calc(100% - 8px);
    height: 142px;
    height: calc(100% - 8px);
    border: 2px solid white;
    position: relative;
    z-index: 10;
    top: 4px;
    left: 4px;
}

/* Span for bg-image and text */
a > span {
    display: block;
    height: 213px;
    width: 213px;
    top: -31px;
    left: -31px;
    position: absolute;
    background-size: cover;
    background-position: center;
    transform: rotate(-45deg);
    padding: 76px 24px 0;
}

The idea is quite simple:

*

*Make the link itself a block element, rotated it 45 degrees. Don't forget overflow: hidden

*Rotate its child 45 degrees back, apply a background-image to this element (dynamically loaded in my case, therefore inline)

This works in all major browsers and degrades gracefully into a simple square in other browsers (IE8 and below; though you might need a background size polyfill). For this reason I want to keep this HTML structure.
So, what's the problem? First of all I'd like to make it applicable to different sizes where I would only need to set the width and height of the link itself (a) after which the height and width of its child are calculated automatically - in my project I can use the relatively new CSS3 calc() function, if that's of any help, along with the beauty of SASS/SCSS. In other words, I need the ratio between the width of a and its child span. As far as I can tell, it seems that the ratio is the square root of 2: 213 / 150 = 1.42. My first question is, then, why? What's the logic and/or arithmetic behind this? Why can't the span simply take up 100% width of its parent? Why need it be exactly square root 2 times more?
Additionally, I also would like to know where the top and left values come from. I haven't figured out yet which arithmetic might be the base of is. I do know that this might be dependent on the value of transform-origin, but I don't know how exactly. In other words, is it possible with a pre-defined transform-origin value to have top and left to be zero and by doing so removing the need for a per-case calculated value? If not, how can the value of these properties be calculated based on the width value of its parent, as that's the only value that should be known?
Summary, if only the width and height of a are known, how do I:

*

*calculate the width for its child, and how can that be explained?

*calculate/use the offsets (top and left) on span and how can they be explained?

I do not want to use any JS solutions for this. If something isn't clear, please post a comment so I can clarify.

A: UPDATED FIDDLE
First of all, as the background-image defined for span will overlap the actual a element, it needs to be bigger. As we are talking about an angle of 45 degrees, this leads to a triangular cut-off shape in which the size of the main square (i.e. the image) is the long side, and the other two equally-sized lines are of the anchor. Therefore, the size of the image (span) should be equal to sqrt(2)*100% ~= 141.42%.
The positioning of the span then. First we rotate the image back by 45 degrees. Import for this action is that the transform-origin is set to 0 0 rather than 50% 50%. By doing so, the element is rotated around a single point right in the top middle of the rhombus. After rotating it's only a matter of translate the element on the X-axis, which can also be done with CSS transforms: translateX(-50%).
No matter what value is now passed onto a's width and height, the image should always be aligned perfectly within it, with the correct dimensions.
(In the fiddle, try giving a a value of, say, 400px. It looks nice, doesn't it? You can also give nice hover effects to the image.)
a {
    display: inline-block;
    width: 200px;
    height: 200px;
    transform: rotate(45deg)  translate(50%);
    position: relative;
    overflow: hidden;
}
a:after {
    content: "";
    display: block;
    width: calc(100% - 8px);
    height: calc(100% - 8px);
    border: 2px solid white;
    position: relative;
    z-index: 10;
    top: 4px;
    left: 4px;
}
a > span {
    display: block;
    height: 141.42%;
    width: 141.42%;
    top: 0;
    left: 0;
    position: absolute;
    background-size: cover;
    background-position: center;
    transform: rotate(-45deg) translateX(-50%);
    transform-origin: 0 0;
}


text:
Q: Got an Increment error "Invalid left-hand side expression in postfix operation" I've got the following module:
module.exports = {
    name: "reputation",
    aliases: ['rep','vouch'],
    category: "misc",
    /**
     * @param {Discord.Message} message
     * @param {Array} args
     */
    async execute(message, args) {
      if (args.length >= 2) {
          args.shift();
        reason = args.join(' ');
      }else reason = 'No reason provided';
      let member = message.mentions.members.first();
      const repmessage = new Discord.MessageEmbed()
      .setTitle("Reputation Given!")
      .setDescription(`<a:peachverify:853511481747046420> You gave a reputation to ${member} for: \`${reason}\``)
      .setFooter(`Rep ID: ${1++}`)
      .setColor("#02b2f7")
      message.channel.send(repmessage)
    },
  };

But whenever I try to run it I got an error:

Invalid left-hand side expression in postfix operation

How do I fix this?

A: It's because you're trying to increment a number. Try to run the following snippet:

console.log(1++)

If you want to increase the reputation of the member, you must have some variable that you can increase. I can see none in your code, so you'll need to fix that.
Anyway, once you store the reputation somewhere, you can use the ++ like you wanted:

let rep = 0
console.log({ rep })
rep++
console.log({ rep })
rep++
console.log({ rep })

A: In JavaScript, numbers are fixed. You cannot increment a number, but you can increment a variable.
let i = 1;
console.log(i++) //shouldn't throw

Doing 1++ is just like doing the following:
1 = 1+1

Which is a clear error.


text:
Q: How to write Electron debug messages into a file? I am developing an Electron app and I want to write it's debug messages into a log file. If I start my app by executing electron electron --debug=5858, then the debug output shows up in my console.
I can grab the console output from the command-line by attaching > debug.log to my cmd statement but I wonder if there is also a programmatic way to save the debug logs for Electron's main process?
My main goal is to be able to write debug logs from the main process when distributing my app.


text:
Q: Selection Sorter, but i want the output to merge So I want to make a sorter, but I want it the output to merge. In my code, I separated the two different type variables from the list, the integer and int.
List:
nlist = [19, 5, 'cat', 'rabbit', 2, 32, 'mice', 'dog', 7]

Code:
def bubble(collection):
    dlist = [e for e in collection if isinstance(e, int)]
    clist = [e for e in collection if not isinstance(e, int)]
    for endnum in range(len(dlist)-1, 0, -1):
        print(dlist)
        for i in range(endnum):
            if dlist[i] > dlist[i+1]:
                dlist[i], dlist[i+1] = dlist[i+1], dlist[i]
    for endnumm in range(len(clist)-1, 0, -1):
        print(clist)
        for j in range(endnumm):
            if clist[j] > clist[j+1]:
                clist[j], clist[j+1] = clist[j+1], clist[j]
    answer = dlist + clist
    print(answer)

Output:
[19, 5, 2, 32, 7]
[5, 2, 19, 7, 32]
[2, 5, 7, 19, 32]
[2, 5, 7, 19, 32]
['cat', 'rabbit', 'mice', 'dog']
['cat', 'mice', 'dog', 'rabbit']
['cat', 'dog', 'mice', 'rabbit']
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']

Required Output:
[19, 5, 'cat', 2, 'rabbit', 32, 'mice', 'dog', 7]
[19, 5, 'cat', 2, 32, 'rabbit', 'mice', 'dog', 7]
[19, 5, 'cat', 2, 32, 'rabbit', 'mice', 7, 'dog']
[19, 5, 2, 'cat', 32, 'rabbit', 'mice', 7, 'dog']
[19, 5, 2, 32, 'cat', 'rabbit', 'mice', 7, 'dog']
[19, 5, 2, 32, 'cat', 'rabbit', 7, 'mice', 'dog']
[19, 5, 2, 32, 'cat', 7, 'rabbit', 'mice', 'dog']
[19, 5, 2, 32, 7, 'cat', 'rabbit', 'mice', 'dog']
[5, 19, 2, 32, 7, 'cat', 'rabbit', 'mice', 'dog']
[5, 2, 19, 32, 7, 'cat', 'rabbit', 'mice', 'dog']
[5, 2, 19, 7, 32, 'cat', 'rabbit', 'mice', 'dog']
[5, 2, 19, 7, 32, 'cat', 'rabbit', 'mice', 'dog']
[2, 5, 19, 7, 32, 'cat', 'rabbit', 'mice', 'dog']
[2, 5, 7, 19, 32, 'cat', 'rabbit', 'mice', 'dog']
[2, 5, 7, 19, 32, 'cat', 'mice', 'rabbit', 'dog']
[2, 5, 7, 19, 32, 'cat', 'mice', 'dog', 'rabbit']
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']

Is there any way that I can make the output to the required output?
Same dude earlier just fixed some problems and the question.

A: The general approach
You can approach this problem by considering that your "greater than" relation is a little more complex than just Python's >:

*

*for two numbers, > applies,

*for two strings, > applies,

*between any number and any string, the string is "greater than" the number.

Now, implement a function that does that, and use it instead of > in your algorithm.
Implementing that approach
Let's write that logic into function my_greater_than:
def my_greater_than(a, b):
    """greater than where an int is "smaller" than other things"""
    if isinstance(a, int):
        if isinstance(b, int):
            return a > b
        else:
            return False
    else:
        if isinstance(b, int):
            return True
        else:
            return a > b

You'll notice here I took a shortcut: I don't check for str, I just check for int and assume str in the else clauses.
That's quite verbose, for clarity, but we can write the same logic more concisely, like this:
def my_greater_than(a, b):
    """greater than where an int is "smaller" than other things"""
    if isinstance(a, int):
        return isinstance(b, int) and a > b
    else:
        return isinstance(b, int) or a > b

Now, let's use this in place of > in your bubble sort code. I'm keeping exactly your bubble sort algorithm, but calling it just once with our greater than function used on the whole list.
def bubble(collection):
    my_list = list(collection)
    for endnum in range(len(my_list)-1, 0, -1):
        print(my_list)
        for i in range(endnum):
            if my_greater_than(my_list[i], my_list[i+1]):
                my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
    print(my_list)

And now we can call it on your list to get the output you want:
nlist = [19, 5, 'cat', 'rabbit', 2, 32, 'mice', 'dog', 7]
bubble(nlist)

prints
[19, 5, 'cat', 'rabbit', 2, 32, 'mice', 'dog', 7]
[5, 19, 'cat', 2, 32, 'mice', 'dog', 7, 'rabbit']
[5, 19, 2, 32, 'cat', 'dog', 7, 'mice', 'rabbit']
[5, 2, 19, 32, 'cat', 7, 'dog', 'mice', 'rabbit']
[2, 5, 19, 32, 7, 'cat', 'dog', 'mice', 'rabbit']
[2, 5, 19, 7, 32, 'cat', 'dog', 'mice', 'rabbit']
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']

Additional notes

*

*You might notice I took a copy of collection into my_list on the first line of bubble(). That's because I don't want to modify the input list I was provided. If we worked directly on collection, we would find nlist also sorted after calling bubble().

*The other reason to copy the collection with a call to list() is that it lets us accept anything iterable. Collections could be a set, a list, a tuple, a dictionary or any other iterable in Python, and our sort function would work on it anyway.

*I print the output because that's what you did, but I would normally have had a return statement in there: replace print(my_list) on the last line of bubble() by return my_list.


text:
Q: Identify a story about running from a relentless chasing machine or bot I am trying to identify a story I read decades ago that I visualize this way and often think about when I am cross country running:
There is a machine that I visualize as round, with some way to destroy people (such as injecting them with something) that relentlessly chases the protagonist to run him down.
I seem to associate the name Ruun with the story.

A: This is "The Ruum" by Arthur Porges
Per wikipedia:

"A shape-shifting, indestructible robot—a "Type H-9 Ruum"—is accidentally left behind on earth during the age of the dinosaurs by
visiting aliens, and not recovered because their ship is destroyed in
a battle. The Ruum's work is collecting different species of animals
within a 30 mile radius, weighing 160 pounds (give or take 15 pounds)
and preserving them in a state of suspended animation for later
retrieval."

A full copy of the text (complete with illustrations) is available here.

You might also be interested to hear that the story had a sequel called "A specimen for the queen".


text:
Q: How do I detect new aspx file and get information from them? I'm developing a website that has modular section. I would like it that when a new aspx (and aspx.cs) file is placed in a subdirectory of the application that I can ask the class some information...
The idea is that when the file is placed in the directory a new menu item is added to the menu. To do that I need to "ask the class" for its name, icon, description, etc.
Is there a way to determine the class that is defined in codebehind file and to instantiate an instance of it?
I know I could look for and parse a config file for each plugin but I would rather not have to go that route.

A: The "standard" method for this is the config file you mention, in the form of a Sitemap.  You'll get a lot of good features out of it by doing it that way, like breadcrumbs and so forth.  I know this is exactly the answer you asked not to get, but there it is anyway.
If you insist, though, there's nothing stopping you from using MapPath and actually searching the disk for .aspx files, parsing them to pull out certain info (like class name), and then doing whatever you like.
But SiteMap is better, unless you have some very strange requirement.  Note that your sitemap can come from a database or another dynamic source, it doesn't have to be an XML file.


text:
Q: Python Unittest Inheritance I have 2 classes, A and B.
class A (unittest.TestCase):
   #methods here

class B (A):
   #methods here

when i try and call self.assertEqual(1,1) in a method of class B, I get the error mentioned here:
Why do I get an AttributeError with Python3.4's `unittest` library?
Yet if I call it in A, everything is fine.
Does unittest not follow regular inheritance? Is there only a very specific way you can use it?

A: I have tried your example as such:
import unittest

class A(unittest.TestCase):
    def test_a(self):
        self.assertEqual(1, 1)

class B(A):
    def test_b(self):
        self.assertEqual(2, 3)

if __name__ == '__main__':
    unittest.main()

and it worked, this is test result:
test_a (__main__.A) ... ok
test_a (__main__.B) ... ok
test_b (__main__.B) ... FAIL


text:
Q: Doctrine MongoDB disable logger on fixture load Is there a way to disable Doctrine MongoDB bundle logger on fixture load only? like suggested in https://stackoverflow.com/a/35222045/3965970 but for MongoDB bundle.
Thanks

A: Yes, absolutely the same way, call
$manager->getConnection()->getConfiguration()->setLoggerCallable(null); right in the fixture.

A: Unfortunately in Doctrine MongoODM-bundle version 4.0 and higher this approach no longer works.
The easiest way is to disable logging in the configuration, see https://symfony.com/doc/master/bundles/DoctrineMongoDBBundle/config.html
You can also disable the logger manually, but you'll need doctrine_mongodb.odm.command_logger service.
What I did in my Symfony 4 application is to create an alias to enable proper dependency injection and then unregister the listener:
services.yaml
Doctrine\Bundle\MongoDBBundle\APM\PSRCommandLogger:
    alias: "doctrine_mongodb.odm.command_logger"

some constructor of a Command or Service:
public function __construct(PSRCommandLogger $mongoLogger)
{
    $mongoLogger->unregister();
}


text:
Q: No error, but the For Loop does not print For a computer science project I am trying to make a game called snake using python, which the snake itself is represented by three XXX's that is printed onto an array. The snake also grows after 5 turns.
My question is concerning how to make a "For Loop" that iterates over the points in the snake and for each point in the snake, draws a new X on the board.
This is my code for that loop:
for i in snake:

    board[i[0]] [i[1]] = "X"

    return snake.pop()

print(snake)

No error shows up and the board is printed, but the snake (represented as XXX) is not printed. What is wrong with this for loop?
Additional information:

*

*I have a function that takes a size and returns an array of that size

*A function that takes a number of rows and a n number of columns and returns a board

*A function that displays a board.

Here is the rest of the code:
def createArray(size):
    return ["_"] * size

def createBoard(rows, cols):
        matrix = createArray(rows)
        for i in range(rows):
                matrix[i] = createArray(cols)
        return matrix

def displayBoard(m):
        for i in range(len(m)):
                for j in range(len(m[0])):
                        print(m[i][j], end=" ")

                print()

def main():
    snake = [[0,0],[0,1],[0,2]]

    board = createBoard(20,30)
    displayBoard(board)

    for i in snake:
        board[i[0]][i[1]] = "X"
        return snake
    print(snake)

main()


text:
Q: Get Number of emails sent by user in postfix I'm using postfix,I have an email user test@mydomain.com
How I can get total number of messages sent by this user ;
Iam trying to search in
/var/spool/mail
with no success

A: Have a look at pflogsumm

Pflogsumm is a log analyzer/summarizer for the Postfix MTA.  It is
  designed to provide an over-view of Postfix activity, with just enough
  detail to give the administrator a "heads up" for potential trouble
  spots.
Pflogsumm generates summaries and, in some cases, detailed reports of
  mail server traffic volumes, rejected and bounced email, and server
  warnings, errors and panics.


text:
Q: How can one avoid too many numbers after the decimalpoint? The following code generates numbers and than divides it with 1000:
But some times numbers like 1.2295999999999998 are generated, while 1229.6 is only being divided by 1000?
What do I need to change in the code, so that this does not occur?

Z1 = document.getElementById("Z1").innerHTML = Math.floor((Math.random() * 99899 + 100)) / Math.pow(10, Math.floor((Math.random() * 3 + 1)));

document.getElementById("L").innerHTML = Z1 / 1000;

A: document.getElementById("L").innerHTML = (Z1 / 1000).toFixed(2);
// if you want 2 digits after decimalpoint

Further Explaination:
Floating point numbers cannot represent all decimals precisely in binary. It has to do with how decimal values are converted to binary floating point numbers. For example, 1/10 turns into a repeating decimal in binary, so the number is not perfectly represented, and repeated operations can expose the error.


text:
Q: Variables, Square roots, and exponents
Answer : $x^2$
I got $x^n$, shouldn't I be multiplying the variables in the parentheses first. Thus cancelling out the roots and left with $x$ then to the power of n? thus -> $x^n$ ? Please explain step by step.

A: $$
(x^{1/n}*x^{1/n})^n = (x^{2/n})^n = x^2
$$


text:
Q: How can I get the total? I could not get the exact query to get the over all total of the total table. i want to get the total of each date in call_time table. here's my query:
SELECT call_type, channel, call_time,
       count (CASE WHEN upper(status) = upper('no answer') THEN 1 ELSE NULL END) AS cnt_no_answer,
       count (CASE WHEN upper(status) = upper('answered') THEN 1 ELSE NULL END) AS cnt_answer,
       count (status) AS cnt_total
FROM   app_account.cc_call
WHERE  channel = 'DAHDI/i1/'
AND    call_time BETWEEN ('30-DEC-2013') AND ('04-JAN-2014')
GROUP BY call_type, channel, call_time;

Some output of that query:
CALL_TYPE        CHANNEL    CALL_TIME CNT_NO_ANSWER  CNT_ANSWERED   CNT_TOTAL
LANDLINE         DAHDI/i1/  03-JAN-14     1            0               1
MOBILE-SUN       DAHDI/i1/  03-JAN-14     0            1               1
MOBILE-SUN       DAHDI/i1/  03-JAN-14     1            0               1
LANDLINE         DAHDI/i1/  03-JAN-14     1            0               1
LANDLINE         DAHDI/i1/  03-JAN-14     1            0               1
LANDLINE         DAHDI/i1/  03-JAN-14     1            0               1
MOBILE-SUN       DAHDI/i1/  02-JAN-14     1            0               1
MOBILE-SUN       DAHDI/i1/  02-JAN-14     0            1               1
LANDLINE         DAHDI/i1/  02-JAN-14     0            1               1
LANDLINE         DAHDI/i1/  02-JAN-14     1            0               1
MOBILE-SMART     DAHDI/i1/  02-JAN-14     1            0               1

My excepted Output:
CALL_TIME  CNT_NO_ANSWER CNT_ANSWERED
03-JAN-14   27             10
02-JAN-14   48             20

Please help me.
Thank you!

A: Use something like the following:
  SELECT CALL_TYPE, CHANNEL, TRUNC(CALL_TIME)
         , COUNT (CASE UPPER(STATUS)
                     WHEN UPPER('no answer') THEN 1
                     ELSE NULL
                  END) AS CNT_NO_ANSWER
         , COUNT (CASE UPPER(STATUS)
                       WHEN UPPER('answered') THEN 1
                       ELSE NULL
                  END) AS CNT_ANSWER
         , COUNT (STATUS) AS CNT_TOTAL
    FROM APP_ACCOUNT.CC_CALL
   WHERE CHANNEL = 'DAHDI/i1/'
     AND CALL_TIME BETWEEN TO_DATE('30-DEC-2013')
                       AND TO_DATE('04-JAN-2014')
GROUP BY CALL_TYPE, CHANNEL, TRUNC(CALL_TIME);

The major change I have made is TRUNC(CALL_TIME). Oracle stores dates as datetime values, which have dates as well as time values. Hence, when you use GROUP BY ..., CALL_TIME, ..., what really happens is that the grouping is done for the datetime values, not date values. Only the calls which were made on the exact time accurate to a fraction of a second will be grouped together, which is not the expected behavior. Hence use GROUP BY TRUNC(CALL_DATE) when you have to show the grouping by day.
EDIT:
To get the overall total for each day, you have already used COUNT(STATUS) AS CNT_TOTAL in your query! It would give you the total number of calls if the column is a not null and status is recorded for each call. If this column contains null values, I would suggest you use COUNT(*) AS CNT_TOTAL as it would count all the rows without regards to constraints on columns.
As far as the "for each day" part, TRUNC(datetime) function can truncate datetime values from their year down to their minute. This means, if you want to get the number of calls, or any other statistics, each year then you can simply use TRUNC(call_time, 'YYYY'). On the other hand, if you want call statistics for each hour, you can use TRUNC(call_time, 'HH') or TRUNC(call_time, 'HH24'). Same goes for a minute.
But beware, unless you use a TO_CHAR function to display dates, the front-end dev tools like Toad or SQL Developer display datetime values in the DD-MON-YYYY format, discarding the time information. This is what got you in the first place. Hence, if you group by truncating datetimes to an hour or a minute, and even though the results are correct, you will see repeated date in DD-MON-YYYY format. Hence, don't get confused.
For further reading on TRUNC, I would suggest Oracle Docs AND this link to techonthenet.com. For TO_CHAR, Oracle Docs here has detailed and easy to understand explanation.

A: Try this:
SELECT CALL_TYPE, CHANNEL, TRUNC(CALL_TIME)
      ,COUNT (CASE WHEN UPPER(STATUS) = UPPER('no answer') THEN 1 END) AS CNT_NO_ANSWER
      ,COUNT (CASE WHEN UPPER(STATUS) = UPPER('answered') THEN 1 END) AS CNT_ANSWER
      ,COUNT (STATUS) AS CNT_TOTAL
FROM APP_ACCOUNT.CC_CALL
WHERE CHANNEL = 'DAHDI/i1/'
AND CALL_TIME BETWEEN ('30-DEC-2013') AND ('04-JAN-2014')
GROUP BY CALL_TYPE, CHANNEL, TRUNC(CALL_TIME);

If CALL_TIME contains time value and you want to GROUP BY each date, you should trunc the CALL_TIME to its date.

A: To get the day-wise count you need to group with CALL_TIME. Try like this,
SELECT call_type,
       channel,
       trunc(call_time),
       count (CASE WHEN upper(status) = upper('no answer') THEN 1 ELSE NULL END) AS cnt_no_answer,
       count (CASE WHEN upper(status) = upper('answered') THEN 1 ELSE NULL END) AS cnt_answer
FROM   happ_account.cc_call
WHERE  channel = 'DAHDI/i1/'
AND    call_time BETWEEN to_date('30-DEC-2013', 'DD-MON-YYYY') AND to_date('04-JAN-2014', 'DD-MON-YYYY')
GROUP BY call_type, channel, trunc(call_time);


text:
Q: Using ZIPFoundation, how to add a file to an archive at desired path? I'm trying to add a file to an archive in Swift using the ZIPFoundation lib.
The archive looks like this:
/
/folder1/
/folder2/ <-- Move file here.

Currently using this to add my file to the archive, but I don't get the logic of the parameters:
public func addEntry(with path: String, relativeTo baseURL: URL)

Creating an Archive object and adding the file using addEntry(), is there a way to not just add the file to the root path of the archive?
Code Edit:
internal func moveLicense(from licenseUrl: URL, to publicationUrl: URL) throws {
    guard let archive = Archive(url: publicationUrl, accessMode: .update) else  {
        return
    }
    // Create local folder to have the same path as in the archive.
    let fileManager = FileManager.default
    var urlMetaInf = licenseUrl.deletingLastPathComponent()

    urlMetaInf.appendPathComponent("META-INF", isDirectory: true)
    try fileManager.createDirectory(at: urlMetaInf, withIntermediateDirectories: true, attributes: nil)

    let uuu = URL(fileURLWithPath: urlMetaInf.path, isDirectory: true)
    // move license in the meta-inf folder.
    try fileManager.moveItem(at: licenseUrl, to: uuu.appendingPathComponent("license.lcpl"))
    // move dir
    print(uuu.lastPathComponent.appending("/license.lcpl"))
    print(uuu.deletingLastPathComponent())
    do {
    try archive.addEntry(with: uuu.lastPathComponent.appending("license.lcpl"), // Missing '/' before license
                         relativeTo: uuu.deletingLastPathComponent())
    } catch {
        print(error)
    }
}
// This is still testing code, don't mind the names :)

A: Path entries in ZIP archives are not really hierarchical paths like on most modern file systems.  They are more or less just identifiers. Usually those identifiers are used to store the path that pointed to the entry on the origin file system.
The addEntry(with path: ...) method in ZIPFoundation is just a convenience method for the above use case.
For example, let's say we want to add an entry from a file that has the following path on a physical file system:
/temp/x/fileA.txt

If we want to use a relative path to identify the fileA.txt entry within the archive, we could use:
archive.addEntry(with: "x/fileA.txt", relativeTo: URL(fileURLWithPath: "/temp/")

Later, this would allow us to look up the entry with:
archive["x/fileA.txt"]

If we don't want to keep any path information except the filename, we could use:
let url = URL(fileURLWithPath: "/temp/x/fileA.txt"
archive.addEntry(with: url.lastPathComponent, relativeTo: url.deletingLastPathComponent())

This would allow us to look up the entry just using the filename:
archive["fileA.txt"]

If you need more control over the path/filename, you can use the closure based API in ZIPFoundation. This is especially useful if your entry contents come from memory or you want to add entries from files that don't have a common parent directory.


text:
Q: CreateCriteria, joining associations How can I write the following SQL using CreateCriteria:
SELECT  sa_bec_matricula.*
FROM    sa_bec_matricula
        INNER JOIN sa_matricula ON sa_bec_matricula.sa_mtc_num = sa_matricula.sa_mtc_num
        INNER JOIN sa_periodo ON sa_matricula.sa_per_cod = sa_periodo.sa_per_cod
        INNER JOIN sa_tpo_beca ON sa_bec_matricula.sa_tpo_bec_cod = sa_tpo_beca.sa_tpo_bec_cod
WHERE   sa_periodo.sa_per_abi = 1
        AND sa_tpo_beca.sa_tpo_bec_gpr = 2

Attach the model.
link text

A: It depends on your models and how they are mapped to your tables as Criteria are in terms of properties on objects not tables in schemas.


text:
Q: How to return value as checked check_boxes in active admin? [ruby] I'm currently having a hard time and try to figure it out on how to return array value as checked box in active_admin gem on ruby on edit form.
it successfully edit the value and updated the array which currently using a has many and belongs to table relationship.but everytime it return to the page, the checkboxes return with no checked boxes.
here are the codes.
f.input   :additional_toppings, collection: AdditionalTopping.all.map{|t| [t.name, t.id]},
as: :check_boxes, filter: food.additional_toppings

i did try to use :checked but with no success.
and also i want to know if its possible for the active admin to display read only value some say to use :disabled => true but it didn't work for me.

A: Ok, I found out the answer and it's particularly simple. (Finally for days)
All I gotta do is just remove the collection, as well change the filter into checked.
I also changed the additional_toppings into additional_topping_ids to return the array and I also add the accessible attribute.
Here are the codes:
f.input :additional_toppings, as: :check_boxes, checked: food.additional_topping_ids

attr_accessible :name, :price, :quantity, :picture, :category_id, :info , :favourite, :weekly, :unlimited, :toppings, :tag_list, :additional_topping_ids

has_many :categorizations
has_many :additional_toppings, :through => :categorizations


text:
Q: Magento Connect Manager / 404 Error / Magento 1.9 Path
Admin > System > Magento Connect > Magento Connect Manager
What I have tried.

*

*Searched / read every post I can find on it

*Reset folder and file permissions

*Cleared cache

*Re-indexed everything

*logout / login

I migrated from Debian to Centos 5, not sure what the issue would be.
File Permissions
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod o+w var app/etc
sudo chmod 550 mage
sudo chmod -R o+w media

Url that shows 404 page
http://my-website.com/downloader/?return=http%3A%2F%2F...

Edit:
Magento 404  page - "Whoops, our bad..." page is displayed.
Solved:
I deleted downloader folder and uploaded the one from the previous/debian site and it started working.

A: This method works for me  to fix Magento Connect Manager 404 page not found error:
Change permission of Directory /downloader/ set to 755 and file /downloader/index.php set to 644.

A: you have to change some magento files permissions.
to do that please use this solution of magento-cleanup.php

*

*Download it

*Unzip magento-cleanup.php to the root directory of your magento
installation

*Browse to http://yourdomain.com/magento/magento-cleanup.php

*it's done!

A: Did all the above, but realised I was using Nginx and so it turned out to be not loading the default /downloader/index.php automatically.
Accessing the connect manager directly worked for me: www.example.com/downloader/index.php
Then added some restrictions in nginx conf to restrict to my IP address ore present basic auth login:-
location ~ /downloader/ {
    satisfy all;
    allow 1.2.3.4; #SET TO YOUR IP
    deny all;
    auth_basic "Restricted";
    auth_basic_user_file .htpasswd; #path to your password file, if there is one!
    autoindex off;
}

A: If Page Not found for Magento connect manager
Go and enable your Downloader folder
magento/downloader keep permision 755 in your server (LAMP ot NGINX)


text:
Q: Why is Leaflet Ajax not processing and displaying GeoJSON data? I have been trying for weeks to get Leaflet Ajax to accept data requests from the Land Information New Zealand (LINZ) API without success.
I have a valid key (not included in the snippet) and have tried several tests to load this data in. Other datasets from the LINZ API do not worth either.
What am I doing wrong here?

    <link rel="stylesheet" href="css/style.css">

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
    integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
    crossorigin=""/>

The code snippet results in this output:

Looking through the logged GeoJSON object does not seem to show any successfully parsed data. The error message in Firefox translates roughly to "The configuration of HTML characters hasn't been declared. The document will show 'rubbish' text in some configurations of the browser."
Any ideas would be super helpful!
An example of the response:
{
  "vectorQuery": {
    "layers": {
      "50804": {
        "crs": {
          "type": "name",
          "properties": {
            "name": "EPSG:4326"
          }
        },
        "field_names": ["id", "title_no", "status", "type", "land_district", "issue_date", "guarantee_status", "estate_description", "number_owners", "spatial_extents_shared"],
        "type": "FeatureCollection",
        "features": [{
          "geometry": {
            "type": "MultiPolygon",
            "coordinates": [
              [
                [
                  [175.4776337167, -41.2221699],
                  [175.4782420833, -41.2225527833],
                  [175.4801549333, -41.2237566167],
                  [175.476269, -41.2259343],
                  [175.47357595, -41.22444375],
                  [175.4776337167, -41.2221699]
                ]
              ]
            ]
          },
          "distance": 0,
          "type": "Feature",
          "properties": {
            "id": 1468560,
            "title_no": "WN53B/277",
            "status": "LIVE",
            "type": "Freehold",
            "land_district": "Wellington",
            "issue_date": "1998-04-16 00:00:00",
            "guarantee_status": "Guarantee",
            "estate_description": "Fee Simple, 1/1, Lot 1 Deposited Plan 85426, 110,945 m2",
            "number_owners": 1,
            "spatial_extents_shared": false
          },
          "id": 1191838
        }, {
          "geometry": {
            "type": "MultiPolygon",
            "coordinates": [
              [
                [
                  [175.48005638330002, -41.2282570333],
                  [175.48105425000003, -41.2286012667],
                  [175.4789359, -41.2297867333],
                  [175.47874645, -41.2298923],
                  [175.4767530167, -41.2310074667],
                  [175.47604405, -41.2314040667],
                  [175.47550265, -41.23170695000001],
                  [175.4749415833, -41.2320208833],
                  [175.4745023167, -41.2322666333],
                  [175.474015, -41.2317699833],
                  [175.4735909, -41.23133785000001],
                  [175.4735833, -41.2313303667],
                  [175.4732046667, -41.23094425],
                  [175.4728425667, -41.2305752833],
                  [175.4725057833, -41.2302328833],
                  [175.4722412333, -41.2299625],
                  [175.4719444667, -41.2296600833],
                  [175.4715930333, -41.22930195],
                  [175.47127355, -41.2289763667],
                  [175.4712437333, -41.2289459833],
                  [175.4708617, -41.22855675],
                  [175.4704157833, -41.2281024167],
                  [175.4699766167, -41.227654983300006],
                  [175.4692410167, -41.2269055],
                  [175.4692395833, -41.2269040667],
                  [175.46921793330003, -41.2268834667],
                  [175.4718439333, -41.2254143333],
                  [175.4733724167, -41.2245578167],
                  [175.48005638330002, -41.2282570333]
                ]
              ]
            ]
          },
          "distance": 134,
          "type": "Feature",
          "properties": {
            "id": 2348803,
            "title_no": "WN103/58",
            "status": "LIVE",
            "type": "Freehold",
            "land_district": "Wellington",
            "issue_date": "1899-10-23 00:00:00",
            "guarantee_status": "Guarantee",
            "estate_description": "Fee Simple, 1/1, Lot 75 Deposited Plan 579, 409,390 m2",
            "number_owners": 1,
            "spatial_extents_shared": true
          },
          "id": 5113879
        }, {
          "geometry": {
            "type": "MultiPolygon",
            "coordinates": [
              [
                [
                  [175.48005638330002, -41.2282570333],
                  [175.48105425000003, -41.2286012667],
                  [175.4789359, -41.2297867333],
                  [175.47874645, -41.2298923],
                  [175.4767530167, -41.2310074667],
                  [175.47604405, -41.2314040667],
                  [175.47550265, -41.23170695000001],
                  [175.4749415833, -41.2320208833],
                  [175.4745023167, -41.2322666333],
                  [175.474015, -41.2317699833],
                  [175.4735909, -41.23133785000001],
                  [175.4735833, -41.2313303667],
                  [175.4732046667, -41.23094425],
                  [175.4728425667, -41.2305752833],
                  [175.4725057833, -41.2302328833],
                  [175.4722412333, -41.2299625],
                  [175.4719444667, -41.2296600833],
                  [175.4715930333, -41.22930195],
                  [175.47127355, -41.2289763667],
                  [175.4712437333, -41.2289459833],
                  [175.4708617, -41.22855675],
                  [175.4704157833, -41.2281024167],
                  [175.4699766167, -41.227654983300006],
                  [175.4692410167, -41.2269055],
                  [175.4692395833, -41.2269040667],
                  [175.46921793330003, -41.2268834667],
                  [175.4718439333, -41.2254143333],
                  [175.4733724167, -41.2245578167],
                  [175.48005638330002, -41.2282570333]
                ]
              ]
            ]
          },
          "distance": 134,
          "type": "Feature",
          "properties": {
            "id": 4177014,
            "title_no": "94991",
            "status": "LIVE",
            "type": "Leasehold",
            "land_district": "Wellington",
            "issue_date": "2003-06-10 09:00:00",
            "guarantee_status": "Guarantee",
            "estate_description": "Leasehold, 1/1, Lot 75 Deposited Plan 579, 409,390 m2",
            "number_owners": 1,
            "spatial_extents_shared": true
          },
          "id": 5116291
        }]
      }
    }
  }
}

A: The Leaflet-ajax plugin expects directly a GeoJSON compliant object in the loaded data, whereas in the sample response you show, the structure of the response is:
{
  "vectorQuery": {
    "layers": {
      [layerId]: {
        // GeoJSON FeatureCollection
      }
    }
  }
}

Therefore you have to convert this data into a GeoJSON object first. Here in this case it looks quite simple, as you just have to extract the FeatureCollection. You can use leaflet-ajax middleware option to perform this conversion between the reception of the data and before it is processed to be transformed into Leaflet layers:
new L.GeoJSON.AJAX("url", {
  middleware(rawData) {
    // Extract the GeoJSON FeatureCollection
    const layerId = 50804;
    return rawData.vectorQuery.layers[layerId];
  }
});