text:
Q: Css3 is not woking in firefox and ie.it is working in google chrome i have align section tag to left and aside tag to right in css3.it is
working in google chrome. but it is not working in firefox and
internet explorer.can someone tell why is not working.
here html5 code
<!DOCTYPE html >

<meta charset="urf-8" />
<title>Bruno Website </title>
<link rel="stylesheet" href="main.css" >

 Welcome to HTML5

Home

Services

Tutorials

Conatct

                <hgroup>

Tiltle of the article

titile h2

                </hgroup>

This is my First Website in hTml5

~BRuno thileeban

                <hgroup>

Tiltle of the article2

titile h2 2

                </hgroup>

This is my First Website in hTml5 2

~BRuno thileeban

News

            HEllo we r doing good job

    Copyright Bruno .....

Here is the css3 code
*
{
margin:0px;
padding:0px;
}
h1
{
 font: bold 20px Tahoma;
}
h2
{
font: bold 14px Tahoma;
}
header, section, footer, aside, nav, article, hgroup{ display:block;}
body
{
 width:100%;
 display:-webkit-box;
 -webkit-box-pack: center;
}
#big_wrapper{
 max-width: 1000px;
 margin:20px 0px;
 display:-webkit-box;
-webkit-box-orient: vertical;
-webkit-box-flex:1;
}
#top_header { background:yellow;
border:3px solid black;
padding:20px;
}
#top_menu{ border:red;
background:blue;
color:white;
}
#top_menu li {
display:inline-block;
list-style:none;
padding:5px;
font:bold 14px tahoma;
 }
 #new_div{
  display:-webkit-box;
  -webkit-box-orient:horizontal;
  }
  #main_section
  {
  border:1px solid blue;
  -webkit-box-flex:1;
  margin:20px ;
  padding:20px;

  }

  #side_news{
    border:1px solid red;
    margin:20px 0px;
    padding:30px;
    background: #66CCCC;

  }
  #the_footer{
  text-align:center;

   padding:20px;
   border-top:2px solid green;
  }
  article{ background:#FFFBCC; border:1px solid red; padding:20px; margin-bottom:15px;}
  article footer{ text-align:right;}

A: You've chosen to only support webkit (upon which Google Chrome is based) in your code. To support rendering engines used by other browsers you need to make some changes.
Everywhere you use -webkit-*, copy that line and below use -moz-*, again with -o-* and -ms-*, and then one more time without any prefix. The web browser will drop the ones it doesn't understand.
For example, -webkit-box-flex:1; becomes
-webkit-box-flex:1; /* chrome, safari, etc */
-moz-box-flex:1;    /* Firefox, seamonkey etc */
-o-box-flex:1;      /* Opera */
-ms-box-flex:1;     /* MSIE */
box-flex:1;         /* Any that support full implementation */

However, it should be noted that this is a property of the original CSS Flexible Box Layout Module standard which is being replaced by a new standard. You may be interested in using flex instead

A: You have used several -webkit prefixes in your CSS (Example: -webkit-box-orient: vertical;).  These specifications only work in some browsers, notably Chrome.
Standard CSS prefixes like float would be a better option.
PS - There's no such charset as urf-8.

A: You seem only to have used -webkit prefixes, which are specific to webkit based browsers such as safari and chrome, either use the other prefixes (-moz, -o), or use Compass, which is  very useful for maintaining prefixes, as the code always reflects the latest browser support.

A: Vendor prefixes, by definition, are only supposed to work in a single vendor's browser as they indicate custom rules or experimental implementations of things which are not yet standardized (although there has been some controversy over that).
The -webkit- bit is a vendor prefix which will only apply to browsers which use the WebKit rendering engine, the most popular of which are Chrome and Safari.  Here is a list of known vendor prefixes for other rendering engines.  So if you take this rule:
body {
    width:100%;
    display: -webkit-box;
    -webkit-box-pack: center;
}

What you have is not really CSS3, but WebKit custom CSS.  CSS3, if the rules and properties you're using get approved would look like this (do not use this code):
body {
    width: 100%;
    display: box;
    box-pack: center;
}

This rule will not work in browsers until the standard for box and box-pack is agreed and finalised, to get maximum current support your rule would have to look like this (again, do not use this code):
body {
    width:100%;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-box;
    display: -o-box;
    display: box;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-box-pack: center;
    -o-box-pack: center;
    box-pack: center;
}

This complexity is why people use tools like Compass to generate their stylesheets.
However, I've been saying all along that you should not use this code and the reason for that is there are no longer any plans to have box and box-pack in CSS3.  They have been superseded by a new approach using the flex keyword.  Although flex replaces box they do not work in quite the same way so it is not a direct translation.  Support for vendor prefixed box attributes will either fade out or return to being custom CSS (the entire box approach started off as custom CSS that Firefox used to layout UI elements in the browser toolbars, ie. not for web pages at all).
This is the risk you run by using vendor prefixed CSS rules - the behaviour and even the syntax is liable to change.  If you intend to use them you must stay on top of the spec as well as carefully monitor the progress of experimental implementations in browsers.


text:
Q: columnDefs is not working for disabling the searching for some columns? I want to disable search for some columns in jquery datatables but when I used columndefs  it returns errors and the search input field remove.

A:

$(document).ready( function () {
  var table = $('#example').DataTable({
  "searching": false
});
} );
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>

DataTables - JS Bin
<!DOCTYPE html>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

            Name
            Position
            Office
            Age
            Start date
            Salary

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $3,120

            Garrett Winters
            Director
            Edinburgh
            63
            2011/07/25
            $5,300

            Ashton Cox
            Technical Author
            San Francisco
            66
            2009/01/12
            $4,800

            Cedric Kelly
            Javascript Developer
            Edinburgh
            22
            2012/03/29
            $3,600

            Jenna Elliott
            Financial Controller
            Edinburgh
            33
            2008/11/28
            $5,300

            Brielle Williamson
            Integration Specialist
            New York
            61
            2012/12/02
            $4,525

            Herrod Chandler
            Sales Assistant
            San Francisco
            59
            2012/08/06
            $4,080

            Rhona Davidson
            Integration Specialist
            Edinburgh
            55
            2010/10/14
            $6,730

            Colleen Hurst
            Javascript Developer
            San Francisco
            39
            2009/09/15
            $5,000

            Sonya Frost
            Software Engineer
            Edinburgh
            23
            2008/12/13
            $3,600

            Jena Gaines
            System Architect
            London
            30
            2008/12/19
            $5,000

            Quinn Flynn
            Financial Controller
            Edinburgh
            22
            2013/03/03
            $4,200

            Charde Marshall
            Regional Director
            San Francisco
            36
            2008/10/16
            $5,300

            Haley Kennedy
            Senior Marketing Designer
            London
            43
            2012/12/18
            $4,800

            Tatyana Fitzpatrick
            Regional Director
            London
            19
            2010/03/17
            $2,875

            Michael Silva
            Senior Marketing Designer
            London
            66
            2012/11/27
            $3,750

            Paul Byrd
            Javascript Developer
            New York
            64
            2010/06/09
            $5,000

            Gloria Little
            Systems Administrator
            New York
            59
            2009/04/10
            $3,120

            Bradley Greer
            Software Engineer
            London
            41
            2012/10/13
            $3,120

            Dai Rios
            System Architect
            Edinburgh
            35
            2012/09/26
            $4,200

            Jenette Caldwell
            Financial Controller
            New York
            30
            2011/09/03
            $4,965

            Yuri Berry
            System Architect
            New York
            40
            2009/06/25
            $3,600

            Caesar Vance
            Technical Author
            New York
            21
            2011/12/12
            $4,965

            Doris Wilder
            Sales Assistant
            Edinburgh
            23
            2010/09/20
            $4,965

            Angelica Ramos
            System Architect
            London
            36
            2009/10/09
            $2,875

            Gavin Joyce
            Developer
            Edinburgh
            42
            2010/12/22
            $4,525

            Jennifer Chang
            Regional Director
            London
            28
            2010/11/14
            $4,080

            Brenden Wagner
            Software Engineer
            San Francisco
            18
            2011/06/07
            $3,750

            Ebony Grimes
            Software Engineer
            San Francisco
            48
            2010/03/11
            $2,875

            Russell Chavez
            Director
            Edinburgh
            20
            2011/08/14
            $3,600

            Michelle House
            Integration Specialist
            Edinburgh
            37
            2011/06/02
            $3,750

            Suki Burks
            Developer
            London
            53
            2009/10/22
            $2,875

            Prescott Bartlett
            Technical Author
            London
            27
            2011/05/07
            $6,730

            Gavin Cortez
            Technical Author
            San Francisco
            22
            2008/10/26
            $6,730

            Martena Mccray
            Integration Specialist
            Edinburgh
            46
            2011/03/09
            $4,080

            Unity Butler
            Senior Marketing Designer
            San Francisco
            47
            2009/12/09
            $3,750

            Howard Hatfield
            Financial Controller
            San Francisco
            51
            2008/12/16
            $4,080

            Hope Fuentes
            Financial Controller
            San Francisco
            41
            2010/02/12
            $4,200

            Vivian Harrell
            System Architect
            San Francisco
            62
            2009/02/14
            $4,965

            Timothy Mooney
            Financial Controller
            London
            37
            2008/12/11
            $4,200

            Jackson Bradshaw
            Director
            New York
            65
            2008/09/26
            $5,000

            Miriam Weiss
            Support Engineer
            Edinburgh
            64
            2011/02/03
            $4,965

            Bruno Nash
            Software Engineer
            London
            38
            2011/05/03
            $4,200

            Odessa Jackson
            Support Engineer
            Edinburgh
            37
            2009/08/19
            $3,600

            Thor Walton
            Developer
            New York
            61
            2013/08/11
            $3,600

            Finn Camacho
            Support Engineer
            San Francisco
            47
            2009/07/07
            $4,800

            Elton Baldwin
            Data Coordinator
            Edinburgh
            64
            2012/04/09
            $6,730

            Zenaida Frank
            Software Engineer
            New York
            63
            2010/01/04
            $4,800

            Zorita Serrano
            Software Engineer
            San Francisco
            56
            2012/06/01
            $5,300

            Jennifer Acosta
            Javascript Developer
            Edinburgh
            43
            2013/02/01
            $2,875

            Cara Stevens
            Sales Assistant
            New York
            46
            2011/12/06
            $4,800

            Hermione Butler
            Director
            London
            47
            2011/03/21
            $4,080

            Lael Greer
            Systems Administrator
            London
            21
            2009/02/27
            $3,120

            Jonas Alexander
            Developer
            San Francisco
            30
            2010/07/14
            $5,300

            Shad Decker
            Regional Director
            Edinburgh
            51
            2008/11/13
            $5,300

            Michael Bruce
            Javascript Developer
            Edinburgh
            29
            2011/06/27
            $4,080

            Donna Snider
            System Architect
            New York
            27
            2011/01/25
            $3,120

for more detail check jquery-datatable API
Jquery DataTable API
"searching": false setting the bool value does the magic
deafult is true

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I extract information using regex Using the following code in a powershell script to pull data from a .txt file and not getting desired results using regex:
$PSRoot      = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

$csvContents = @()

Get-Content C:\PROJECTS\Reports\NodeReports\NU_001_20200620.txt |
?{$_ -imatch 'Client Name' -or $_ -imatch 'Windows Ver:'} | %{

if($_ -imatch 'Client Name'){
           $Name = ([regex]::Matches($_,'\b\d+') | select value).value -join ','

           }

if($_ -imatch 'Windows Ver:'){
           $WinVer = ([regex]::Matches($_,'\b\d+') | select value).value -join ','

           }
    $obj = [PSCustomObject]@{
        POSType        = $Name
        WindowsVersion = $WinVer

        }

        $csvContents += $obj

    }
 $csvContents | ConvertTo-Csv -NoTypeInformation  | Set-Content -path "$PSRoot\NodeReportStatus.csv" -force

Example of output:

No info is being pulled for POSType (Client Name)  and WindowsVersion (Windows Ver:) should just be pulling 6.1
Portion of .txt file:
Node 001 Status Report - Report Version 20200505;
Generated 2020-06-20 00:50:56;
=====================================================================;
DEV001 Windows Ver: 6.1, SerialLink Ver: 1464.056, CPU Type: NT;
DEV001 Name: 2723998POS1, ActiveName: 2723998POS1
DEV001 Time Setup: 06/20/2020   00:50:55   GMT +05:00,YES,35,Eastern Standard Time;
DEV001 Uptime: 9 days, 2 hours, 27 mins, 12.69 secs
---------------------------------------------------------------------;
DEV001 GetInfo: Client Name      P1530;

A: You may try:
DEV\d+ Windows Ver: (\d+)\.(\d+), SerialLink Ver: (\d+)\.(\d+)

Sample Powershell Commands:(You can modify your code according to your further requirement)
PS C:\Path\To\MyDesktop> $input_path='C:\Path\To\MyDesktop\test.txt'
PS C:\Path\To\MyDesktop> $output_path='C:\Path\To\MyDesktop\testResult.txt'
PS C:\Path\To\MyDesktop> $regex='DEV\d+ Windows Ver: (\d+)\.(\d+), SerialLink Ver: (\d+)\.(\d+)'
PS C:\Path\To\MyDesktop> select-string -Path $input_path -Pattern $regex -AllMatches | % { "$($_.matches.groups[1]), $($_.matches.groups[2]), $($_.matches.groups[3]), $($_.matches.groups[4])" } > $output_path

Sample Output:

A: Since you could have multiple Node Status Reports within one file, I'd use a switch statement to do regex matching and custom object creation.
$csvcontents = switch -regex -file C:\PROJECTS\Reports\NodeReports\NU_001_20200620.txt {
    'Windows Ver: ([\d\.]+)' {
        $Version = $matches.1
    }
    'Client Name\s*(.*);' {
        $Client = $matches.1
        [pscustomobject]@{POSType = $Client; WindowsVersion = $Version }
    }
}

Using switch with regex, each matching string is stored in the automatic $matches variable. Since we are only using one set of parentheses per match for the target string, that becomes unnamed capture group 1. Capture group 1 can be accessed using $matches.1.


text:
Q: HTTP BODY in memory rather than writing to disk Is it possible to have the body of an HTTP request stored in memory as a stream of data.
Specifically, I am using the libcurl C library to write a few HTTP requests and the idea is to have the body of the HTTP responses in memory rather than writing to disk.
The various curl_easy_setopt options (CURLOPT_WRITEFUNCTION, CURLOPT_WRITEDATA) actually write the body of the response to a file. What I want is to be able to work on the data stream that is in the body directly, irrespective of what it is.
Something to the tune of:
char* dataStream = HTTP_RESPONSE_BODY

This is because the HTTP body will be passed on to something else for further processing and writing to disk and reading back will take time, particularly for large files. I know I may not have sufficient memory to hold large data but it is definitely going to be faster than writing to disk and reading again.

A: You can tell cURL to pass data to a function defined by your own by making it matching the prototype: size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp); and call: curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);
This is mentioned in the official libcurl tutorial at: http://curl.haxx.se/libcurl/c/libcurl-tutorial.html


text:
Q: Send multiple Fluxes with different types in one response If I have code like so:
data class Response(
  val a: String,
  val b: List<String>,
  val c: Int,
)

fun buildResponse(): Response {
  val a: Mono<String> = getA()
  val b: Flux<String> = getB()
  val c: Mono<Int> = getC()

  return Response(
    a = a.blockOptional().orElseThrow(),
    b = b.collectList().blockOptional().orElseThrow(),
    c = c.blockOptional().orElseThrow(),
  )
}

Is there a way to reactively return a Mono<Response> instead of blocking and returning the actual Response?

A: Sure - have a look at the Mono.zip operator, which will allow you to combine several publishers into a single Mono. The basic Mono.zip variants just return a tuple, but you can also specify your own class (Response in this case) as so:
return Mono.zip(
        Function { eles: Array<Any> ->
            Response(eles[0] as String,
                    eles[1] as List<String>,
                    eles[2] as Int)
        },
        a, b.collectList(), c)


text:
Q: Pandas Drop rows for current Year-month My dataframe has multiple years and months in "yyyy-mm-dd" format.
I would like to dynamically drop all current Year-month rows from the df

A: you could use a simple strftime method where the %Y%m is not equal to the year month of the current date.
df1 = df.loc[
 df['Date'].dt.strftime('%Y%m') != pd.Timestamp('today').strftime('%Y%m')]

Example
d = pd.date_range('01 oct 2021', '01 dec 2021',freq='d')
df = pd.DataFrame(d,columns=['Date'])

print(df)
         Date
0  2021-10-01
1  2021-10-02
2  2021-10-03
3  2021-10-04
4  2021-10-05
..        ...
57 2021-11-27
58 2021-11-28
59 2021-11-29
60 2021-11-30
61 2021-12-01

print(df1)

         Date
0  2021-10-01
1  2021-10-02
2  2021-10-03
3  2021-10-04
4  2021-10-05
5  2021-10-06
6  2021-10-07
7  2021-10-08
8  2021-10-09
9  2021-10-10
10 2021-10-11
11 2021-10-12
12 2021-10-13
13 2021-10-14
14 2021-10-15
15 2021-10-16
16 2021-10-17
17 2021-10-18
18 2021-10-19
19 2021-10-20
20 2021-10-21
21 2021-10-22
22 2021-10-23
23 2021-10-24
24 2021-10-25
25 2021-10-26
26 2021-10-27
27 2021-10-28
28 2021-10-29
29 2021-10-30
30 2021-10-31
61 2021-12-01


text:
Q: How to manipulate iOS contacts with SwiftAddressBook? I'm trying to get all the users contacts and see if they are already singed up in the backend. I'm trying first to get all the contacts using SwiftAddressBook and then I want to edit all the phone numbers and add country code to phone number.
I made this function but it doesn't work, it's only showing phone numbers.
 SwiftAddressBook.requestAccessWithCompletion({ (success, error) -> Void in
            if success {
                if let people = swiftAddressBook?.allPeople {
                    for person in people {
                        var phonenumber = String (person.phoneNumbers?.map({$0.value}))
                          print(phonenumber.characters.last)
                        if phonenumber.characters.first == "0" {
                           phonenumber = phonenumber.stringByReplacingCharactersInRange(phonenumber.startIndex..<phonenumber.startIndex.successor(), withString: "+33")
                        }

                        print(phonenumber)
                    }
                }
            }
            else {
              print("Fail")
            }
        })

A: Well, in first, you should call swiftAddressBook.save() to save the current state of the address book. In second, you are changing a local string variable, which will not affect the address book state. It appears SwiftAddressBook will only make changes to the contacts if you change phoneNumbers array. This should work:
SwiftAddressBook.requestAccessWithCompletion({ (success, error) -> Void in
        if success {
            if let people = swiftAddressBook?.allPeople {
                for person in people {
                    if let phoneNumbers = person.phoneNumbers {
                        var phoneNumbersChanged = false
                        var newPhoneNumbers = [MultivalueEntry<String>]()

                        for var phonenumber in phoneNumbers {
                            if phonenumber.value.characters.first == "0" {
                                phonenumber.value = phonenumber.value.stringByReplacingCharactersInRange(phonenumber.value.startIndex..<phonenumber.value.startIndex.successor(), withString: "+33")
                                newPhoneNumbers.append(MultivalueEntry(value: phonenumber.value, label: phonenumber.label, id: phonenumber.id))
                                phoneNumbersChanged = true
                            } else {
                                newPhoneNumbers.append(phonenumber)
                            }

                            print(phonenumber.value)
                        }

                        if phoneNumbersChanged {
                            person.phoneNumbers = newPhoneNumbers
                        }
                    }
                }
                swiftAddressBook.save()
            }
        }
        else {
            print("Fail")
        }
    })


text:
Q: Convert data frame into String using scala and save the ouput to a csv I want to append rows in a single string
+--------------------+
|   defectDescription|
+--------------------+
|ACEView NA : Daework|
|ACEView NA : Documen|
|ACEView NA : ACev   |
|ACEView NA : Dragdro|
+--------------------+

Expected Output:
ACEView NA : Daework ACEView NA : Documen ACEView NA : ACev ACEView NA : Dragdro

A: If you indeed want to get all the data into a single string you can do it using collect:
val rows = df.select("defectDescription").collect().map(_.getString(0)).mkString(" ")

You first select the relevant column (so you have just it) and collect it, it would give you an array of rows. the map turns each row to the string (there is just one column - 0). Then mkString would make an overall string of them with a space as the separator.
Note that this would bring the entire dataframe to the driver which might cause memory exceptions. If you need just some of the data you can use take(n) instead of collect to limit the number of rows to n.

A: val str1 = df.select("defectDescription").collect.mkString(",")
val str =  str1.replaceAll("[\\[\\]]","")

Another way to do this is as follows:
The 1st line selects the particular columns then collects the subset, collects behaves as:
Collect (Action) - Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
mkString - mkString method has an overloaded method which allows you to provide a delimiter to separate each element in the collection.
The 2nd line just replaces the additional brackets

A: df.createTempView(viewName="table")
val res=spark.sqlContext.sql(sqlText="select defectDescription from table").collectAsList.toString.replace("[", "").replace("]", "")

Initially create a temporary view of the dataframe, then convert into a list, and then string- Finally remove the brackets as per the required output.

A: Let's leverage parallel computing by not prematurely collecting the data while there is associative processing to be done:
def str(r: Row) = r.getString(0)
def cat(r0: Row, r1: Row) = Row(s"${str(r0)} ${str(r1)}")

str(df.select("defectDescription").reduce(cat))

This allows parallel concatenations to be done on all executors before concatenating their results in the driver.


text:
Q: Quantum Mechanical Meaning of Atomic Orbitals According to quantum mechanics, for multi-electron atoms, a single electron around the nuclei can be in the state of linear combination of different eigen energy states. In that case, even the energy of the electron is not one of the eigen energies.
In chemistry, we often say that an electron is in an orbital (such as 1s, 2s), another electron is in another orbital, etc. How does it make sense if an electron is in a linear combination state?

A: While it's possible for the atom to be in a superposition on energy states, the superposition collapses to an eigenstate as soon as we observe it. Therefore every atom we observe will have a distinct electronic configuration.
Incidentally, note that for a multi electron atom the assignment of electrons to the atomic orbitals 1s, 2s, etc, is an approximation. The electron correlation mixes up the atomic orbitals so strictly speaking we don't have separate atomic orbitals, just a single wavefunction for the atom. However, in most cases using atomic orbitals is an excellent approximation.

A: As John Rennie points out, the picture of an electron in an orbital breaks down in multielectron atoms because of electron correlations. However, you can still assign a "fraction" of an electron to an orbital by diagonalizing the reduced one-particle density matrix (1RDM) of the system. This matrix is Hermitian, positive semi-definite, has eigenvalues $n_i \leq 1$, and describes the total electronic density of the system as
\begin{equation}
\rho (r) = \sum \limits_i n_i \psi_i^*(r) \psi_i(r)
\end{equation}
where $\psi_i (r)$ are the orbitals. Thus, $n_i$ is the "occupation number" of orbital $\psi_i$ and describes how much on average an electron is in that orbital.
Now, with respect to your question:
"In chemistry, we often say that an electron is in an orbital (such as 1s, 2s), another electron is in another orbital, etc. How does it make sense if an electron is in a linear combination state?" Well, it makes sense because often we find that there are $N_e$ (number of electrons) eigenvalues $n_i$ which are very close to one, while the rest of the eigenvalues are very small. The reason for this is that the exact wavefunction is an infinite sum of Slater determinants (i.e., an antisymetric function which describes one electron configuration) considering all possible configurations. However, because of the variational principle, configurations which are very high in energy contribute very little to the wavefunction and hence have small weights $n_i$.
There are cases in which the eigenvalues of the 1RDM differ significantly from one or zero. This occurs if there are different possible configurations that are similar in energy. For example, in transition metals, configurations involving 4s or 3d orbitals are very close in energy. This is the reason for which the configurations predicted by the aufbau principle break down for these elements.


text:
Q: Renaming and versioning image uploads in php So I have an image upload page in my forum. If an image already exists, the old version is renamed to file.ext,timestamp (instead of being overwritten). I want the old, renamed version to have the correct extension (.jpg) so my gallery script can recognize old versions of the picture.
I think this the critical code:
if (IsEnabled($EnableUploadVersions, 0))
  @rename($filepath, "$filepath,$Now");

How can i change this for my purpose?
Thank you for help. :)
     UploadAuth($pagename, $auth);
  $uploadfile = $_FILES['uploadfile'];
  $upname = @$_REQUEST['upname'];
  if ($upname=='') $upname=$uploadfile['name'];
  $upname = MakeUploadName($pagename,$upname);
  if (!function_exists($UploadVerifyFunction))
    Abort('?no UploadVerifyFunction available');
  $filepath = FmtPageName("$UploadFileFmt/$upname",$pagename);
  $result = $UploadVerifyFunction($pagename,$uploadfile,$filepath);
  if ($result=='') {
    $filedir = preg_replace('#/[^/]*$#','',$filepath);
    mkdirp($filedir);
    if (IsEnabled($EnableUploadVersions, 0))
      @rename($filepath, "$filepath,$Now");
    if (!move_uploaded_file($uploadfile['tmp_name'],$filepath))
      { Abort("?cannot move uploaded file to $filepath"); return; }
    fixperms($filepath, $UploadPermAdd, $UploadPermSet);
    if ($LastModFile) { touch($LastModFile); fixperms($LastModFile); }
    $result = "upresult=success";
    $FmtV['$upname'] = $upname;
    $FmtV['$upsize'] = $uploadfile['size'];
    if (IsEnabled($RecentUploadsFmt, 0)) {
      PostRecentChanges($pagename, '', '', $RecentUploadsFmt);
    }
    if (IsEnabled($NotifyItemUploadFmt, 0) && function_exists('NotifyUpdate')) {
      $NotifyItemFmt = $NotifyItemUploadFmt;
      $IsUploadPosted = 1;
      register_shutdown_function('NotifyUpdate', $pagename, getcwd());
    }


text:
Q: Drawing multiple layers over wpf map control I have the grid with wpf map control and canvas over it for drawing markers over map.
    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <UserControl Grid.Row="0" Content="{Binding CurrentMap}" />
    <UserControl Grid.Row="0" Content="{Binding DrawningCanvas}" />
</Grid>

Now I needed to use more than 1 layer over the map.
What wpf control I should use for binding to ObservableCollection<Canvas> in DataContext and draw them all over each other?

A: You seem to be somewhat confused. An ObservableCollection is a collection for data items. A Canvas is a UI control. Therefore, you should never have a data item collection with UI elements in.
Instead, you could have a Marker data class that contains X and Y properties for the marker's positions and maybe Name and ImageSource properties to define what it would look like in the UI. Then you could have a ObservableCollection of type Marker named Markers that you could bind to the ItemsSource property of an ItemsControl. Finally, you could set a Canvas as the ItemsPanel of the ItemsControl:
<ItemsControl ItemsSource="{Binding Markers}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Top" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type YourXmlNamespacePrefix:Marker}">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding ImageSource}" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

I don't really know why you would want to have multiple layers because you could overlay multiple items on the same layer, but if you really need multiple layers, then you can just add more of the ItemsControl elements shown above.


text:
Q: Ubuntu 19.10 not booting on Threadripper but 18.04 will So my new system (Threadripper 3970x on Gigabyte TRX40 AORUS MASTER) doesn't boot on Ubuntu 19.10 - it gets stuck at recognizing USB devices:
7-6 New USB device found, idVendor=05e3, idProduct=0608
7-6 New USB device strings: Mfr=0, Product=1, Serialnumber.....
7-6 Product: USB2.0 Hub
7-6:1.0: USB hub found
7-6:1.0: 4 ports detected

..then nothing happens. This is the same on booting from USB stick, normal boot and recovery mode.
I tried removing USB devices, but this hub seems to be on the motherboard. What can I do? Since I can't even enter recovery mode it seems a bit tricky to troubleshoot. Can I disable specific USB ports through GRUB maybe? Or is the listed USB entry not even the problem?

A: You need to add an mce=off line to your kernel parameters if you wish you use kernel version 5.39 - the default kernel for Ubuntu 19.10.
See:  https://www.phoronix.com/scan.php?page=news_item&px=Linux-Boot-Threadripper-Zen2MCE
I edited my grub config by booting into Ubuntu with the 4.15 Kernel as found in my grub menu and then using grub-customizer to add the parameter.


text:
Q: Can a 2d array be created without static initializers? I want to have an object that takes a course that a student has completed, but the student can take a course 3 times if they did not pass on their first attempt, basically an array of arrays, for example:
["F", "A", " "]//This means that the student took the course twice because they failed on the first attempt and because they passed on their second, the third string remains null

This is how I initialized the "CompletedCourses" variable in the Student class
public string[,,] CompletedCourses

And this is the constructor
public Student(string StudentID, string Name, string Status, Enum StudentMajor, string[,,] CompletedCourses)
    {
        this.StudentID = StudentID;
        this.Name = Name;
        this.Status = Status;
        this.StudentMajor = StudentMajor;
        this.CompletedCourses = CompletedCourses;
    }

This is what the object is supposed to achieve.
Student student = new("00069110", "Erling Haaland", "Full-time", Majors.Computer_Information_Systems, new string[,,]//These are the courses completed and grade(s) achieved in them.
{
    {{"CS50"},{"F", "B+", " "}},
    {{"Psychology 101"}, {"A", " ", " "} }//This is my idea of storing the courses a student has completed and the grade(s) they received in the courses.
});

The code above, I don't believe is the correct syntax for a multi-dimensional array, but I think it can be a guide to what the expected outcome is.

A: The immediate reason your code doesn't work is because multidimensional arrays in C# require that all dimensions have the same length. You can't have both a length 1 array {"CS50"} and a length 3 array {"F", "B+", " "} in the same dimension. It has nothing to do with static initialisers, really.
Since you just want a collection of courses and their grades, you can create types to model those things:
enum Grade {
    NotTaken, // could also be modelled with null instead, if you use Grade?
    Fail,
    A,
    B,
    C,
    D,
    E
}

record CompletedCourse(string name, Grade[] grades);

Then the constructor of Student could take a List<CompletedCourse>. Example usage:
Console.WriteLine(new Student( // omitting other arguments of the Student constructor
    new() {
        new("CS50", new[] { Grade.Fail, Grade.B, Grade.NotTaken }),
        new("Psychology 101", new[] { Grade.A, Grade.NotTaken, Grade.NotTaken }),
    }
));

Alternatively, if you want to easily search a course's grades by the course name, you can use a Dictionary<string, Grade[]> instead, in which case the inline initialisation would look like this:
Console.WriteLine(new Student(
    new() {
        { "CS50", new[] { Grade.Fail, Grade.B, Grade.NotTaken } },
        { "Psychology 101", new[] { Grade.A, Grade.NotTaken, Grade.NotTaken } },
    }
));


text:
Q: XFS filesystem different amount of free space, if mounted RW vs RO I have big disk (14 TB), and fill it with big files (~100GB each), so I use XFS filesystem. After disk is full (52G free) - I remount partition as read-only, to protect files. And there is 143G of free space, so one more file would fit. Yet, when I remount partition as RW to put one extra file - there are not enough free space again (52G free).
How could I use extra ~100 GB to fit one more file to disk? For this partition I will have only ~130 files, ~100GB each, and disk is ok to be read-only after it's full.
root@linux:/etc# df -h /mnt/disk3
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdd1        13T   13T   52G 100% /mnt/disk3

root@linux:/etc# mount -o remount,ro /dev/sdd1 /mnt/disk3
root@linux:/etc# df -h /mnt/disk3
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdd1        13T   13T  143G  99% /mnt/disk3

root@linux:/etc# mount -o remount,rw /dev/sdd1 /mnt/disk3
root@linux:/etc# df -h /mnt/disk3
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdd1        13T   13T   52G 100% /mnt/disk3


text:
Q: Continue Shopping redirect to previous category in woocommerce I am creating an e-commerce website using Woocommerce and I need some help with a redirect. So the layout is images of Category 1 Category 2 etc.
When Category 1 is clicked on, it opens  category 1a category 1b etc when category 1a is clicked, it opens up list of products.
If user is on page 3 of of category 1a and clicks on product. it goes to single product page and when they click add to cart. It now goes to the cart page and offers an option to continue shopping. When the user clicks continue shopping, I want it to go back to category1a page 3 or if easier , the specific category the user was in.
With the code below, I managed to redirect it to the main shop page but the client is requesting to go to where the user was prior to clicking on product.
add_filter( 'woocommerce_add_to_cart_message', 'woocommrece_custom_add_to_cart_message' );

function woocommrece_custom_add_to_cart_message() {
global $woocommerce;

// Output success messages
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {

    $return_to = get_permalink( woocommerce_get_page_id( 'shop' ) ); // Give the url, you want to redirect which would be previous location before user clicked on product
    $message   = sprintf( '%s %s', $return_to, __( 'More Donation Options →', 'woocommerce' ), __( 'Donation successfully added to your cart.', 'woocommerce' ) );
} else {

    $message = sprintf( '%s %s', get_permalink( woocommerce_get_page_id( 'cart' ) ), __( 'View Cart →', 'woocommerce' ), __( 'added to cart.', 'woocommerce' ) );

}

A: This will work for primary category... add to functions.php
add_filter( 'wc_add_to_cart_message', 'custom_add_to_cart_message', 10, 2 );
function custom_add_to_cart_message( $message, $product_id) {
    $terms = get_the_terms( $product_id, 'product_cat' );
    $return_to = get_term_link( $terms[0], 'product_cat');
    $message    = sprintf( '%s %s', $return_to, __( 'Continue Shopping?', 'woocommerce' ), __( 'Your cart was updated.', 'woocommerce' )  );
return $message;
}


text:
Q: SCP version of - ssh -A -t -l root 192.16.4.9 ssh -A -t node-17 I'm on a vpn. I ssh to a machine through another machine like so
ssh -A -t -l bob 192.16.4.9 ssh -A -t node-17
I now need to scp a file from node-17:/tmp/something.
How can I do the above in one step? There is no space left on the other nodes to move it to first. I should add that public keys are used to authenticate between 192.168.4.9 and node-17
Thanks

A: I'm not sure about the -t options, but what I think you want is
ssh -At -o 'ProxyCommand ssh -At -l bob 192.16.4.9' node-17

Then the same method works with scp, e.g.
scp -o 'ProxyCommand ssh -At -l bob 192.16.4.9' file node-17:file

To make this connection configuration permanent so you don't have to reenter it every time, put the following into your ~/.ssh/config:
Host node-17
ProxyCommand ssh -At -l bob 192.16.4.9

Then all you'll need to run is ssh -At node-17 or scp file node-17:file.

A: Instead of SCP you could just cat the file on the remote machine and save the output locally.
ssh -A -t -l bob 192.16.4.9 ssh -A -t node-17 cat /tmp/something > /local/copy/of/something

You can also use this in the other direction to upload a file to the remote machine, but with an extra hop it requires some creative quoting on the command line:
ssh -A -t -l bob 192.16.4.9 'ssh -A -t node-17 "cat > /tmp/new-file"' < /local/copy/of/new-file


text:
Q: Does Oracle Spatial calculate geodetic distance? I've got to migrate a PostGIS database to Oracle Spatial, and am stuck on a problem:
In a view, I have a column that amounts to ST_Distance(geography(geom_1), geography(geom_2)), effectively calculating geodetic distance in meters.
In Oracle, calculating the distance in WGS-84 gets me the result in degrees. I've also tried to project the geometries to World Mercator and calculate distance, but when data gets far from the equator, the results become more and more different.
How can I replicate this code in Oracle Spatial?

A: "In Oracle, calculating the distance on WGS-84 gets me the result in degrees."
That can only happen if your geometries are defined without any explicit SRID (= SDO_SRID is set to NULL). In that case, the database has no clue about what you are actually storing: it does not know that your data is actually geodetic. All it sees is some numbers that it assumes are in some unspecified cartesian projection. As a result, the distance you get is in decimal degrees. For example:
select sdo_geom.sdo_distance(
  sdo_geometry(2001, null, sdo_point_type(-90.207591, 32.3205, null), null, null),
  sdo_geometry(2001, null, sdo_point_type(-76.51416, 37.07585, null), null, null),
  0.01
) as distance
from dual;

which returns
  DISTANCE
----------
 14.495634

in decimal degrees.
1359310.6 meters.
To get the proper result (= a distance measured in meters or any other chosen unit), you must explicitly specify that the points are in geodetic coordinates. For example:
select sdo_geom.sdo_distance(
  sdo_geometry(2001, 4326, sdo_point_type(-90.207591, 32.3205, null), null, null),
  sdo_geometry(2001, 4326, sdo_point_type(-76.51416, 37.07585, null), null, null),
  0.01
) as distance
from dual;

which returns
  DISTANCE
----------
 1359310.6

This time the result is in the default distance unit, i.e. meters.
You can also specify an explicit unit for the result:
select sdo_geom.sdo_distance(
  sdo_geometry(2001, 4326, sdo_point_type(-90.207591, 32.3205, null), null, null),
  sdo_geometry(2001, 4326, sdo_point_type(-76.51416, 37.07585, null), null, null),
  0.01,
  'unit=mile'
) as distance
from dual;

The result is now:
  DISTANCE
----------
844.636447

in miles.
I should add that storing geometries without any SRID is a very poor practice: you will not be able to do any calculations with those shapes (like measuring lengths, distances and areas) and you will not be able to match them with shapes in other coordinate systems. While you can get away with projected shapes without a SRID to some extent, having geodetic shapes without any SRID is a definite no-no.

A: Have you tried specifying the units.
Based on this https://docs.oracle.com/cd/B19306_01/appdev.102/b14255/sdo_objgeom.htm#i857957
"Unit of measurement: a quoted string with unit= and an SDO_UNIT value from the MDSYS.SDO_DIST_UNITS table (for example, 'unit=KM'). See Section 2.8 for more information about unit of measurement specification."
I would think:
SDO_GEOM.SDO_DISTANCE(geom1 , geom2,0.01,'unit=M')

Would do the trick


text:
Q: highlight last 3 number in the string how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9
i want output:

ab9c5lek94ke72koe8nsk9

i tried following:
$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '$0', $str);

but it highlight:

ab9c5lek94ke72koe8nsk9

A: You can achieve that easily using regular expression with PHP's preg_replace() function. Just find last 3 digits 3 times at the end of the string. See the following code:
$str1 = 'ab9c5lek94ke2koe8nsk9';
$str2 = 'dag2vue41a89au76zhz30';

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '$1$2$3$4$5$6', $str1);
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '$1$2$3$4$5$6', $str2);

Outputs

ab9c5lek94ke2koe8nsk9

and

dag2vue41a89au76zhz30

A: You can have a regex like below:
/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/

which is basically (\d)([^\d]*) 3 times with a $ sign at the end. It means we are matching a digit followed by 0 or more non digit characters. Note that we do need the $ sign at the end to match only last 3 digits.
Snippet:
<?php

$str = "ab9c5lek94ke2koe8nsk9";

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/',"$1$2$3$4$5$6",$str);

Demo: https://3v4l.org/PoYCG
The replacement string is just having the bold tags with group number of the matched strings which are to be highlighted.

A: You can split the string on the 3rd from last number, then highlight everything in that sub string and then recombine the substrings.
In my example, I get all of the numbers in the string and put them in array. Then I use that array to get the delimiter (72 in your example), then use that to split the string into two arrays, at that point you can highlight everything in array[1] and then combine it back into array[0]
$str = "ab9c5lek94ke72koe8nsk9";
// get all of the numbers in order and place into it's own array
$numbers = trim(preg_replace('/[^0-9]/', ' ', $str ));
$numbers = preg_split('/\s+/', $numbers);

// using that get the delimiter to where to split the string. and split.
$delim = $numbers[count($numbers)-3];
$arr = explode($delim, $str);
$arr[1] = $delim . $arr[1];

// then highlight everything in $arr[1]
// then combine $arr[0] and $arr[1]


text:
Q: NgRx RxJS Extract and reuse common selector I'm trying to find a way to reuse RxJS Observable that combines multiple feature selectors:
// auth.selectors.ts
export const selectAuthState
  = createFeatureSelector<AuthState>('auth');

export const selectCurrentUser = createSelector(
  selectAuthState,
  (state) => {
    return state.auth
  }
)

// foo.selectors.ts
export const selectFoosState
  = createFeatureSelector<FoosState>('foo');

export const selectAllFoos = createSelector(
  selectFoosState,
  selectAll
)

// foo.component.ts
class FooComponent {
  constructor(private store: Store) {
    this.currentUser$ = this.store.pipe(select(selectCurrentUser));
    this.availableFoos$ = this.store.pipe(select(selectAllFoos));

    // GOAL is to reuse this observable in multiple components
    this.accountIsPendingReviewMsg$ = combineLatest(
      this.currentUser$,
      this.availableFoos$
    ).pipe(
      map(([user, foos]) => {
        return user && user.role === 'user' && foos.length === 0
      })
    )
  }
}

Is it possible? Not sure how to inject that this.store in extracted function.
I would like to know if it is possible to be done using just NgRx+RxJs, probably some idiomatic solution for what seems to be a pretty common task.
Alternative solution might involve the use of decorators and Angular injector but I would like to avoid it if possible.

A: you can simply create a combined selector on top of the two available selectors, something like below and use "accountPendingSelector" selector everwhere.
    // auth.selectors.ts
export const selectAuthState
  = createFeatureSelector<AuthState>('auth');

export const selectCurrentUser = createSelector(
  selectAuthState,
  (state) => state.AuthState
)

// foo.selectors.ts
export const selectFoosState
  = createFeatureSelector<FoosState>('foo');

export const selectAllFoos = createSelector(
  selectFoosState,
  selectAll
);

export const accountPendingSelector = createSelector(selectCurrentUser, selectAllFoos, (user, foos) => {
  return user && user.role === 'user' && foos.length === 0;
});


text:
Q: How do I install midi controller drivers and Traktor Pro software? I want to use ubuntu budgie remix 16.10, I'm dj and I have a MIDI controller that controls a sofware, called traktor pro. I use the controller in windows 7 ulltimate without problem, but I want to use it in ubuntu.
My problems are as follows:

*

*How to install the driver from my controller (Xponent from the manufacturer m-audio) in Ubuntu? Knowing that there is only driver for windows 7.

*How to install the program that the controller controls, the traktor pro (native instruments company)? Knowing that the installer is for Windows.
Thank you very much for the help and attention of all. I am available to try to do this remotely via teamviewer if necessary.

A: You can't install the Windows drivers. And you can't install Traktor Pro windows version on Linux. What you can try is mixxx.org, a free DJ program, much like Traktor.


text:
Q: Complex regular expression in JavaScript I have this task:
sum all numbers in string and perform multiplication

input: "3 chairs, 2 tables, 2*3 forks"
result: 11

I already have regular expression to do this:
eval(str.match(/(\d[\d\.\*]*)/g).join(' + '))

But I want to add option to ignore numbers inside brackets "()"

input: "2 chairs, 3 tables (1 broke)"
result: 5

How to do it?
Regular expressions were always pain for me :(

A: One simple way is to do a first pass and remove all parenthesized expressions.
str = str.replace(/\([^\)]*\)/g, "");
// now run your original algorithm to sum/multiply...
// ...

This is not super efficient but it does the job.
I should note that this does not handle nested parentheses, but it doesn't seem like that is required here.

A: You can use indexOf() and lastIndexOf() to detect the out-most parenthesis so that you can get rid of what you want.This works with indefinite parenthesis

A: (?=(\d+[\d.*]*)(?![^(]*?\)))\1

(?=( starts capturing a group using a look forward
(\d+[\d.*]*)

is the capture group for your number
(?![^(]*?\))

is a negative forward lookup that makes sure there isn't an open parenthesis after the number
)\1

look forward ends here match the found number.


text:
Q: On a Variational Inequality Let $H$ be a Hilbert space with real inner product. Consider $f: C \rightarrow C$, where $C \subset H$ is closed and convex.
I am not sure about the variational inequality problem: find $x \in H$ s.t.
$$ \langle f(x) - x, \ J(x-y) \rangle \geq 0$$
for all $y \in K \subset C \subset H$, where $J$ is the dual mapping.
How does this problem look like if $H = \mathbb{R}^n$?
Now assume that $f$ is decreasing (hence pseudocontractive, i.e., $\text{Id} - f$ is monotone).
Are there computational (iterative) methods to solve the variational inequality (say for $H = \mathbb{R}^n$)?


text:
Q: Como ajusta minha data da minha query?

$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$data' AND
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";

Tenho essa query, mas a mesma não funcionar direito pois o input que preencher a variável '$data' vem com o formato '12/11/2018' e o formato que conta na colona 'date_created' e '2018-12-11', como faço pra ajusta a minha query??

A: Use uma função que irá servir para duas entradas dd/mm/YYYY ou YYYY-mm-dd.
function inverteData($data){
    if(count(explode("/",$data)) > 1){
        return join("-",array_reverse(explode("/",$data)));
    }elseif(count(explode("-",$data)) > 1){
        return join("/",array_reverse(explode("-",$data)));
    }
}

$data = "12/11/2018";

//para usar na query
$dataInvertida = inverteData($data); //2018-11-12

//alguma data retornada do select
$dataBanco = "2018-11-21";

$dataBancoInvertida =  inverteData($dataBanco); // 21/11/2018

exemplo no ideone
$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$dataInvertida' AND
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";

A: Tem várias formas de fazer isso. Recomendo o seguinte:
// Recebe a variável com a data, e cria um objeto DateTime a partir do formato especificado.
$objetoData = DateTime::createFromFormat('d/m/Y', $data);

// Reformata a data do jeito desejado
$data = $objetoData->format('Y-m-d');

Depois é só usar a variável $data da forma que você estava fazendo.

A: Já que você precisa apenas fazer a consulta, pode trazer a sua coluna date_created do select formatado como precisa.
DATE_FORMAT(date_created, '%d/%m/%y')

Aqui tem maiores informações sobre a função date_format

É possivel fazer através do PHP também.
Transformando a data que você recebe no padrão utilizado pelo BD.
$dataFormat = DateTime::createFromFormat('d/m/Y', $data);

E para utilizar depois você pode formatar ela para o padrão necessário
$data = $dataFormat->format('Y-m-D');


text:
Q: Getting IMEI number without runtime permission Is there a way I can get IMEI(GSM)/MEID(CDMA) without implementing run time permission?
I have included the following permission in Android, however for some devices I get the IMEI number and for some Android devices I am getting my IMEI number and for some devices I get Exception {Java.Lang.SecurityException: getDeviceId at Java.Interop.JniEnvironment+InstanceMethods...
Why is that I have to handle the permission in the runtime despite listing them out in Manifest?

    var telephonyManager = (TelephonyManager)Forms.Context.GetSystemService(Android.Content.Context.TelephonyService);
    if (telephonyManager != null)
    {
        sIMEI = telephonyManager.DeviceId;
    }

If there is no way other than giving permission at runtime and then getting IMEI, could someone suggest the best way to get Unique ID for the android device programmatically. (The device ID should be seen from device as well)
I tried the below but few post suggests that AndroidId is not the same everytime.
 var android_id = Android.Provider.Settings.Secure.GetString(Forms.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);

A: Answer is NO, If you're running on Marshmallow or above version then you need android.permission.READ_PHONE_STATE permission to access the device id.
Alternatively you can generate unique id using below code -
String uniqueID = UUID.randomUUID().toString();

OR you can follow below link for more options
deviceID


text:
Q: Animate ImageBrush Transition I am building a WPF app to slideshow a sequence of images. For now, the slideshow images are hard-coded in the code behind class. The slideshow starts and stops by clicking the Click me button. I deliberately chose ImageBrush to be applied to Background property of Grid control, in place of the expected first choice of Image control, because I found that using Image.Source produces issues with the DispatcherTimer accuracy. Some images were displayed as expected, i.e., they followed timer.Interval, some were delayed, some were too short.
I want to add fade in and out transition animation as the images cycle. How do I do that?
Here is the current state of the XAML:
<Window x:Class="Temp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Temp"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid x:Name="gridBackground">

    <Button Width="100" Height="40" VerticalAlignment="Bottom" Click="btnClickMe_Click">
        Click me
    </Button>

</Grid>
</Window>

And here is the code behind:
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

public partial class MainWindow : Window
{
    private DispatcherTimer timer;
    private Brush[] colors;
    private int counter;

    public MainWindow()
    {
        counter = 0;
        colors = new Brush[]
        {
            new ImageBrush(new BitmapImage(new Uri(@"C:\Users\boris\Desktop\Stikeri\02.png", UriKind.Absolute))) { Stretch = Stretch.Uniform },
            new ImageBrush(new BitmapImage(new Uri(@"C:\Users\boris\Desktop\Stikeri\03.png", UriKind.Absolute))) { Stretch = Stretch.Uniform },
            new ImageBrush(new BitmapImage(new Uri(@"C:\Users\boris\Desktop\Stikeri\04.png", UriKind.Absolute))) { Stretch = Stretch.Uniform },
            new ImageBrush(new BitmapImage(new Uri(@"C:\Users\boris\Desktop\Stikeri\05.png", UriKind.Absolute))) { Stretch = Stretch.Uniform },
            new ImageBrush(new BitmapImage(new Uri(@"C:\Users\boris\Desktop\Stikeri\06.png", UriKind.Absolute))) { Stretch = Stretch.Uniform },
        };

        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 2);
        timer.Tick += Timer_Tick;

        InitializeComponent();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        if (counter == colors.Length)
        {
            counter = 0;
        }
        gridBackground.Background = colors[counter];

        counter++;
    }

    private void btnClickMe_Click(object sender, RoutedEventArgs e)
    {
        timer.IsEnabled = !timer.IsEnabled;
    }
}

If I am way off with my current approach, I'd be OK with ditching the DispatcherTimer in favor of some kind of animation defined in the code behind. I would, however, prefer to just slap some animation to the code I have already, if that is possible. Thank you!


text:
Q: Как сохранить http-response в MemoryStream или Jpeg файл В общем сабжю Посмотрел много форумов. Предлагают Webclient. Я хочу через HttpWebrequest.
A: Попробуйте следующий код:
var request = HttpWebrequest.Create(url);
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream()) {
 var memStream = new MemoryStream();
 responseStream.CopyTo(memStream);
}


text:
Q: Selenium java - HtmlUnitDriver finding elements So I am writting a program that performs actions on webpage automatically and I was using FirefoxDriver to do it but now i could really use HtmlUnitDriver instead.
This code works just fine:
                tempStr = AutoBot.queue.get(i);
                if(k == 0)
                {
                    System.out.println(ForumDialogBS.forumURL);
                    driver.get(ForumDialogBS.forumURL);
                    baseWinHandle = driver.getWindowHandle();
                    temp = AutoBot.logDetails.get("stuff");
                    element = driver.findElement(By.className("login-window"));
                    element.click();
                    element = driver.findElement(By.name("vb_login_username"));
                    element.sendKeys(temp.getUser());
                    element = driver.findElement(By.id("navbar_password_hint"));
                    element.sendKeys(temp.getPswd());
                    element = driver.findElement(By.className("loginbutton"));
                    element.click();
                    temp.rst();
                    driver.switchTo().window(baseWinHandle);
                    k = 1;
                    pause(2);
                }
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("qr_preview")));
                element = driver.findElement(By.id("qr_preview"));
                element.click();
                element = driver.findElement(By.cssSelector("textarea.cke_source"));
                element.sendKeys(tempStr);
                wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("sbutton")));
                element = driver.findElement(By.name("sbutton"));
                element.click();
                System.out.println((i+1) + "//" + AutoBot.toIndex);
                pause(8);

the driver is made like this:
String tempStr;
String baseWinHandle;

FirefoxDriver driver = new FirefoxDriver();

WebDriverWait wait = new WebDriverWait(driver, 60);

WebElement element;

List<WebElement> inputs;

But when I try to change to HtmlUnitDriver I encounter problems with locating elements.
First I got errors like this:
:43:57 PM com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error WARNING: CSS error: 'http://pornsavant.com/clientscript/vbulletin_css/style00011l/main-rollup.css?d=1415642704' [1:48457] Error in expression. (Invalid token ";". Was expecting one of: <S>, <NUMBER>, "inherit", <IDENT>, <STRING>, <PLUS>, <HASH>, <EMS>, <EXS>, <LENGTH_PX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <PERCENTAGE>, <DIMENSION>, <URI>, <FUNCTION>, "-".)

And then:
    Exception in thread "Thread-5" org.openqa.selenium.TimeoutException: Timed out after 60 seconds waiting for visibility of element located by By.id: qr_preview
Driver info: org.openqa.selenium.htmlunit.HtmlUnitDriver
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:79)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:228)
    at pl.posterhelper.Poster.run(Poster.java:135)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element with ID: qr_preview
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Driver info: driver.version: HtmlUnitDriver
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementById(HtmlUnitDriver.java:949)
    at org.openqa.selenium.By$ById.findElement(By.java:214)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1637)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1291)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1633)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:539)
    at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:730)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:728)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:1)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)

If i delete the "wait" i get error saying that Returned element wasn't Html element
Is there anyone that could help solve those errors?
I've literally searched everywhere and couldn't find any answers.


text:
Q: The system cannot find the file specified- Task Scheduler. Win Server 2012 I have batch script file, which should encrypt a file with pgp. I have defined a task in task scheduler to do this, but I am keep receiving the error"The system cannot find the file specified".
Interestingly, when I run the same line of script in my powershell , the encrypted file is successfully generated.
I was wondering if anyone knows what can possibly be wrong here?
I tried to give the full path in my batch script , and also added the pass in start in part, when defining the action.
the batch scrip code is here::
rem @echo off
@set path=c:\test;%path%

@set d=%date:~-4,4%%date:~4,2%%date:~-7,2%
@set d=%d: =_%
@set t=%time:~0,2%%time:~3,2%%time:~6,2% @set t=%t: =0%

Rem  Generate PGP encrypted file
@echo Starting PGP... >> c:\apps\ftpLogs\test.log
gpg2 --batch --yes -r testkey --output c:\test\foo\test_20150505.pgp --encrypt c:\test\foo\test_20150505.txt >> c:\apps\ftpLogs\test.log

and the script that I ran in my powershell, which works fine, is this line:
gpg2 --batch --yes -r testkey --output c:\test\foo\test_20150505.pgp --encrypt c:\test\foo\test_20150505.txt >> c:\apps\ftpLogs\test.log

A: Finally I was able to resolve the issue. The problem was with the user authority. The batch script was suppose to encrypt a file and then ftp the encrypted file to the vendor's ftp server.
Apparently in Windows Server 2012 , the ADMINISTRATORS have the permission to create a file (here the encrypted file) while this user does not have the permission to send it. and SYSTEM user has the permission to send but not to create. (Both of them had this authority back in Win Server 2008).
hence what did I do at the end, was to make two different batch script tasks and schedule them with 10 mins time distance. The first one was running the above code with ADMINISTRATOR privileges and the second one was sending it out with SYSTEMS.

A: I had this same error, but in my case it only occurred when running the task as a Service account; the task worked fine when running as my domain user. The error was basically a red herring, and instead ended up being due to using the GUI to select an option that may be unsupported. Basically, don't set "If the task is already running..." to "Stop the existing instance". Use any of the other 3 options.
More detailed info here.


text:
Q: XamarinForms ListView item fill with How can I force my TemplateItem to expand and fill the entire width of the ListView?
AS you can see in the Screenshot, the listView has a red background, and my items have an white background.
The code of the DataTemplate:
  <DataTemplate x:Key="InformationMessageTemplate">
    <StackLayout Orientation="Horizontal" BackgroundColor="#FFFFFF" HorizontalOptions="FillAndExpand">
      <Label FontAttributes="Bold" Text="{Binding Sender}"  />
      <Label Text=" chegou na sala" HorizontalOptions="FillAndExpand"/>
    </StackLayout>
  </DataTemplate>

A: Try putting the StackLayout in a ViewCell:
<DataTemplate x:Key="InformationMessageTemplate">
    <ViewCell>
        <ViewCell.View>
             <StackLayout Orientation="Horizontal" BackgroundColor="#FFFFFF" HorizontalOptions="FillAndExpand">
                 <Label FontAttributes="Bold" Text="{Binding Sender}"  />
                 <Label Text=" chegou na sala" HorizontalOptions="FillAndExpand"/>
             </StackLayout>
         </ViewCell.View>
    </ViewCell>
  </DataTemplate>


text:
Q: Processes don't terminate I am using Java Executors.newWorkStealingPool(); for running several commands in parallel. Since some of these tasks are expected to timeout, I added a 2 second timeout for them.
ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
Process p = null;
StringBuilder result = new StringBuilder();
try {
    p = pb.start();
    p.waitFor(2000, TimeUnit.MILLISECONDS);
    BufferedReader errreader =
    new BufferedReader(new InputStreamReader(p.getErrorStream()));
    BufferedReader outreader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = outreader.readLine())!= null)
    result.append(line + "\n");
    while ((line = errreader.readLine())!= null)
        result.append(line + "\n");
    outreader.close();
    errreader.close();
    } catch (InterruptedException e) {
        result.append("INTERRUPTED");
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    finally {
        p.destroy();
    }
    ....
    return b; // b is boolean

Submitting tasks looks like this
List<ImmutablePair> curJobs = new ArrayList<ImmutablePair>();
for (int i = 0; i <  allMutants.size(); i++) {
    String mutant = allMutants.get(i);
    t = executor.submit(new mutTask(mutant));
    ImmutablePair pair = new ImmutablePair(mutant, t);
    curJobs.add(pair);
    }

and finally. I gather results in the following loop.
// data collection loop
for (int i = 0; i< curJobs.size(); i++) {
        ImmutablePair p = curJobs.get(i);
        String m= (String) p.getLeft();
    System.out.println(m);
        t = (Future<Boolean>) p.getRight();
    try {
        boolean res;
        try {
            res = t.get(2000L, TimeUnit.MILLISECONDS);

        } catch (TimeoutException e) {
            res = true;
        }
        finally {
            t.cancel(true);
        }}

The problem is that, the timeout does not seem to terminate some of the commands or processes as it defined in the program. After few minutes data collection loops get very slow. The result of ps shows some jobs that are running well above the specified timeout and keeping CPU busy. My config is JDK8 on CentOS.

A: As @MadProgrammer noted the problem was reading out/err buffers in case that processes terminate. To solve that, you need to check the output of  p.waitFor(2000, TimeUnit.MILLISECONDS);
    try {
        p = pb.start();
        boolean timeout = !p.waitFor(2000, TimeUnit.MILLISECONDS);
        if (!timeout){
            BufferedReader errreader =
                     new BufferedReader(new InputStreamReader(p.getErrorStream()));
            BufferedReader outreader =
                     new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = outreader.readLine())!= null)
                result.append(line + "\n");
            while ((line = errreader.readLine())!= null)
                    result.append(line + "\n");
            outreader.close();
            errreader.close();
        }

    } catch ...


text:
Q: Javascript: Find text (like ctrl+f) and return boolean if found Can anyone help me out with a function in javascript which is for searching a site for words (like the ctrl+f function of browsers) and return a bolean if found?
For example on this site it would like this:
searchText("Question");
It would search and find it on the top right and would return true.
Thanks already!

A: There is window.find() method doing exactly what you want. It finds a string in window:
if (find(stringToFind)) {
    alert('Found');
}

Found string will also be highlighted. This function is supported in all major browsers (IE7+).
https://developer.mozilla.org/en-US/docs/Web/API/Window.find

A: Using jQuery you can do:
if ( $('body').text().search('YOUR TEXT') == -1)
    return false;
else
    return true;


text:
Q: Is there a cap to EM wavelengths I was just wondering, if there is a cap to the min and max of EM waves.
like whats the smallest possible wavelength? the width of an electron? smaller? What kind of wave would that be?
And what about the other end? If I'm not wrong radio waves are really long but what would we get with a wavelength of like 1 km?

A: Well, 1km wavelength is not unusual. It's at the top of the Low Frequency (LF) band:
https://en.wikipedia.org/wiki/Low_frequency
and it is surpassed in length by the very-, ultra-, super-, and extremely-low bands (VLF, ULF, SLF, and ELF, respectively). ELF goes down to 3Hz (100,000 km).
Of course, there are lower frequencies, with 0Hz corresponding to a static field.
At higher frequencies, we generally consider single photons. Accelerators can produce Bremsstrahlung up to their beam energy.
Higher energy photons come in the form of cosmic rays, which are detected via the Cherenkov shower detectors. Very-high-energy gamma rays (VHEGR) ranging from 100 GeV to 100 TeV have been detected. Recall that:
$$ \hbar c \approx 200 \,{\mathrm{MeV\cdot fm}} $$
so VHEGRs' wavelengths can be a short as
$$ 2\times 10^{-6}\ \mathrm{fm} = 2\times 10^{-21}\ {\mathrm m}$$
Higher energy photons are called Ultra-High Energy Gamma Rays (UHEGR), and are the subject of cosmic-ray research. At these extreme energies pair-production can occur in a static magnetic field (e.g., the Earth's field), so that propagation becomes non-trivial. (See: Landau–Pomeranchuk–Migdal effect).
There is also the Greisen–Zatsepin–Kuzmin limit, which should remind you that wavelength is not a Lorentz scalar. In the reference frame of an Ultra High Energy Cosmic Ray, some of the cosmic microwave background radiation is extremely short wavelength photons.

A: Theoretically:
There is no maximal wavelength. One could say that the observable universe is the max, but then we could say that the whole universe is infinite.
There is no minimal wavelength. One could say that the Planck scale is the minimal that makes sense, but that is a misconception.
Even at wavelengths smaller then the Planck length, we would be nowhere near the energy of the universe.
In practice:
The shortest ever detected is 16Tev gamma ray, which means 1 billionth of a nanometer.
The longestwavelength is 40000km, which is for the Schuman resonance, for 7.83Hz. It is caused by 1000 lightnings per second, and is a standing wave.


text:
Q: Delete button on a UITableview Cell blocks custom cell images I have subclassed a tableview cell and added a couple of labels and images to the custom cell.
   [self.contentView addSubview:lblDesc];
   [self.contentView addSubview:imagesToDisplay];

When i edit the tableView and press the "-" sign the delete button appears on top of the image and other contents.
Some other apps squeeze the contents of the cell to accomodate the delete button.
How do i go about doing this??
Do i need to add a key value Observer
       [cell addObserver: self forKeyPath: @"showingDeleteConfirmation"
          options: NSKeyValueObservingOptionNew context: NULL];

A: Autoresizing is simple - think of it like a web page.  Web content "flows", it takes up as much space as the browser window gives it.  Autoresizing is the same.  There are "masks" which tells UIKit how you want your content to adjust to different frame sizes.
So, for example, if you want your view to shrink or grow from the right side (if it were, for example, left-justified content like a table cell), you'd set the mask like this:
cell.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;

Autoresizing also works like a bitwise-OR operation, so if you want it to grow from the right (as above) but also grow from the bottom, you'd "OR" the two together.
cell.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin);

In the case that this does not work for you (e.g. you want to put too much on the screen, and need to remove certain elements, etc, or you want to animate somehow differently than the default), consider using the pre-existing method calls in UITableViewCell.  From the documentation:
- (void)willTransitionToState:(UITableViewCellStateMask)state

This will be called right before the cell changes state (normal->editing or the other), so if you need to do anything special to handle the animation to the editing state, this is your opportunity to do so.  The docs state:

Subclasses of UITableViewCell can
  implement this method to animate
  additional changes to a cell when it
  is changing state. UITableViewCell
  calls this method whenever a cell
  transitions between states, such as
  from a normal state (the default) to
  editing mode. The custom cell can set
  up and position any new views that
  appear with the new state. The cell
  then receives a layoutSubviews message
  (UIView) in which it can position
  these new views in their final
  locations for the new state.
  Subclasses must always call super when
  overriding this method.overriding this method.

A: You need to set the proper autoresizingMask so that your button moves properly when the contentView changes size.


text:
Q: Sum of reciprocals of maximal prime gaps and primes Let $G_r =$ http://oeis.org/A005250, and $P_r =$ http://oeis.org/A002386.
$\sum_{n=1}^{\infty}{\frac{1}{G_r}} = c_1$
$\sum_{n=1}^{\infty}{\frac{1}{P_r}} = c_2$
Do the constants c_1 and c_2 exist?
The reason I ask is how rare these numbers seems to be. There are only 80 of them known $< 2^{64}$ yet $\infty$ many of them. I kinda expect the sum with gaps to diverge while the primes to converge. The sum of the first 80 gaps is 2.55968417154317 while the first 5 terms added to 2.04166666666667. For the primes, they seem to converge in a spreadsheet to 1.04470058508119. Because this not even a 64-bit spreadsheet, I do not trust it to answer my guess.


text:
Q: Obtaining sequential matches between two columns of a data frame returning a list I have a data frame of two variables (Var1 and Var2). The two elements of each row of the data frame are already matched based on characteristic differences between the two values which were previously established. I.e. 397.1074 is matched to 510.2119 and 436.4694 is also matched to 510.2119.
matches <- data.frame(
  Var1 = c(397.1074, 436.4694, 510.2119, 581.2889, 761.0372, 851.5489, 860.3277, 861.0612, 851.5489, 860.3277, 861.0612, 860.3277, 861.0612, 861.0612,
871.4374, 861.0612, 871.4374),
  Var2=c(510.2119, 510.2119, 581.2889, 728.2789, 860.3277, 924.9473, 924.9473, 924.9473, 925.7278, 925.7278, 925.7278, 934.1579, 934.1579, 935.0957,
935.0957, 943.1851, 943.1851)
 )
matches
#        Var1     Var2
# 1  397.1074 510.2119
# 2  436.4694 510.2119
# 3  510.2119 581.2889
# 4  581.2889 728.2789
# 5  761.0372 860.3277
# 6  851.5489 924.9473
# 7  860.3277 924.9473
# 8  861.0612 924.9473
# 9  851.5489 925.7278
# 10 860.3277 925.7278
# 11 861.0612 925.7278
# 12 860.3277 934.1579
# 13 861.0612 934.1579
# 14 861.0612 935.0957
# 15 871.4374 935.0957
# 16 861.0612 943.1851
# 17 871.4374 943.1851

However, what I am trying to do and am unaware of a function or package suitable for the task is to identify the unbroken chains of matches of the variables from one column to another.
i.e. 397.1074 is matched to 510.2119 in the first row. 510.2119 is matched to 581.2889 in the 3rd row. 581.2889 is matched to 728.2789 in the 4th row. This continues until the value from column 2 can no longer be matched to the values in column 1.
Therefore the first chain of matches would in this case be a vector of length 4 preferably returned as an element within a list :
[[1]]
[1] 397.1074 510.2119 581.2889 728.2789

The second list element in the result  would therefore be:
[[2]]
[1] 436.4694 510.2119 581.2889 728.2789

[[3]] .... Etc.

The list result would contain all of the matched elements from columns 1 and 2. Even those of a length of only  two.

A: An approach, that is probably not that efficient, could be:
ff = function(var2)  # a function to, recursively, match each match
{
   res = c(var2, matches$Var2[match(tail(var2, 1), matches$Var1)])
   if(!is.na(tail(res, 1))) res = Recall(res)
   return(c(na.omit(res)))
}

lapply(seq_len(nrow(matches)),
       function(i) c(matches$Var1[i], ff(matches$Var2[i])))
#[[1]]
#[1] 397.1074 510.2119 581.2889 728.2789
#
#[[2]]
#[1] 436.4694 510.2119 581.2889 728.2789
#
#[[3]]
#[1] 510.2119 581.2889 728.2789
#
#[[4]]
#[1] 581.2889 728.2789
#
#[[5]]
#[1] 761.0372 860.3277 924.9473
#
#[[6]]
#[1] 851.5489 924.9473
#
#[[7]]
#[1] 860.3277 924.9473
#....


text:
Q: How can I throw die in Perl debugger? I want to debug my Perl code with die.
I wrote this code.
eval {
  print("foo");
  print("bar");
  print("fizz");
  print("buzz");
}

if ($@) {
  print("error");
}

*Of course this code is an abstracted sample.
I want to run "if" route in the debugger without any code changes.
I want to run "if" route of this code in the debugger.

A: The debugger doesn't change what the program does. You can change the value of variables, but that's it.
Fortunately, the code in question is executed based on the value of $@. So you would set the value of $@ to something true.


text:
Q: How to implement AsyncTask on my code? public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //connMgr = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);

        //if ((connMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
            //  || (connMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)) {

        if(new CheckInternetAvaliable(MobileReagentsActivity.this).isInternetAvaliable) {

            morePrefs = this.getSharedPreferences("morePrefs", MODE_WORLD_READABLE);

            final int welcomeScreenDisplay = 5000;

            db = new VendorRatingDatabaseHandler(this);

            isDataInserted = morePrefs.getBoolean("flagValue", false);

            Thread welcomeThread = new Thread() {

                int wait = 0;

                @Override
                public void run() {
                    try {
                        super.run();
                        while (wait < welcomeScreenDisplay) {
                            sleep(100);
                            wait += 100;
                        }
                    } catch (Exception e) {
                        System.out.println("EXc=" + e);
                    } finally {
                        Intent intent = new Intent(MobileActivity.this, HomeScreen.class);

                        intent.putExtra("message", message);
                        intent.putExtra("topMolNames", topMolNames);
                        intent.putExtra("topFomls", topFomls);
                        intent.putExtra("lastConnect", lastConnect);
                        intent.putExtra("dateDiff", dateDiff);
                        intent.putExtra("moldrawPrefs", moldrawPrefs);

                        startActivity(intent);
                        Log.i("Test", "Starting Home Screen!! ");
                        MobileActivity.this.finish();
                    }
                }
            };
            welcomeThread.start();

            try {

                SAXParserFactory saxPF = SAXParserFactory.newInstance();
                SAXParser saxP = saxPF.newSAXParser();
                XMLReader xmlR = saxP.getXMLReader();

                URL url = new URL(ConstantsClass.MORE_STARTUP_MESSAGE_URL + "?uid="+new AndroidUdIdClass(MobileActivity.this).androidId+"&device=android"); // URL of the XML

                XMLHandler myXMLHandler = new XMLHandler();
                xmlR.setContentHandler(myXMLHandler);
                xmlR.parse(new InputSource(url.openStream()));

            } catch (Exception e) {
                System.out.println(e);
            }

             getsetXML = XMLHandler.data;

             message = getsetXML.getMessage();
             vendorListFull = getsetXML.getVendorListFull();
             vendorListUser = getsetXML.getVendorListUser();
             topMolNames = getsetXML.getTopMolNames();
             topFomls = getsetXML.getTopFomls();
             lastConnect = getsetXML.getLastConnect();
             dateDiff = getsetXML.getDateDiff();
             moldrawPrefs = getsetXML.getMoldrawPrefs();

             prefsEditor = morePrefs.edit();
             prefsEditor.putString("UserVendorList", vendorListUser);
             prefsEditor.putString("VendorListFull", vendorListFull);
             prefsEditor.commit();

             //---------------------------------------------------------

             String[] str_arr_vendor_list = vendorListFull.split(",");

             for(int i=0; i<str_arr_vendor_list.length; i++) {

                 VendorRatingData vendorRatingData = new VendorRatingData();

                 vendorRatingData.setVendorName(str_arr_vendor_list[i]);
                 vendorRatingData.setVendorRating("0");

                 VendorRatingData vendor_rating = new VendorRatingData();

                 if(!isDataInserted) {

                     db.addVendorRating(vendorRatingData);

                 }else {

                     vendor_rating = db.getRating(str_arr_vendor_list[i]);

                    // Toast.makeText(getApplicationContext(), "vendor_rating::" + i, Toast.LENGTH_LONG).show();
                     if(!(vendor_rating.getVendorName().equalsIgnoreCase(str_arr_vendor_list[i]))) {

                         db.addVendorRating(vendorRatingData);
                     }
                 }

             }

             db.close();

             prefsEditor = morePrefs.edit();
             prefsEditor.putBoolean("flagValue", true);
             prefsEditor.commit();
        }

I get ANR error while executing this code when the data is fetching takes time so i would like to add AsyncTask to it but i dont know to to do. please help me!

A: follow like this:
@Override
protected void onNewIntent(Intent intent) {
    //this is very important, otherwise you would get a null Scheme in the onResume later on.
    setIntent(intent);
}

public class FetchAlbums extends AsyncTask<Void, Void, ArrayList<Photoset>> {

//declarations what u required
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected ArrayList<PhotoSet> doInBackground(Void... params) {

    //do ur work here completly that will runs as background
}

@Override
protected void onPostExecute(ArrayList<PhotoSet> result) {
super.onPostExecute(result);
}
}


text:
Q: React native keyboard ignores padding and don't scroll all the way down when input pressed Okay, so I have a problem where when I press the text input to add a user the app dont scroll all the way down as you can se in the second picture. I have some padding on the input View wrapper "the red color" but when I press the input it scrolls all the way to input and removes some of the border color and it just looks ugly.
How do I fix so that it scroll all the way down with the padding?
My code for the file
CSS
  logoWrapper: {
    position: 'relative',
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: 120
  },
  logo: {
    color: 'white',
    textAlign: 'center',
    fontSize: 55,
    fontFamily: 'JosefinSans-BoldItalic',
    position: 'absolute',
    zIndex: 2,
  },
  back: {
    color: 'black',
    textAlign: 'center',
    fontSize: 55,
    fontFamily: 'JosefinSans-BoldItalic',
    position: 'absolute',
    top: '50%',
    transform: [{ translateY: -50 }],
    marginTop: 20,
  },
  container: {
    flex: 1,
    backgroundColor: '#303030',
  },
  taskWrapper: {
    paddingHorizontal: 20,
  },
  textSection: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  items: {
    marginTop: 30,
    justifyContent: 'center',
    alignItems: 'center',
  },
  writeTaskWrapper: {
    backgroundColor: 'red',
    paddingVertical: 20,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  addText: {
    fontFamily: 'JosefinSans-Regular',
    color: 'white',
    fontSize: 40,
    position: 'absolute',
    top: -5,
  },
  addPlayer: {
    fontFamily: 'JosefinSans-Regular',
    fontSize: 13,
    color: 'white'
  },
  input: {
    paddingVertical: 15,
    width: 200,
    paddingHorizontal: 25,
    backgroundColor: '#333',
    borderRadius: 60,
    borderColor: '#C0C0C0',
    borderWidth: 1,
    color: 'white',
    height: 60,
  },
  addWrapper: {
    width: 60,
    height: 60,
    backgroundColor: '#333',
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: '#C0C0C0',
    color: 'white',
    borderWidth: 1,
  },
  startWrapper: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  startButton: {
    padding: 15,
    backgroundColor: '#f06e6e',
    borderRadius: 10,
    borderColor: 'white',
    borderWidth: 2,
    marginTop: 20,
    width: 250,
    justifyContent: 'center',
    alignItems: 'center',
  },
  startText: {
    color: 'white',
    fontSize: 20,
    fontFamily: 'JosefinSans-BoldItalic',
  },
  changeLang: {
    position: 'absolute',
    top: 10,
    right: 10,
    zIndex: 10,
  },
  langStyle: {
    color: 'white',
    fontSize: 12,
    fontFamily: 'JosefinSans-BoldItalic',
    borderRadius: 10,
    textTransform: 'capitalize',
  },
  debug: {
    position: 'absolute',
    top: 10,
    left: 10,
    zIndex: 10,
  }

APP js file
  return (
      <View style={styles.container}>
        <View style={styles.changeLang}>
          <TouchableOpacity onPress={() => changeLang()}>
            <Text style={styles.langStyle}>{lang.lang}</Text>
          </TouchableOpacity>
        </View>
        <ScrollView style={styles.container} keyboardShouldPersistTaps={'handled'} enableAutoAutomaticScroll={false}>
          <FadeInView>
            <View style={styles.logoWrapper}>
              <Text style={styles.logo}>
                PartyTime
              </Text>
              <Text style={styles.back}>
                PartyTime
              </Text>
            </View>
          </FadeInView>
          <View style={styles.taskWrapper}>
            <View style={styles.startWrapper}>
              {players.length > 0 ? <TouchableOpacity onPress={() => startGame()} style={styles.startButton}>
                <Text style={styles.startText}>Start game</Text>
              </TouchableOpacity> : <Text style={styles.addPlayer}>Add a player to start the game</Text>}
            </View>
            <View style={styles.items}>
              {
                players.map((item, index) => {
                  return (
                    <TouchableOpacity key={index} onPress={() => dispatch(removePlayer(index))}>
                      <Users text={item} />
                    </TouchableOpacity>
                  )

                })
              }
              <View style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Add a player'} placeholderTextColor="white"
                  value={playerName} onChangeText={text => setPlayerName(text)} />
                <TouchableOpacity onPress={() => { dispatch(addPlayer(playerName)); setPlayerName('') }} >
                  <View style={styles.addWrapper}>
                    <Text style={styles.addText}>+</Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </ScrollView>
      </View>
  );

A: Please consider using KeyboardAvoidingView.
It would help you scroll the screen when the keyboard events occur.
Official Document :
https://reactnative.dev/docs/keyboardavoidingview

A: You can try this,
<KeyboardAwareScrollView  keyboardShouldPersistTaps={'always'}
        style={{flex:1}}
        showsVerticalScrollIndicator={false}>
    {/* Your code goes here*/}
</KeyboardAwareScrollView>


text:
Q: Simple Algorithm complexity I have an algorithm and I need help finding the complexity of it (tightest possible upper bound)
for(int i = 0; i < n/2; i++)
    for(int j = 0; j < n/4; j++)
        for(int k = 0; k < n; k++)
            x++;

My analysis is that if n would not be divided in each for loop, it would be O(n^3). This complexity still holds true, since each "for loop" will reduce each operation to a O(log n) complexity since it divides n every time the loop executes, making it smaller and smaller (smaller than O(n) at least).
I would say that the answer is between O(log n) and O(n^3). Could you help me getting the tightest possible bound?

A: start with inner loop :
for(int k = 0; k < n; k++)
    x++;

is obviously O(n).
now one layer above that :
for(int j = 0; j < n/4; j++)

is O(n) because it takes n/4 for j to reach the n and we know that O(n/4) = O(n)
and like this for outer loop is O(n).so the complexity is O(n^3) because you have three nested loop each with O(n) and non of them have effect on each other.

A: Assume each step takes time C.
For k-loop, time taken is Cn.
For j-loop, time taken to complete iteration is (Cn)n/4=C(n^2)/4
For i-loop, time taken to complete iteration is (C*(n^2)/4)n/2=C(n^3)/8
So Total time taken=(C/8)*(n^3)
As C/8 is a constant it can be ignored when considering Big-O Notation.
Thus, Time Complexity=O(n^3).

A: for(int i = 0; i < n/2; i++)    --> n/2
    for(int j = 0; j < n/4; j++)  --> n/4
        for(int k = 0; k < n; k++)  --> n
            x++;

Hence total complexity is O((n^3)/8) which is O(n^3)


text:
Q: Showing CSV-file in GeoServer I created a PostGIS connection in QGIS and I added in a CSV-file.
I added this database into GeoServer but inside this, I don't have the CSV-file.
How can I add it as well?

So is it not possible visualize CSV in geoserver?

A: GeoServer will only show you tables that have a geometry column in them.


text:
Q: Adding Custom Key-bindings to XCode I am trying to add a group of custom key-bindings to Xcode 6. I've looked up in the past posts and discovered to do this you need to edit the Default.idekeybindings file located in your Xcode -> UserData -> KeyBindings -> Default.ideakeybindings
I have edited this according to how it was done in the previous versions, but when I go into the preferences -> keybindings within Xcode I am not able to find the custom action I defined. I would ideally like to make a one key "copy line", "cut line", "duplicate line" and some other useful keybindings I've grown to like while using Sublime and Atom. I've included my .ideakeybindings edited file contents below for reference to what I'm trying to do.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>My Custom Actions</key>
    <dict>
        <key>Delete Current Line/Selection</key>
        <string>deleteToEndOfLine:, deleteToBeginningOfParagraph:</string>
        <key>Duplicate Line</key>
        <string>selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:</string>
    </dict>
</dict>
</plist>

A: I did this on Xcode 7:

*

*Close Xcode

*Open the file /Applications/Xcode-Beta.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist with sudo privileges (be sure to use the correct app-directory for the version of Xcode you are using---for Xcode 6.3 beta mine was Xcode-Beta.app)

*Add your custom commands, save and then start Xcode.

*Set key bindings in Xcode preferences

I added this section:
<key>My Custom Commands</key>
<dict>
    <key>Insert New Line Below</key>
    <string>moveToEndOfLine:, insertNewline:</string>
    <key>Insert New Line Above</key>
    <string>moveUp:, moveToEndOfLine:, insertNewline:</string>
    <key>Duplicate Current Line</key>
    <string>moveToBeginningOfLine:, deleteToEndOfLine:, yank:, insertNewline:, moveToBeginningOfLine:, yank:</string>
    <key>Delete Current Line</key>
    <string>selectLine:, delete:</string>
    <key>Cut Current Line</key>
    <string>selectLine:, cut:</string>
    <key>Copy Current Line</key>
    <string>setMark:, selectLine:, copy:, moveToEndOfLine:, swapWithMark:</string>
    <key>Paste At Beginning Of Line</key>
    <string>moveToBeginningOfLine:, paste:</string>
</dict>

As this gets overwritten every time a new version of Xcode is installed, a user settings location for the custom commands would really be appreciated if someone knows where to add them in the user dir.

A: I've been using the following for years because I came from Eclipse camp and do like "Duplicate Current Line Up" and "Duplicate Current Line Down" very much.
Note "Xcode.app" could be "Xcode62.app" or "Xcode63.app" depending on how you renamed it.
sudo vim /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist

<key>Customized</key>
<dict>
    <key>Duplicate Current Line Up</key>
    <string>moveToBeginningOfLine:, deleteToEndOfLine:, yank:, insertNewline:, moveToBeginningOfLine:, yank:, moveUp:</string>
    <key>Duplicate Current Line Down</key>
    <string>moveToBeginningOfLine:, deleteToEndOfLine:, yank:, insertNewline:, moveToBeginningOfLine:, yank:</string>
    <key>Delete Current Line</key>
    <string>deleteToBeginningOfLine:, moveToEndOfLine:, deleteToBeginningOfLine:, deleteBackward:, moveDown:, moveToBeginningOfLine:</string>
</dict>

Restart Xcode | Preferences | Key Bindings | All
search "Duplicate"
search "Current"
then input your favorite shortcut key bindings.
I learnt this trick from somewhere in SO - thx a lot to the original poster. It works on Xcode 6.3 latest beta, Xcode 6.2, 6.1 and previous Xcode versions.