text:
Q: Perl foreach loop variable scope I am new to perl and was confused with perl scoping rules after I wrote below code snippet:
#!/usr/bin/perl
my $i = 0;
foreach $i(5..10){
    print $i."\n";
}
print "Outside loop i = $i\n";

I expected output to be like :
5
6
7
8
9
10
Outside loop i = 10

But its giving :
5
6
7
8
9
10
Outside loop i = 0

So the variable $i value is not changing after the loop exits. Whats going on in here?

A: According to the perldoc information regarding foreach loops: here

The foreach loop iterates over a normal list value and sets the
  variable VAR to be each element of the list in turn. If the variable
  is preceded with the keyword my, then it is lexically scoped, and is
  therefore visible only within the loop. Otherwise, the variable is
  implicitly local to the loop and regains its former value upon exiting
  the loop. If the variable was previously declared with my, it uses
  that variable instead of the global one, but it's still localized to
  the loop. This implicit localization occurs only in a foreach loop.

If you want to retain the value of $i outside the loop then you can omit $i in the foreach loop call and use perl's special variable $_ an example below:
#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;
foreach (5..10){
    print $_."\n";
    $i = $_;
}
print "Outside loop i = $i\n";

5
6
7
8
9
10
Outside loop i = 10

A: foreach localize variable to the loop.
use strict;
use warnings;

my $adr;
my $i = 0;
foreach $i(5..10){
    $adr = \$i;
    print "$i ($adr)\n";
}
$adr = \$i;
print "Outside loop i = $i ($adr)\n";

output
5 (SCALAR(0x9d1e1d8))
6 (SCALAR(0x9d1e1d8))
7 (SCALAR(0x9d1e1d8))
8 (SCALAR(0x9d1e1d8))
9 (SCALAR(0x9d1e1d8))
10 (SCALAR(0x9d1e1d8))
Outside loop i = 0 (SCALAR(0x9d343a0))

From perldoc,

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.

To preserve value of $i you can use C like for loop,
my $i = 0;
for ($i = 5; $i <= 10; $i++) { .. }

although it's less readable than perl foreach

A: The variable $i is redefined in foreach scope at
foreach $i(5..10){

So the variable outside foreach will not change.


text:
Q: Definition of a 'tunneling lifetime' I'm given a one-dimensional potential with two wells, one local minimum at some higher energy and one deep global minimum next to it, separated by a barrier of own shape and height (phase qubit). I used a WKB approx. in conjunction with a harmonic approximation of the barrier to find the tunneling probability, i.e. the transmission coefficient T.
Now, I'm asked to estimate the tunneling lifetime of the metastable levels in the elevated well. How do you relate the tunneling probability to the lifetime?

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to switch from 64 bit python 2.7 to 32 bit python 2.7 on mac I need to switch from 64 bit python to 32 bit, in order to run py-game. because py-game only comes in 32 bit version and does not come in 64 bit. so i either have to be able to switch it from 64 to 32 or uninstall the 64 and install the 32. and on that note i have no idea how to do either of them.
thanks

A: Install the 32-bit version here:
https://www.python.org/download/
I don't recommend uninstalling the 64 bit version as it could potentially break some programs in your computer.
But should you want to follow through (and again, I don't recommend), follow this tutorial here:
http://wolfpaulus.com/jounal/mac/installing_python_osx/
Basic overview (please look at guide for the complete safer way to do this):
sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
sudo rm -rf "/Applications/Python 2.7"

This will remove python from your system. And to furthermore complete, find the related-python links in: /usr/local/bin use ls and rm -rfto delete them.


text:
Q: Incorrect use of Parent Data Widget in ListView There are three tags in a row, which are fetching data from an API, now when the text coming from data is large, the pixels are overflowing , so i want that, when the data comes for first tag, it takes a a small space and then goes to the 2nd line, and other tags should remain at the same place, how can i do that.
below are the three tags named CustonTag which are children of a row and row is a child of a col, and col is a child of an expanded container
ListView(
          children: [
            HeadlineofArticle(article: article),
            Expanded(
              child: Container(
                padding: const EdgeInsets.all(20.0),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      topRight: Radius.circular(20.0)),
                  color: Colors.white,
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        CustomTag(background: Colors.black, children: [
                          CircleAvatar(
                            radius: 10,
                            backgroundImage:
                                NetworkImage(article.urlToImage.toString()),
                          ),
                          const SizedBox(width: 10),
                          Text(
                            article.author.toString(),
                            maxLines: 1,
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium!
                                .copyWith(color: Colors.white),
                          )
                        ]),
                        CustomTag(background: Colors.grey.shade200, children: [
                          const Icon(
                            Icons.timer,
                            color: Colors.grey,
                          ),
                          const SizedBox(width: 10),
                          Text(
                            "TIME",
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium!
                                .copyWith(color: Colors.black),
                          )
                        ]),
                        const SizedBox(
                          width: 10,
                        ),
                        CustomTag(
                          background: Colors.grey.shade200,
                          children: [
                            const Icon(
                              Icons.remove_red_eye,
                              color: Colors.grey,
                            ),
                            Text(
                              " VIEW ",
                              style: Theme.of(context)
                                  .textTheme
                                  .bodyMedium!
                                  .copyWith(color: Colors.black),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],

I tried expanding the different children but it was making it more wrong, i am expecting that they should be at their place and if the text is large than then text should come on the sec line/

A:
Incorrect use of Parent Data Widget in ListView  is caused when you use Expanded  but not in Row,Column or Flex

ListView(
  children: [
    HeadlineofArticle(article: article),
    Expanded(   <<< this is your error

An Expanded widget must be a descendant of a Row, Column, or Flex.
read here for detail: https://api.flutter.dev/flutter/widgets/Expanded-class.html
Solution: remove Expanded


text:
Q: LinkedIn API Suddenly Returning 405 Error One of our apps that uses LinkedIn Login, and has been working fine for a long time, is now suddenly broken, as of yesterday.  Most, but not all of our calls to the People endpoint return a 405 error.  Did something change for that endpoint?
I'm making a GET, just as the documentation says, and I'm getting back "(405) Method Not Allowed." from LinkedIn.  Here is the URL that I'm requesting:
https://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,headline,industry,summary,specialties,associations,honors,skills,interests,educations,phone-numbers,main-address,picture-url,public-profile-url,following,positions,three-current-positions,location,site-standard-profile-request)
Any help or any links to recent LinkedIn API changes would be appreciated.  I can't find any reference to any changes there in the last couple of days, but our app suddenly broke and we didn't change anything on our end.  Anyone?

A: LinkedIn made some unannounced changes yesterday which has broken their oAuth endpoint. They still haven't mentioned it of course.
You can see a workaround here:
POST https://www.linkedin.com/uas/oauth2/accessToken HTTP/1.1 results in Method Not Found on LinkedIn

A: We have solved this fix adding the request header "Expect" empty like this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:') );


text:
Q: JS split method causes 'is not a legal ECMA-262 octal constant' warning in FF I have string in js:
var str = "A(B|C)D"
and I want to split it by "(", ")", "|". I try to do it in this way:
str.split("\(|\)|\|");
which doesn't work (result is: Array [ "A(B|C)D" ])
Then I try to do it using regex:
str.split(/\(|\)|\|/);
which actually work as expected (result is: Array [ "A", "B", "C", "D" ]) but after that FF prints following message in logging console: "SyntaxError: 08 is not a legal ECMA-262 octal constant"

A: Try to use this code, please:
str.split(/[\(\)\|]/g);

Look here. May be you have any extension that produces this error?

A: It seems the error you are getting is unrelated to the split function specifically.
It might be what you are attempting to split is causing this bug.
From MDN

Decimal literals can start with a zero (0) followed by another decimal digit,  but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. Because this is not the case with 08 and 09, JavaScript warns about it.

You can see more about it on MDN: SyntaxError: "x" is not a legal ECMA-262 octal constant:


text:
Q: Need query to get function execution stats in SQL Server 2008 R2 Like below query, is there any query which can return the execution status of a function in SQL server using sys.dm_exec_?
SELECT TOP 1
    d.object_id,
    d.database_id,
    OBJECT_NAME(object_id,database_id) 'proc name',
    d.cached_time,d.last_execution_time, d.total_elapsed_time,
    (d.total_elapsed_time/d.execution_count)/1000 AS [avg_elapsed_time],
    d.last_elapsed_time/1000 as last_elapsed_time,
    d.execution_count,
    *
FROM
    sys.dm_exec_procedure_stats AS d
WHERE
    OBJECT_NAME(object_id, database_id) = 'ssp_StoredProcedureName'
ORDER BY
    d.Last_Execution_Time DESC

A: You can't get exact function execution stats in versions below SQL2016.But from SQLSERVER 2016,we have sys.dm_exec_function_stats.

Applies to: SQL Server (SQL Server 2016 Community Technology Preview
  3.2 (CTP 3.2) through current version), Azure SQL Database, Azure SQL Data Warehouse Public Preview.


text:
Q: Sorting and merge values of a python dict I got a problem with a dict I want to sort in python 3.5.
It looks like :
d = {'automate': <Routing.Route.Route object at 0x2b7f84835c18>,
    'index': <.Routing.Route.Route object at 0x2b7f8486e5c0>,
    'index_1': <Routing.Route.Route object at 0x2b7f8483d400>,
    'index_2': <Routing.Route.Route object at 0x2b7f84835f98>,
    'second': <Routing.Route.Route object at 0x2b7f8483d470>,
    'test_route_parameters': <Routing.Route.Route object at 0x2b7f8486e588>}

Where Route class has name, package_name attributes.
I want to print this dict like:
>> Package_name1:
     automate
     index
     index_1

   Package_name2:
     second
     index_2

   Package_name3:
     test_route_parameters

How can I sort my dict by package_name and print it to match the above output?
Have a good day and thank you.

A: This will do the trick:
{v.package_name:[k for k in d if d[k].package_name==v.package_name] for v in d.values()}

A: This should work. Loop through the dictionary and check if the package name in value is present in the sorted_dict. If not, add a list as value and package_name as key and then just append the keys to each package_name. Runs in O(n).
sorted_dict = {}
for key in d:
    if d[key] not in sorted_dict:
        sorted_dict[d[key].package_name] = []
sorted_dict[d[key].package_name].append(d[key])


text:
Q: Performing a Search is breaking layout When using the search bar to search profiles by first or last name the layout breaks. What I mean by the "layout breaks" is when performing a search if I delete characters from the input field the layout does not return to its original state, but rather it does not display profile images (please view the attachments). If I delete all the characters in the search input field and I hit the enter key the layout returns to its original state. What I would like to happen is if I delete all the characters in the search input field or hit enter the layout returns to its original state.

Search.js
import {useContext} from 'react'
import {ThemeContext} from './themeContext'

const Search = () => {
const {search, setSearch } = useContext(ThemeContext)

  const handleChange = event => {
    if (event.keyCode !== 44) {
      setSearch(event.target.value)
    } else {
      event.preventDefault()
      setSearch("")
    }
  }
    return (
          <>
              <form className="student-search-form">
                  <input type="text" className="student-search-input" value={search} onChange={handleChange} placeholder="Search by name"/>
              </form>
          </>

    )
}

export default Search

themeContext.js
import {useState, useEffect, createContext} from 'react'
import axios from 'axios'
const ThemeContext = createContext()

const ThemeContextProvider = props => {

  const [students, setStudents] = useState([])
  const [loading, setLoading] = useState(false)

  const [filter, setFilter] = useState([])
  const [search, setSearch] = useState('')

  useEffect(() => {
    const studentFil = students.filter(student =>
      student.firstName.includes(search) ||
      student.lastName.includes(search))

      setFilter(studentFil)
  },[students, search])

  useEffect(()=>{
    getStudents()
  },[])

  const getStudents = async () => {
    try {
          const res = await axios.get('https://api.hatchways.io/assessment/students')
          setStudents(res.data.students)
          setLoading(true)
    }
    catch (err) {
      console.log(err.message)
    }
  }

  return (
      <ThemeContext.Provider value={{students, loading, filter, search, setSearch}}>
          {props.children}
      </ThemeContext.Provider>
  )

}

Students.js
import { useState, useContext} from 'react'
import {ThemeContext} from './themeContext'
import Search from './Search'

const Students = () => {

  const {loading, filter} = useContext(ThemeContext)

  return (
    <>

        {loading &&

                   <Search />
                     {filter.map(student => {
                      return (
                     <>

{student.firstName} {student.lastName}

Email: {student.email}

Company: {student.company}

Skill: {student.skill}

Average: {student.average}%

                    </>
                     )
                  })}

              }

      </>
    );
  }

export default Students;

Styles.css:
@import url('https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;700&display=swap');

body {
  margin: 0;
  box-sizing: border-box;
  font-family: 'Raleway', sans-serif;
  font-size: 16px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: lightgray;

}

ul {
    padding: 0;
    list-style: none;
}

li {
  line-height: 1.5;
}

p {
  line-height: .8;
}

img {
  border: 1px solid #a9a9a9;
  border-radius: 50%;
   max-width: 100%;
   width: 7rem;
   margin-top: 4em;
}

button {
  cursor: pointer;
  background-color: transparent;
  border: none;
  font-size: 3rem;
  color: gray;
}

.student-profile-container {
  display: flex;
  justify-content: center;
  width: 800px;
  margin: 0 auto;
  margin-top: 2em;
  border: 2px #a9a9a9 solid;
  border-radius: 9px;
  background-color: #fff;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  border-top: 1px solid #a9a9a9;
  margin: 0;
  padding: 0 2rem;
  width: 700px;
}

.student-search-input {
  width: 100%;
  margin: 0 auto;
  padding: .7em 0;
  outline: none;
  border: none;
  text-align: left;
  font-size: 1.5rem;
}

.student-profile-image {
  width: 20%;
}

.student-profile-info {
  width: 70%;
}

.student-grades-expander {
margin-top: 2em;
padding-left: 3em;
margin-right:auto;
}


text:
Q: How to find the name/path of a parent batch file from within another batch file RUN, but not CALLed, by the parent? my goal is to have a general use batch file that is able to be run by name from within another  batch file, which will then do meta/introspective things with the parent batch file that ran it. In order to do this, I'm hoping I can identify the parent from within my general use file. I'm aware I can supply the name/path of the parent alongside the command as an argument when the parent runs my file, but to prevent dishonest reporting by the parent file, for aesthetic reasons, and also in the interest of exploring the functionality of batch in general, I would like to avoid doing this and leave all identification to be done by my script, if that is possible.
I've looked into WMIC, and I'm sure I can get the ParentProcessID of my script's cmd.exe instance when it runs, but I haven't found a way to do anything useful with it. I've messed with the (goto) trick, and I know how to get the name/path of the parent if the parent CALLs my script, but since I'm trying to RUN it (i.e. by its bare name as a command), the (goto) trick also hasn't done me any good, since it seems to all be one call stack.
although anyone who messes with batch should already know what I've attempted when I say these things, in the interest of fluffing up this post's content, here's how I'll use the (goto) trick to inspect changes to the call stack:
@ECHO OFF
:: TOPLEVEL.BAT, note I'm not calling my script
"MYSCRIPT.BAT"

@ECHO OFF
:: MYSCRIPT.BAT
SETLOCAL
SET "_SELF_=%~dpnx0"
(
  (goto) 2>NUL
  ECHO this is the scope I should be in: %~dpnx0
  CALL ECHO this is the scope I would break into: %%~dpnx0
  (goto) 2>NUL

  :: define variable that will be blank while still in nested scope
  CALL SET "_COMPLETE_=%%"

  IF NOT DEFINED _COMPLETE_ (
    :: go one scope deeper and recurse
    CALL "%_SELF_%"

  ) ELSE (
    :: back to baseline
    CALL "%ComSpec%" /c
  )
)
ENDLOCAL

anyway, any wizards out there know whether this is possible or how it could be done?

A: When chaining batchfiles there is very little info available from previous chains.
There is however the variable %cmdcmdline%.
Depending on the way the first batchfile is started, this variable may contain the name of the first started batchfile.
If manually started from the commandline it has no usefull info, but this can be silently changed to run with cmd/c (see chain0.cmd).
If started with the start-command or started from explorer or started from commandline with cmd/c it will contain the name of the first started batchfile in %cmdcmdline%.
chain0.cmd
@echo off
cls
echo this is: %~0
echo cmdcmdline=[%cmdcmdline%]

if "%comspec%" == %cmdcmdline% cmd /c %0 & exit /b

Chain1.cmd

chain1.cmd
@echo off
echo this is: %~0
echo cmdcmdline=[%cmdcmdline%]

Chain2.cmd

Chain2.cmd
@echo off
echo this is: %~0
echo cmdcmdline=[%cmdcmdline%]

pause


text:
Q: Orchard Projection Widget with pager issue I'm working on a website made with Orchard CMS. I put a Projection Widget on a page with a custom query and it works perfectly but if there is a pager on that page and I click to another page (not to the first) the Projection Widget becomes empty. So it shows result only on the first page of the pager.
Is this an Orchard bug or am I doing something wrong maybe? Any ideas?
Thanks!

A: You need to configure the pager on that widget to use a different pagination parameter.


text:
Q: Generating random Key firestore Im running a FIRESTORE database, and i want to create a random key with the same pattern as firestore does.
In the link i found the function that is called once i create a document
with: 'db.ref.add()' to generate the key in client side:
https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36
I need to do something like this:
let key = newId()
console.log(key)
db.ref().doc(key).set(data)

A: it is very easy to use the firestore uid generator:
const uid = admin.firestore().collection("tmp").doc().id

this would do the trick without requiring to save some data
but in your specific example: if you don't specify any key it will be auto-generated by firestore:
await admin.firestore().collection("MY COLLECTION").doc().set(data)

A: Looks like you can just use the .add method instead of auto generating a uuid on your own.
https://firebase.google.com/docs/firestore/manage-data/add-data
// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});


text:
Q: Change the center of jvectormap from EU to ASIA I want to change the center of jvectormap world_mill map from EU to ASIA. It is possible? If it is not, how can I create a custom world map with ASIA in the center?

A: Longitude is the geographic coordinate used to express the distance of a point east or west, relative to the Greenwich meridian or Prime meridian.
I think if you change this parameter, you need to position markers by pixel coordinates only, not by latitude and longitude (as stated on the jvectormap website).
To avoid this, if you absolutely need to have a world map with center in Asia, another possibility would be to do some math calculations to shift the longitude (for example to position markers by coordinates) with respect of the new meridian that will be origin of your "shifted" longitude.
To create a new map, you can use the open-source tool SVG-edit:
https://en.wikipedia.org/wiki/SVG-edit
Here you will find two step-by-step tutorial how to do a custom map:
http://anshumania.github.io/delhi-map/howtocreate.html
http://www.jaffredo.com/2012/tutoriel-jquery-creer-ses-propres-cartes-pour-jvectormap-et-jqvmap/

A: You can manipulate SVG map view (center, zoom and rotation) easily like explained here http://maps-on-blackboard.com/articles/can-you-rotate-and-pinch-the-svg-map/


text:
Q: KeyGenerator AES implementation not found in android I am new to android development and I tried to generate the secret key for encryption and decryption and store that key inside the key store.But I got the below error while the app was being run.
java.security.NoSuchAlgorithmException: KeyGenerator AES implementation not found
 at org.apache.harmony.security.fortress.Engine.notFound(Engine.java:190)
 at org.apache.harmony.security.fortress.Engine.getInstance(Engine.java:183)
 at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:164)
 at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:135)
 at com.example.lakshika.seureapp.codes.KeyStore.createSecretKey(KeyStore.java:56)
 at com.example.lakshika.seureapp.codes.KeyStore.<init>(KeyStore.java:37)

This is the code which I have implemented.
public class KeyStore{
private static final String ANDROID_KEY_STORE = "AndroidKeyStore";
private static String DEFAULT_KEY = "";
private java.security.KeyStore keystore;
private String TAG = "Key store";

@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.M)
public KeyStore(String alias) {
    this.DEFAULT_KEY = alias;
    Log.w(TAG,"start key store:"+ DEFAULT_KEY);
    loadKeystore();
    if (getSecretKey() == null) {
        createSecretKey();
    }
}

private void loadKeystore() {
    try {
        keystore = java.security.KeyStore.getInstance(ANDROID_KEY_STORE);
        keystore.load(null);
    } catch (IOException | NoSuchAlgorithmException |
            CertificateException | KeyStoreException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

@RequiresApi(api = Build.VERSION_CODES.M)
private void createSecretKey() {
    try {
        KeyGenerator keyGenerator = KeyGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_AES,
                        ANDROID_KEY_STORE);
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec
                .Builder(DEFAULT_KEY, KeyProperties.PURPOSE_ENCRYPT |
                KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .setUserAuthenticationRequired(true);
        keyGenerator.init(builder.build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

SecretKey getSecretKey() {
    try {
        return (SecretKey) keystore.getKey(DEFAULT_KEY, null);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        e.printStackTrace();
    }
    return null;
}

}
If anybody knows how to solve this error, please help me.Thank you.

A: AES/CBC/PKCS7Padding is available since Android 23, but you are executing on Android 5 (android 21), so AES can not be used in your device
See https://developer.android.com/training/articles/keystore.html#SupportedCiphers


text:
Q: find -printf work around I'm trying to use a script to call compare file size. Unfortunately the version of find on my mac does not support the -printf switch. Any suggestions?

A: You should consider install GNU find using homebrew.
To install homebrew you just need to type the following in your terminal:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then install findutils by typing:
brew install findutils

Then your find version will support the -printf and should be the latest:
$ find --version
find (GNU findutils) 4.4.2
, nc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
, o the extent permitted by law.

, nd Kevin Dalley.
Built using GNU gnulib version e5573b1bad88bfabcda181b9e0125fb0c52b7d3b
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS() CBO(level=0)

A: Use exec option with 'wc -c' for size in bytes or 'du' for the disk blocks:
$ find . -name bill\* -exec wc -c {} + 2>/dev/null
8496 ./bill
 341 ./bill.c
 274 ./bill.c~
9111 total
$ find . -name bill\* -exec du {} + 2>/dev/null
24  ./bill
8   ./bill.c
8   ./bill.c~


text:
Q: 'Calloc' could not allocate memory with kernelUD function I know, there was similar question asked a while ago ("'Calloc 'could not allocate memory" in 64-bit R), and I tried to ask over there, but I was deleted... although as I said in my question, I did try their solutions (updating plugins), but it didn't work for me. Sooo, let me try again :)
When I try to use kernelUD() function from adehabitatHR package, depending on h parameter value I get that error. It's working with h="href" parameter, but not with h="LSCV" (different smoothing parameter)
require(adehabitatHR)
BCLoc <- puechabonsp$relocs[, 1] #data comes with adehabitatHR
BC.href <- kernelUD(BCLoc, h="href") #works :)
BC.LSCV <- kernelUD(BCLoc, h="LSCV") #gets error :(

Error in .kernelUDs(SpatialPoints(x, proj4string = CRS(as.character(pfs1))),  :
  'Calloc' could not allocate memory (18446744071710095360 of 8 bytes)

any ideas?

A: I have exactly the same question. For what I've been able to learn, LSCV seems to perform poorly (or simply fail miserably) if the number of relocations is too large (Hemson et al 2005 Journal of Animal Ecology 2005. 74, 455–463). Mine is huge and at the beginning R session aborted when I tried to run the KDE with hLSCV, although all worked well with ref.
When I reduce the sample I got the error that you asked about. Reducing it further,  I started to get a new error:
In .kernelUDs(SpatialPoints(x, proj4string = CRS(as.character(pfs1))),  :
  The algorithm did not converge within the specified range of hlim:
  try to increase it

No matter how high I set him it did not converge. A possible solution for this is to add noise to the relocationswith the function "jitter" as explained here: https://ecosystems.psu.edu/research/labs/walter-lab/manual/home-range-estimation/link-to-pdf and here https://animov.faunalia.narkive.com/NnG9nLKl/again-kernelud-and-lscv
It did not work for me, though, but I hope this helps anyone


text:
Q: Hover over images to reveal text (centered vertically) This may seem like a standard question, but I'm after some 'best practice' here. Around the web (a good example is designspiration.net) you have sites that have images, that when hovered, reveal a block/alpha colour with text (usually a title, caption or number) positioned in the centre both horizontally and vertically.
In the past I've usually hacked my way through to achieve this effect, but it would be great to know the best and most effective/semantic way to do this (CSS? jQuery? Both?)
If you look at the designspiration landing page and hover over the images, you'll get the idea. Note these images don't have a fixed height.
Any implementation would be really appreciated (jsFiddle etc) and hopefully this'll help others.
Many thanks
Richard

A: Use vertical-allign: middle;!
http://jsfiddle.net/zR4kk/
You just have to make your container display:table
And your content display: table-cell
HTML

To look best, text should really be centered inside this div both vertically and horizontally.

CSS
.area {
  width: 300px;
  height: 300px;
  background: green;
  display:table;
    padding:5px;
}

.area p {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

A: For this particular case, the solution that designspiration uses is method 4 from this blog post: Vertical Centering with CSS.

        This will be centered


text:
Q: upsell.phtml in static block = Fatal error: Call to a member function getItems() on a non-object I'll show my category list in a static block

{{block type="catalog/product_list" category_id="488" template="catalog/product/list.phtml"}}

No problem. But now I'm try to use the upsell.phtml- Template with

{{block type="catalog/product_list" category_id="488" template="catalog/product/list/upsell.phtml"}}

and I'll get these PHP Error. I'm not a PHP-developer, can you help me?
Fatal error: Call to a member function getItems() on a non-object in /var/www/.../catalog/product/list/upsell.phtml on line 1

and there's the standard Magento Code (upsell.phtml)
<?php if(count($this->getItemCollection()->getItems())): ?>

I have no idea what's wrong?!

A: you can try below one

{{block type="catalog/product_list_upsell" category_id="488" template="catalog/product/list/upsell.phtml"}}

A: You are attempting to only change the template, not the block type. If you check the block Mage_Catalog_Model_Product_list you will see that there is no getItemCollection method on it, therefore this call will return null (or possibly an empty string, can't remember off the top of my head). This results in your template attempting to call getItems on that null/empty string. As @Keyul suggests the solution would be to use the block type that the upsell.phtml file is associated with, which is Mage_Catalog_Model_Product_List_Upsell. This block has the method getItemCollection and thus returns the collection expected in the template.
{{block type="catalog/product_list_upsell" category_id="488" template="catalog/product/list/upsell.phtml"}}


text:
Q: Postfix - Can't Receive External Mail i am using webmin control panel with postfix mail server and every thing working well i mean email message is encrypted and mail sending from my server to other companies like gmail also working very good but when some on try to send mail from externally i mean from any other company like gmail i did not receive emails on my admin@mydomain.com . but internally email receiving also working. i am using cloudflare service but i have fully configured my cloudflare dns records MX, A records . but still the problem alive. below is my server postfix main.cf file code
> smtpd_sasl_authenticated_header = yes smtp_header_checks =
> pcre:/etc/postfix/header_checks
> # Global Postfix configuration file. This file lists only a subset
> # of all parameters. For the syntax, and for a complete parameter
> # list, see the postconf(5) manual page (command: "man 5 postconf").
> #
> # For common configuration examples, see BASIC_CONFIGURATION_README
> # and STANDARD_CONFIGURATION_README. To find these documents, use
> # the command "postconf html_directory readme_directory", or go to
> # http://www.postfix.org/.
> #
> # For best results, change no more than 2-3 parameters at a time,
> # and test if Postfix still works after every change.
>
> # SOFT BOUNCE
> #
> # The soft_bounce parameter provides a limited safety net for
> # testing.  When soft_bounce is enabled, mail will remain queued that
> # would otherwise bounce. This parameter disables locally-generated
> # bounces, and prevents the SMTP server from rejecting mail permanently
> # (by changing 5xx replies into 4xx replies). However, soft_bounce
> # is no cure for address rewriting mistakes or mail routing mistakes.
> #
> #soft_bounce = no
>
> # LOCAL PATHNAME INFORMATION
> #
> # The queue_directory specifies the location of the Postfix queue.
> # This is also the root directory of Postfix daemons that run chrooted.
> # See the files in examples/chroot-setup for setting up Postfix chroot
> # environments on different UNIX systems.
> #
>
> # The command_directory parameter specifies the location of all
> # postXXX commands.
> # command_directory = /usr/sbin
>
> # The daemon_directory parameter specifies the location of all Postfix
> # daemon programs (i.e. programs listed in the master.cf file). This
> # directory must be owned by root.
> # daemon_directory = /usr/libexec/postfix
>
> # The data_directory parameter specifies the location of Postfix-writable
> # data files (caches, random numbers). This directory must be owned
> # by the mail_owner account (see below).
> # data_directory = /var/lib/postfix
>
> # QUEUE AND PROCESS OWNERSHIP
> #
> # The mail_owner parameter specifies the owner of the Postfix queue
> # and of most Postfix daemon processes.  Specify the name of a user
> # account THAT DOES NOT SHARE ITS USER OR GROUP ID WITH OTHER ACCOUNTS
> # AND THAT OWNS NO OTHER FILES OR PROCESSES ON THE SYSTEM.  In
> # particular, don't specify nobody or daemon. PLEASE USE A DEDICATED
> # USER.
> #
>
> # The default_privs parameter specifies the default rights used by
> # the local delivery agent for delivery to external file or command.
> # These rights are used in the absence of a recipient user context.
> # DO NOT SPECIFY A PRIVILEGED USER OR THE POSTFIX OWNER.
> #
> #default_privs = nobody
>
> # INTERNET HOST AND DOMAIN NAMES
> #
> # The myhostname parameter specifies the internet hostname of this
> # mail system. The default is to use the fully-qualified domain name
> # from gethostname(). $myhostname is used as a default value for many
> # other configuration parameters.
> #
> #myhostname = host.domain.tld
> #myhostname = virtual.domain.tld
>
> # The mydomain parameter specifies the local internet domain name.
> # The default is to use $myhostname minus the first component.
> # $mydomain is used as a default value for many other configuration
> # parameters.
> #
> #mydomain = domain.tld
>
> # SENDING MAIL
> #
> # The myorigin parameter specifies the domain that locally-posted
> # mail appears to come from. The default is to append $myhostname,
> # which is fine for small sites.  If you run a domain with multiple
> # machines, you should (1) change this to $mydomain and (2) set up
> # a domain-wide alias database that aliases each user to
> # user@that.users.mailhost.
> #
> # For the sake of consistency between sender and recipient addresses,
> # myorigin also specifies the default domain name that is appended
> # to recipient addresses that have no @domain part.
> #
> #myorigin = $myhostname
> #myorigin = $mydomain
>
> # RECEIVING MAIL
>
> # The inet_interfaces parameter specifies the network interface
> # addresses that this mail system receives mail on.  By default,
> # the software claims all active interfaces on the machine. The
> # parameter also controls delivery of mail to user@[ip.address].
> #
> # See also the proxy_interfaces parameter, for network addresses that
> # are forwarded to us via a proxy or network address translator.
> #
> # Note: you need to stop/start Postfix when this parameter changes.
> # inet_interfaces = all
> #inet_interfaces = $myhostname
> #inet_interfaces = $myhostname, localhost
>
> # Enable IPv4, and IPv6 if supported inet_protocols = all
>
> # The proxy_interfaces parameter specifies the network interface
> # addresses that this mail system receives mail on by way of a
> # proxy or network address translation unit. This setting extends
> # the address list specified with the inet_interfaces parameter.
> #
> # You must specify your proxy/NAT addresses when your system is a
> # backup MX host for other domains, otherwise mail delivery loops
> # will happen when the primary MX host is down.
> #
> #proxy_interfaces =
> #proxy_interfaces = 1.2.3.4
>
> # The mydestination parameter specifies the list of domains that this
> # machine considers itself the final destination for.
> #
> # These domains are routed to the delivery agent specified with the
> # local_transport parameter setting. By default, that is the UNIX
> # compatible delivery agent that lookups all recipients in /etc/passwd
> # and /etc/aliases or their equivalent.
> #
> # The default is $myhostname + localhost.$mydomain.  On a mail domain
> # gateway, you should also include $mydomain.
> #
> # Do not specify the names of virtual domains - those domains are
> # specified elsewhere (see VIRTUAL_README).
> #
> # Do not specify the names of domains that this machine is backup MX
> # host for. Specify those names via the relay_domains settings for
> # the SMTP server, or use permit_mx_backup if you are lazy (see
> # STANDARD_CONFIGURATION_README).
> #
> # The local machine is always the final destination for mail addressed
> # to user@[the.net.work.address] of an interface that the mail system
> # receives mail on (see the inet_interfaces parameter).
> #
> # Specify a list of host or domain names, /file/name or type:table
> # patterns, separated by commas and/or whitespace. A /file/name
> # pattern is replaced by its contents; a type:table is matched when
> # a name matches a lookup key (the right-hand side is ignored).
> # Continue long lines by starting the next line with whitespace.
> #
> # See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS".
> #
> #mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
> #mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain,
> #   mail.$mydomain, www.$mydomain, ftp.$mydomain
>
> # REJECTING MAIL FOR UNKNOWN LOCAL USERS
> #
> # The local_recipient_maps parameter specifies optional lookup tables
> # with all names or addresses of users that are local with respect
> # to $mydestination, $inet_interfaces or $proxy_interfaces.
> #
> # If this parameter is defined, then the SMTP server will reject
> # mail for unknown local users. This parameter is defined by default.
> #
> # To turn off local recipient checking in the SMTP server, specify
> # local_recipient_maps = (i.e. empty).
> #
> # The default setting assumes that you use the default Postfix local
> # delivery agent for local delivery. You need to update the
> # local_recipient_maps setting if:
> #
> # - You define $mydestination domain recipients in files other than
> #   /etc/passwd, /etc/aliases, or the $virtual_alias_maps files.
> #   For example, you define $mydestination domain recipients in
> #   the $virtual_mailbox_maps files.
> #
> # - You redefine the local delivery agent in master.cf.
> #
> # - You redefine the "local_transport" setting in main.cf.
> #
> # - You use the "luser_relay", "mailbox_transport", or "fallback_transport"
> #   feature of the Postfix local delivery agent (see local(8)).
> #
> # Details are described in the LOCAL_RECIPIENT_README file.
> #
> # Beware: if the Postfix SMTP server runs chrooted, you probably have
> # to access the passwd file via the proxymap service, in order to
> # overcome chroot restrictions. The alternative, having a copy of
> # the system passwd file in the chroot jail is just not practical.
> #
> # The right-hand side of the lookup tables is conveniently ignored.
> # In the left-hand side, specify a bare username, an @domain.tld
> # wild-card, or specify a user@domain.tld address.
> #
> #local_recipient_maps = unix:passwd.byname $alias_maps
> #local_recipient_maps = proxy:unix:passwd.byname $alias_maps
> #local_recipient_maps =
>
> # The unknown_local_recipient_reject_code specifies the SMTP server
> # response code when a recipient domain matches $mydestination or
> # ${proxy,inet}_interfaces, while $local_recipient_maps is non-empty
> # and the recipient address or address local-part is not found.
> #
> # The default setting is 550 (reject mail) but it is safer to start
> # with 450 (try again later) until you are certain that your
> # local_recipient_maps settings are OK.
> # unknown_local_recipient_reject_code = 550
>
> # TRUST AND RELAY CONTROL
>
> # The mynetworks parameter specifies the list of "trusted" SMTP
> # clients that have more privileges than "strangers".
> #
> # In particular, "trusted" SMTP clients are allowed to relay mail
> # through Postfix.  See the smtpd_recipient_restrictions parameter
> # in postconf(5).
> #
> # You can specify the list of "trusted" network addresses by hand
> # or you can let Postfix do it for you (which is the default).
> #
> # By default (mynetworks_style = subnet), Postfix "trusts" SMTP
> # clients in the same IP subnetworks as the local machine.
> # On Linux, this does works correctly only with interfaces specified
> # with the "ifconfig" command.
> #
> # Specify "mynetworks_style = class" when Postfix should "trust" SMTP
> # clients in the same IP class A/B/C networks as the local machine.
> # Don't do this with a dialup site - it would cause Postfix to "trust"
> # your entire provider's network.  Instead, specify an explicit
> # mynetworks list by hand, as described below.
> #
> # Specify "mynetworks_style = host" when Postfix should "trust"
> # only the local machine.
> #
> #mynetworks_style = class
> #mynetworks_style = subnet
> #mynetworks_style = host
>
> # Alternatively, you can specify the mynetworks list by hand, in
> # which case Postfix ignores the mynetworks_style setting.
> #
> # Specify an explicit list of network/netmask patterns, where the
> # mask specifies the number of bits in the network part of a host
> # address.
> #
> # You can also specify the absolute pathname of a pattern file instead
> # of listing the patterns here. Specify type:table for table-based lookups
> # (the value on the table right-hand side is not used).
> #
> #mynetworks = 168.100.189.0/28, 127.0.0.0/8
> #mynetworks = $config_directory/mynetworks
> #mynetworks = hash:/etc/postfix/network_table
>
> # The relay_domains parameter restricts what destinations this system will
> # relay mail to.  See the smtpd_recipient_restrictions description in
> # postconf(5) for detailed information.
> #
> # By default, Postfix relays mail
> # - from "trusted" clients (IP address matches $mynetworks) to any destination,
> # - from "untrusted" clients to destinations that match $relay_domains or
> #   subdomains thereof, except addresses with sender-specified routing.
> # The default relay_domains value is $mydestination.
> #
> # In addition to the above, the Postfix SMTP server by default accepts mail
> # that Postfix is final destination for:
> # - destinations that match $inet_interfaces or $proxy_interfaces,
> # - destinations that match $mydestination
> # - destinations that match $virtual_alias_domains,
> # - destinations that match $virtual_mailbox_domains.
> # These destinations do not need to be listed in $relay_domains.
> #
> # Specify a list of hosts or domains, /file/name patterns or type:name
> # lookup tables, separated by commas and/or whitespace.  Continue
> # long lines by starting the next line with whitespace. A file name
> # is replaced by its contents; a type:name table is matched when a
> # (parent) domain appears as lookup key.
> #
> # NOTE: Postfix will not automatically forward mail for domains that
> # list this system as their primary or backup MX host. See the
> # permit_mx_backup restriction description in postconf(5).
> #
> #relay_domains = $mydestination
>
> # INTERNET OR INTRANET
>
> # The relayhost parameter specifies the default host to send mail to
> # when no entry is matched in the optional transport(5) table. When
> # no relayhost is given, mail is routed directly to the destination.
> #
> # On an intranet, specify the organizational domain name. If your
> # internal DNS uses no MX records, specify the name of the intranet
> # gateway host instead.
> #
> # In the case of SMTP, specify a domain, host, host:port, [host]:port,
> # [address] or [address]:port; the form [host] turns off MX lookups.
> #
> # If you're connected via UUCP, see also the default_transport parameter.
> #
> #relayhost = $mydomain
> #relayhost = [gateway.my.domain]
> #relayhost = [mailserver.isp.tld]
> #relayhost = uucphost
> #relayhost = [an.ip.add.ress]
> # REJECTING UNKNOWN RELAY USERS
> #
> # The relay_recipient_maps parameter specifies optional lookup tables
> # with all addresses in the domains that match $relay_domains.
> #
> # If this parameter is defined, then the SMTP server will reject
> # mail for unknown relay users. This feature is off by default.
> #
> # The right-hand side of the lookup tables is conveniently ignored.
> # In the left-hand side, specify an @domain.tld wild-card, or specify
> # a user@domain.tld address.
> #
> #relay_recipient_maps = hash:/etc/postfix/relay_recipients
>
> # INPUT RATE CONTROL
> #
> # The in_flow_delay configuration parameter implements mail input
> # flow control. This feature is turned on by default, although it
> # still needs further development (it's disabled on SCO UNIX due
> # to an SCO bug).
> #
> # A Postfix process will pause for $in_flow_delay seconds before
> # accepting a new message, when the message arrival rate exceeds the
> # message delivery rate. With the default 100 SMTP server process
> # limit, this limits the mail inflow to 100 messages a second more
> # than the number of messages delivered per second.
> #
> # Specify 0 to disable the feature. Valid delays are 0..10.
> #
> #in_flow_delay = 1s
>
> # ADDRESS REWRITING
> #
> # The ADDRESS_REWRITING_README document gives information about
> # address masquerading or other forms of address rewriting including
> # username->Firstname.Lastname mapping.
>
> # ADDRESS REDIRECTION (VIRTUAL DOMAIN)
> #
> # The VIRTUAL_README document gives information about the many forms
> # of domain hosting that Postfix supports.
>
> # "USER HAS MOVED" BOUNCE MESSAGES
> #
> # See the discussion in the ADDRESS_REWRITING_README document.
>
> # TRANSPORT MAP
> #
> # See the discussion in the ADDRESS_REWRITING_README document.
>
> # ALIAS DATABASE
> #
> # The alias_maps parameter specifies the list of alias databases used
> # by the local delivery agent. The default list is system dependent.
> #
> # On systems with NIS, the default is to search the local alias
> # database, then the NIS alias database. See aliases(5) for syntax
> # details.
> #
> # If you change the alias database, run "postalias /etc/aliases" (or
> # wherever your system stores the mail alias file), or simply run
> # "newaliases" to build the necessary DBM or DB file.
> #
> # It will take a minute or so before changes become visible.  Use
> # "postfix reload" to eliminate the delay.
> #
> #alias_maps = dbm:/etc/aliases alias_maps = hash:/etc/aliases
> #alias_maps = hash:/etc/aliases, nis:mail.aliases
> #alias_maps = netinfo:/aliases
>
> # The alias_database parameter specifies the alias database(s) that
> # are built with "newaliases" or "sendmail -bi".  This is a separate
> # configuration parameter, because alias_maps (see above) may specify
> # tables that are not necessarily all under control by Postfix.
> #
> #alias_database = dbm:/etc/aliases
> #alias_database = dbm:/etc/mail/aliases alias_database = hash:/etc/aliases
> #alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases
>
> # ADDRESS EXTENSIONS (e.g., user+foo)
> #
> # The recipient_delimiter parameter specifies the separator between
> # user names and address extensions (user+foo). See canonical(5),
> # local(8), relocated(5) and virtual(5) for the effects this has on
> # aliases, canonical, virtual, relocated and .forward file lookups.
> # Basically, the software tries user+foo and .forward+foo before
> # trying user and .forward.
> #
> #recipient_delimiter = +
>
> # DELIVERY TO MAILBOX
> #
> # The home_mailbox parameter specifies the optional pathname of a
> # mailbox file relative to a user's home directory. The default
> # mailbox file is /var/spool/mail/user or /var/mail/user.  Specify
> # "Maildir/" for qmail-style delivery (the / is required).
> #
> #home_mailbox = Mailbox
> #home_mailbox = Maildir/
>
> # The mail_spool_directory parameter specifies the directory where
> # UNIX-style mailboxes are kept. The default setting depends on the
> # system type.
> #
> #mail_spool_directory = /var/mail
> #mail_spool_directory = /var/spool/mail
>
> # The mailbox_command parameter specifies the optional external
> # command to use instead of mailbox delivery. The command is run as
> # the recipient with proper HOME, SHELL and LOGNAME environment settings.
> # Exception:  delivery for root is done as $default_user.
> #
> # Other environment variables of interest: USER (recipient username),
> # EXTENSION (address extension), DOMAIN (domain part of address),
> # and LOCAL (the address localpart).
> #
> # Unlike other Postfix configuration parameters, the mailbox_command
> # parameter is not subjected to $parameter substitutions. This is to
> # make it easier to specify shell syntax (see example below).
> #
> # Avoid shell meta characters because they will force Postfix to run
> # an expensive shell process. Procmail alone is expensive enough.
> #
> # IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN
> # ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER.
> #
> #mailbox_command = /some/where/procmail
> #mailbox_command = /some/where/procmail -a "$EXTENSION"
>
> # The mailbox_transport specifies the optional transport in master.cf
> # to use after processing aliases and .forward files. This parameter
> # has precedence over the mailbox_command, fallback_transport and
> # luser_relay parameters.
> #
> # Specify a string of the form transport:nexthop, where transport is
> # the name of a mail delivery transport defined in master.cf.  The
> # :nexthop part is optional. For more details see the sample transport
> # configuration file.
> #
> # NOTE: if you use this feature for accounts not in the UNIX password
> # file, then you must update the "local_recipient_maps" setting in
> # the main.cf file, otherwise the SMTP server will reject mail for
> # non-UNIX accounts with "User unknown in local recipient table".
> #
> # Cyrus IMAP over LMTP. Specify ``lmtpunix      cmd="lmtpd"
> # listen="/var/imap/socket/lmtp" prefork=0'' in cyrus.conf.
> #mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp
>
> # If using the cyrus-imapd IMAP server deliver local mail to the IMAP
> # server using LMTP (Local Mail Transport Protocol), this is prefered
> # over the older cyrus deliver program by setting the
> # mailbox_transport as below:
> #
> # mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp
> #
> # The efficiency of LMTP delivery for cyrus-imapd can be enhanced via
> # these settings.
> #
> # local_destination_recipient_limit = 300
> # local_destination_concurrency_limit = 5
> #
> # Of course you should adjust these settings as appropriate for the
> # capacity of the hardware you are using. The recipient limit setting
> # can be used to take advantage of the single instance message store
> # capability of Cyrus. The concurrency limit can be used to control
> # how many simultaneous LMTP sessions will be permitted to the Cyrus
> # message store.
> #
> # Cyrus IMAP via command line. Uncomment the "cyrus...pipe" and
> # subsequent line in master.cf.
> #mailbox_transport = cyrus
>
> # The fallback_transport specifies the optional transport in master.cf
> # to use for recipients that are not found in the UNIX passwd database.
> # This parameter has precedence over the luser_relay parameter.
> #
> # Specify a string of the form transport:nexthop, where transport is
> # the name of a mail delivery transport defined in master.cf.  The
> # :nexthop part is optional. For more details see the sample transport
> # configuration file.
> #
> # NOTE: if you use this feature for accounts not in the UNIX password
> # file, then you must update the "local_recipient_maps" setting in
> # the main.cf file, otherwise the SMTP server will reject mail for
> # non-UNIX accounts with "User unknown in local recipient table".
>
> #
> # For details, see "man header_checks".
> #
> #header_checks = regexp:/etc/postfix/header_checks header_checks = regexp:/etc/postfix/header_checks
> # FAST ETRN SERVICE
> #
> # Postfix maintains per-destination logfiles with information about
> # deferred mail, so that mail can be flushed quickly with the SMTP
> # "ETRN domain.tld" command, or by executing "sendmail -qRdomain.tld".
> # See the ETRN_README document for a detailed description.
> #
> # The fast_flush_domains parameter controls what destinations are
> # eligible for this service. By default, they are all domains that
> # this server is willing to relay mail to.
> #
> #fast_flush_domains = $relay_domains
>
> # SHOW SOFTWARE VERSION OR NOT
> #
> # The smtpd_banner parameter specifies the text that follows the 220
> # code in the SMTP server's greeting banner. Some people like to see
> # the mail version advertised. By default, Postfix shows no version.
> #
> # You MUST specify $myhostname at the start of the text. That is an
> # RFC requirement. Postfix itself does not care.
> #
> #smtpd_banner = $myhostname ESMTP $mail_name
> #smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
>
> # PARALLEL DELIVERY TO THE SAME DESTINATION
> #
> # How many parallel deliveries to the same user or domain? With local
> # delivery, it does not make sense to do massively parallel delivery
> # to the same user, because mailbox updates must happen sequentially,
> # and expensive pipelines in .forward files can cause disasters when
> # too many are run at the same time. With SMTP deliveries, 10
> # simultaneous connections to the same domain could be sufficient to
> # raise eyebrows.
> #
> # Each message delivery transport has its XXX_destination_concurrency_limit
> # parameter.  The default is $default_destination_concurrency_limit for
> # most delivery transports. For the local delivery agent the default is 2.
>
> #local_destination_concurrency_limit = 2
> #default_destination_concurrency_limit = 20
>
> # DEBUGGING CONTROL
> #
> # The debug_peer_level parameter specifies the increment in verbose
> # logging level when an SMTP client or server host name or address
> # matches a pattern in the debug_peer_list parameter.
> # debug_peer_level = 2
>
>
> debugger_command =
>      PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
>      ddd $daemon_directory/$process_name $process_id & sleep 5
>
>
>
> # sample_directory: The location of the Postfix sample configuration files.
> # This parameter is obsolete as of Postfix 2.1.
> # sample_directory = /usr/share/doc/postfix-2.10.1/samples
>
> # readme_directory: The location of the Postfix README files.
> # readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES virtual_alias_maps = hash:/etc/postfix/virtual sender_bcc_maps =
> hash:/etc/postfix/bcc mailbox_command = /usr/bin/procmail-wrapper -o
> -a $DOMAIN -d $LOGNAME home_mailbox = Maildir/ smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yes smtpd_recipient_restrictions = permit_mynetworks permit_sasl_authenticated permit_inet_interfaces
> reject_unknown_client reject_unauth_destination mailbox_size_limit = 0
> allow_percent_hack = no smtpd_use_tls = yes
>
> smtp_header_checks = pcre:/etc/postfix/smtp_header_checks
> smtpd_delay_reject = no smtp_sasl_password_maps =
> hash:/etc/postfix/smtp_sasl_password_map
>
> smtpd_tls_security_level = may smtp_tls_security_level = may
> smtp_tls_loglevel = 1 smtpd_tls_loglevel = 1myorigin = $mydomain
> mydestination = $myhostname, localhost.$mydomain, $mydomain

A: issue has been resolved when i turn of TSL from my webmin control panel and now emails sending and receiving function work correctly.


text:
Q: get a value with jq by matching one of parent value from a variable I have JSON data as below, in services.json
{
"checkout-serviceA":{"prId":6644,"Sourcebranch":"","HFX":false,"IS_CR":"Yes"},
"checkout-serviceB":{"prId":15826,"Sourcebranch":"","HFX":false,"IS_CR": "no"},
"checkout-toggle":{"prId":8963,"Sourcebranch":"","HFX":true,"IS_CR": "Yes"},
"checkout-res":{"prId":1104,"Sourcebranch":"","HFX":false,"IS_CR": "Yes"}
}

I have a variable eg $PRID that contains prID value  already.
I want to pass this to jq and fetch or get an output of IS_CR value for the respective prID.
I tried
jq --arg v "$PRID" '.[] | select(.prId == $v).IS_CR' services.json
&
jq --arg v "$PRID" 'to_entries | map(select(.value.prId == $v))[0].value.IS_CR' services.json
but none worked as it gives null or nothing returns.
kindly help on this

A: --arg creates a string variable, but your prId properties are numbers (6644 != "6644").
Use --argjson instead:
jq --argjson v "$PRID" '.[] | select(.prId == $v).IS_CR' services.json

A: Use:
jq '.[] | select(.prId == '"$PRID"') | .IS_CR' services.json
Output:
# PRID=6644
# cat services.json
{
"checkout-serviceA":{"prId":6644,"Sourcebranch":"","HFX":false,"IS_CR":"Yes"},
"checkout-serviceB":{"prId":15826,"Sourcebranch":"","HFX":false,"IS_CR": "no"},
"checkout-toggle":{"prId":8963,"Sourcebranch":"","HFX":true,"IS_CR": "Yes"},
"checkout-res":{"prId":1104,"Sourcebranch":"","HFX":false,"IS_CR": "Yes"}
}
# jq '.[] | select(.prId == '"$PRID"') | .IS_CR' services.json
"Yes"


text:
Q: Django 1.5 extend admin/change_form.html object tools I'm new to Django but I've been really enjoying it.  But occasionally I seem to run into places where I just don't seem to get things correct.   So, I'm asking for some help and guidance.
I'm trying to extend the object-tools for one of my models so I can have a Print button next to History.
My templates is as follows:
project/app/templates/admin/

I'm successfully extending base_site.html with no issues.
project/app/templates/admin/base_site.html

However, when I add change_form.html like so:
project/app/templates/admin/change_form.html

With the following:
{% extends 'admin/change_form.html' %}

{% block object-tools %}
    One
    Two
{% endblock %}

I get an exception: maximum recursion depth exceeded while calling a Python object
This seems like I'm missing something quite basic.
Things that I've tried:

*

*Many variations of the {% block %}

*extending base_site, base etc ...

*adding /model as part of the path (project/app/templates/admin/model/change_form.html)

I'm confused and unsuccessful.
P.S.: I'm also using a bootstrap theme from here http://riccardo.forina.me/bootstrap-your-django-admin-in-3-minutes/ but for the purposes of this problem I'm currently not using it.

A: The problem is that admin/change_form.html in your {% extend %} block is getting resolved as project/app/templates/admin/change_form.html.
One solution is to create a subdirectory of templates named for your app - possibly project/templates/admin/app/change_form.html.

In order to override one or more of them, first create an admin directory in your project's templates directory. This can be any of the directories you specified in TEMPLATE_DIRS.
Within this admin directory, create sub-directories named after your app.

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template

A: That's because you're extending the template with itself. What I do is put my custom admin templates in templates/admin. Then in that same folder I symlink to the django admin folder (templates/admin/admin).
So my extends looks like:
 {% extends 'admin/admin/change_form.html' %}

Make sure you also override index.html if you want to go down that path.

A: The best way to do this that I have found is to use '..' to go up a couple of directories, then go back down into directories that should only be found in the Django code base.
As the Django templates are in something like "django/contrib/admin/templates/admin", I found that this worked me:
{% extends "../../admin/templates/admin/change_form.html" %}

If that still causes a clash with some other structure you have, you could go further:
{% extends "../../../contrib/admin/templates/admin/change_form.html" %}

or even:
{% extends "../../../../django/contrib/admin/templates/admin/change_form.html" %}

Although it is a little hacky, at least by doing the above you don't have to use some other technique that involves copying the django source or setting up a symlink.


text:
Q: multiple pointers in SQLite I am trying to re-write a dictionary program in python(3.X). I have been using JSON but thought it could be fun to try my hand at SQLlite. My question is:
I have:

*

*a word

*a list of sentences using the word

*a list of synonyms

*a list of antonyms

what is the the cleanest way to organise the data using SQLite3?
what I thought was to one table with unique id's for the 'val and example' and then create new entries for synonyms and antonyms if they do not yet exist.
ValId  Val        Eaxmples
1      'hot'      'the water is hot\n she's hot\n'
2      'warm'     '...'
3      'cold'     '...'
4      'freezing' '...'

but then how would I create a table that could point back to multiple id's?
for example 'hot' points to 2 as a synonym and 3 , 4 as antonyms. How would I create multiple ponters, do I have to put them in a sting and then parse them, as I do not know how may synonyms or antonyms might be created.
LinksID  ValID SynIDs AntsIds
   1        1     2      3,4

A: I would create two separate tables, one for synonyms and one for antonyms where you have FOREIGN KEYS to reference your words:
CREATE TABLE synonym (
    SynID INTEGER,
    WordID1 INTEGER,
    WordID2 INTEGER,
    FOREIGN KEY (WordID1) REFERENCES word(ValID),
    FOREIGN KEY (WordID2) REFERENCES word(ValID)
);

CREATE TABLE antonym (
    AntID INTEGER,
    WordID1 INTEGER,
    WordID2 INTEGER,
    FOREIGN KEY (WordID1) REFERENCES word(ValID),
    FOREIGN KEY (WordID2) REFERENCES word(ValID)
);

Then you don't have to worry about having an unknown number of synonyms and antonyms for each word. You would then get the following structure:
Your word table:
ValId  Val        Eaxmples
1      'hot'      'the water is hot\n she's hot\n'
2      'warm'     '...'
3      'cold'     '...'
4      'freezing' '...'

Your synonym table:
SynID  WordID1  WordID2
1      1        2
2      3        4

And your antonym table:
AntID  WordID1  WordID2
1      1        3
2      1        4
3      2        3
4      2        4


text:
Q: Varistor equivalent I am repairing an old Marantz stereo amplifier and have come across a varistor MV11Y that appears to be the issue.
Is anyone able to advise/send me the data sheet for this varistor or perhaps let me know an equivalent part?

A: This Ohimuzi MV-11Y is used for temperature-compensated biasing. It consists of one or more diodes in series (I think just two for this one).
They aren't produced anymore, but sometimes seen on Ebay et al. at very steep prices.
I have no idea about the specs, but it is often replaced by one or more 1N4148s or other diodes in series (two for this one) by the audio equipment restauration people.
Also see "What can I use to replace an SV-04F bias diode?" for discussion of a similar component. You could also try audio repair sites for more information.

A: I had the same problem with a Harman Kardon amplifier, so, just in case still works: https://www.digikey.com/en/products/detail/nte-electronics-inc/NTE605A/13968207?s=N4IgTCBcDaIHIBUCiA2ADAVgIIgLoF8g


text:
Q: Is there any good substitute for BuildURLFromExpression I am using MVC ASP 1.0 , how can i acheive the functionality done by BuildURLFromExpression method ? basically i am trying to get image from Controller
thanks

A: return(new FileResult(pathtoimage, "image/jpeg"));
you can also do it with bytes to image, pdf etc


text:
Q: How to enable/install HTTP/2 on Virtualmin in CentOS7 I have Virtualmin installed on my CentOS7 server and few websites are currently running on this server. There's no separate Apache installation because it is using Virtualmin. However I need to install / enable HTTP/2 on my server but current resources on the internet are not helpful enough to learn how to do this since I have a Virtualmin installation on which few sites are hosted. How can I do this?

A: HTTP/2 support was only added with Apache 2.4.17, therefore the only way to make it work on CentOS 7 is to rebuild it manually. OpenSSL version 1.0.2 is already available with CentOS 7 though.
Perhaps the easiest way would be is to upgrade to the distro that already ships needed version of Apache.
I cannot recommend CentOS 8 due to recent events, however Ubuntu 20.04 LTS and Debian 10 are both supported with Virtualmin and have latest versions of Apache. In the future we will support any 1:1 compatible forks/clones of RHEL; recently we fixed RHEL 8 support as well and CentOS 8 Stream is also supported.


text:
Q: Numpy filter to smooth out zero-regions I have a 2D numpy array of ints 0 and greater, where the values represent region labels. For example,
array([[9, 9, 9, 0, 0, 0, 0, 1, 1, 1],
       [9, 9, 9, 9, 0, 7, 1, 1, 1, 1],
       [9, 9, 9, 9, 0, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 0, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 0, 2, 2, 2, 1, 1],
       [4, 4, 4, 4, 0, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 0, 0, 0, 0, 0, 0],
       [4, 6, 6, 4, 0, 0, 0, 0, 0, 0],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]])

I would like the indices equal to 0 (i.e. zero-regions) to take on the value most-common in their neighborhood. The operation would essentially close the zero-regions. I've tried multiple variations of dilation, erosion, grey-closing, and other morphology operations, but I cannot completely eliminate the zero-regions (without awkwardly blending the other regions). A decent approach could be to define a kernel that convolves only over the zeros, and sets the value with the most common label in the filter area. I'm unsure how to implement this though.

A: One vectorized approach is proposed here. Steps are :

*

*Get kernel sized 2D sliding windows, leading to 4D array. We can use
skimage's view_as_windows to get those as view and thus avoid creating
any extra memory for this.

*Select the windows which are centered at zeros by indexing into the 4D array. This forces a copy. But assuming number of zeros is a relatively smaller number than the total number of elements in input array, this should be okay.

*For each of those selected windows, offset each window with a proper offset with the idea of using np.bincount to perform counting. Thus, use bincount and get the max count excluding the zeros. The argmax for the max count should be our guy!
Here's the implementation covering those steps -
from skimage.util import view_as_windows as viewW

def fill_zero_regions(a, kernel_size=3):
    hk = kernel_size//2 # half_kernel_size

    a4D = viewW(a, (kernel_size,kernel_size))
    sliced_a = a[hk:-hk,hk:-hk]
    zeros_mask = sliced_a==0
    zero_neighs = a4D[zeros_mask].reshape(-1,kernel_size**2)
    n = len(zero_neighs) # num_zeros

    scale = zero_neighs.max()+1
    zno = zero_neighs + scale*np.arange(n)[:,None] # zero_neighs_offsetted

    count = np.bincount(zno.ravel(), minlength=n*scale).reshape(n,-1)
    modevals = count[:,1:].argmax(1)+1
    sliced_a[zeros_mask] = modevals
    return a

Sample run -
In [23]: a
Out[23]:
array([[9, 9, 9, 0, 0, 0, 0, 1, 1, 1],
       [9, 9, 9, 9, 0, 7, 1, 1, 1, 1],
       [9, 9, 9, 9, 0, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 0, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 0, 2, 2, 2, 1, 1],
       [4, 4, 4, 4, 0, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 0, 0, 0, 0, 0, 0],
       [4, 6, 6, 4, 0, 0, 0, 0, 0, 0],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]])

In [24]: fill_zero_regions(a)
Out[24]:
array([[9, 9, 9, 0, 0, 0, 0, 1, 1, 1],
       [9, 9, 9, 9, 9, 7, 1, 1, 1, 1],
       [9, 9, 9, 9, 2, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 2, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 2, 2, 2, 2, 1, 1],
       [4, 4, 4, 4, 2, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 4, 2, 2, 2, 1, 0],
       [4, 6, 6, 4, 4, 5, 5, 5, 5, 0],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]])

As seen, we are not solving for the boundary cases. If needed to do, use a zero-padded array as the input array, something like this : np.pad(a, (k//2,k//2), 'constant'), with k as the kernel size (=3 for the sample).

A: A possible solution based on the convolve idea
from scipy import stats
ar = #Your np array
blank = np.zeros(ar.shape)
#Size to search in for mode values
window_size = 3

for x,y in np.array(np.where(ar == 0)).T:
    window = ar[max(x-window_size,0):x+window_size,max(0,y-window_size):y+window_size]
    oneD = window.flatten()

    #fill blank array with modal value
    blank[x,y] = stats.mode(oneD[oneD != 0])[0]

#fill in the zeros
print ar + blank

Im not sure if avoiding a loop is possible here

A: Here's a working solution using Numba, which I haven't profiled but should be pretty fast:
import numba
@numba.njit
def nn(arr):
    res = arr.copy()
    zeros = np.where(arr == 0)
    for n in range(len(zeros[0])):
        i = zeros[0][n]
        j = zeros[1][n]
        left = max(i-1, 0)
        right = min(i+2, arr.shape[1])
        top = max(j-1, 0)
        bottom = min(j+2, arr.shape[0])
        area = arr[left:right,top:bottom].ravel()
        counts = np.bincount(area[area != 0])
        res[i,j] = np.argmax(counts)
    return res

It produces:
array([[9, 9, 9, 9, 7, 1, 1, 1, 1, 1],
       [9, 9, 9, 9, 9, 7, 1, 1, 1, 1],
       [9, 9, 9, 9, 2, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 2, 2, 2, 1, 1, 1],
       [9, 9, 9, 8, 2, 2, 2, 2, 1, 1],
       [4, 4, 4, 4, 2, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 4, 2, 2, 2, 1, 1],
       [4, 6, 6, 4, 4, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5],
       [4, 4, 4, 4, 5, 5, 5, 5, 5, 5]])

The kernel size is 3x3 here, as defined by subtracting 1 and adding 2 to i and j (adding 2 because Python slices take one-past-the-end, e.g. [0:3] gives you 3 elements).  Boundary conditions are handled by min and max.
Credit for the bincount idea: https://stackoverflow.com/a/6252400/4323


text:
Q: YUI Shifter builder for language i18n from YRB(.pres) I am working on website internalization and it has YUI3 in stack, so it is good to use YUI intl module for that. Reading documentation gave idea to leverage shifter builder to convert Java property i18n files into YUI3 intl format (think as YRB(.pres) as they both have same syntax. Going from that I created meta module/meta/module.json file looking like this:
{
  "modulename": {
    "requires": [
        "oop"
    ]
},
"lang": ["en"]
}

And accordingly placed the language file like module/lang/modulename_en.pres.
That's not worked out, build processing successfully but no lang folders with context created. Also I tried use json like javascript version with no luck. I guess missing some additional step.
UPD: Thank you for comments. There is wrong syntax in my meta, the lang property has to be on the same level as requires that fixed problem with finding language files but still there is error when trying to use .pres files. Here it is the output:
....
shifter [info] shifting 2 langs for module

fs.js:427
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT, no such file or directory 'c:\\..\module\lang\module.js'
    at Object.fs.openSync (fs.js:427:18)
    at Object.fs.openSync (c:\Program Files\nodejs\node_modules\shifter\node_mod
ules\cpr\node_modules\graceful-fs\graceful-fs.js:68:26)
    at Object.fs.readFileSync (fs.js:284:15)
    at c:\Program Files\nodejs\node_modules\shifter\lib\module.js:424:26
    at Array.forEach (native)
    at Object.buildLang [as lang] (c:\Program Files\nodejs\node_modules\shifter\
lib\module.js:417:11)
    at c:\Program Files\nodejs\node_modules\shifter\lib\module.js:709:33
    at c:\Program Files\nodejs\node_modules\shifter\lib\stack.js:24:38
    at c:\Program Files\nodejs\node_modules\shifter\lib\module.js:372:13
    at c:\Program Files\nodejs\node_modules\shifter\node_modules\gear\node_modul
es\async\lib\async.js:190:13

I also opened report into shifter github repo. Will try to debug and see what I am missing here.

A: Seems like intl module documentation is referring for some other internal version of shifter other than git one, or possibly that functionality is on its  way. Nevertheles I needed that functionality and there is what works so far.
UPD: Thanks for comment I did glimpse to pre shifter era builder, and find out yrb2json parser here in already javascript format. Seems I am only the one person for these years who was interested in this functionality into nodejs shifter.


text:
Q: Prompt on exit for another program VB.NET I would like to make a message box to promp to exit. The problem here is, I would like to get information when ANOTHER program(e.g. chrome.exe) is closing.
Is it even possible to achieve?
Thanks in advance, Kaarel.


text:
Q: Defining a type that holds 3 int value I'm new to C++ and could not figure out how can I define a variable that holds 3 values,
e.g. coordinates hold 2 values, as (x,y).
I tried:
typedef int U_K(int a,int b,int c);

but that doesn't seem to work.
I'd really appreciate a quick simple answer :)
Thanks!
edit:
So i did this :
struct U_K{
    float a,b,c;
};
    U_K Uk; //this line

is this wrong? because i get "unknown type name U_K" for that line... i first though its because i needed to declare it under the function i am going to use the struct for, but turns out there is the error for both cases.

A: the shortest way is to use a struct
struct U_K
{
    int a,b,c;
};

usage:
U_K tmp;
tmp.a = 0;
tmp.b = 1;
tmp.c = 2;

You can add complexity to that type by adding member function/constructors to make the usage of U_K easier:
struct U_K
{
    int a,b,c;
    U_K() //default constructor
        :a(0)
        ,b(0)
        ,c(0)
    {}
    U_K(int _a_value,int _b_value, int _c_value) //constructor with custom values
        :a(_a_value)
        ,b(_b_value)
        ,c(_c_value)
    {}

};
//usage:
int main()
{
    U_K tmp(0,1,2);
    std::cout << "a = " << tmp.a << std::endl;//print a
    std::cout << "b = " << tmp.b << std::endl;//print b
    std::cout << "c = " << tmp.c << std::endl;//print c
}

Alternatively you can use std::tuple to obtain the same result. Using it is different:
std::tuple<int,int,int> t = std::make_tuple(0,1,2);
std::cout << "a = " << std::get<0>(t) << std::endl;//print first member
std::cout << "b = " << std::get<1>(t) << std::endl;//print second member
std::cout << "c = " << std::get<2>(t) << std::endl;//print third member

If you are learning c++ now you should know that the implementation std::tuple is much more complex than a trivial struct and to understand it you need to learn about templates and variadic templates.

A: struct TypeWith3Ints
{
  public:
    int a;
    int b;
    int c;
};

A: Use std::array<int, 3> which is to be preferred over tuple in this case as a homogenous container can be used.
If you want to typedef:
#include <array>
typedef std::array<int, 3> X;

A: Use std::tuple, then you don't have to make your own structure. Just write
std::tuple<int, int, int> your_tuple(a,b,c);
std::cout << std::get<1>(your_tuple) << ' '; // b
your_tuple = std::make_tuple(c,d,e);
std::cout << std::get<0>(your_tuple) << ' '; // c

If you want your own name, use alias, like:
typedef std::tuple<int, int, int> your_name;
your_name your_object(a,b,c); //your_tuple
std::cout << std::get<2>(your_tuple) << ' '; // c

If you want, your own structure, and if you want to write object(x,y,z), than you should make constructor or even overload operator (). It's more complicated. I suggest not to do it. Unless that has a deeper meaning. If you really want it, it could look like:
struct coordinate
 {
  int x,y,z;
  coordinate(int a, int b, int c) : x(a), y(b), z(c)
   {}
  void operator()(int a, int b, int c)
   {
    x = a;
    y = b;
    z = c;
   }
 } my_object(10,20,30);

int main()
 {
  std::cout<<my_object.x<<' '<<my_object.y<<' '<<my_object.z<<'\n';
  my_object(30,40,50);
  std::cout<<my_object.x<<' '<<my_object.y<<' '<<my_object.z<<'\n';
  return 0;
 }

You can also do not make constructor and use {} notation.


text:
Q: Как сделать, чтобы определенный блок кода выполнился после загрузки страницы и после выполнения всех скриптов? Здравствуйте. Как сделать, чтобы определенный блок кода выполнился после загрузки страницы и после выполнения всех скриптов?

A: Единственный надёжный способ - window.onbeforeunload

A: В jquery вроде так можно сделать
$(function() {

    // Ваш код

});


text:
Q: Echo the Requested URL in PHP I am not even A PHP newbie. But I need to call BS on a outside consultant who has come to my company and told me something was impossible.
Is it possible in PHP to simply create a webpage that displays the URL requested by the user.
In other words: rather than echoing/Printing   "Hello World"
I would like the page to print the URL that the user requested.

A: This can be accomplished with:
echo $_SERVER['REQUEST_URI']--
for a full list:
print_r($_SERVER)
Another useful one is $_SERVER['HTTP_HOST']
If you're going to do a redirect, you have more footwork to do, but a straightforward solution would be:
header("Location: {$site}?original_request={$_SERVER['REQUEST_URI']}"); - and then handle the rest in the page you redirect to.

A: I think what you are looking for is the full url. This can be done with.
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $url;

Just incase the port is included.
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$url = "http://".$_SERVER['HTTP_HOST'].$port.$_SERVER['REQUEST_URI'];

A: Here ya go:
echo $_SERVER['PHP_SELF'];

A: In a sense, both you and the consultant are correct.  In most cases, yes you can get the exact URL.  In many cases, the URL will be approximate.  In some cases, you might not get anywhere close to the requested URL.
Here are some barriers to building the exact URL:

*

*The #fragment isn't sent

*You don't know if :port was present (so you can't know whether to add it or not)

*You don't know what outside PHP rerouting was done (eg in .htaccess)

You could get around these by having a hidden input variable that is filled by Javascript with the full URL, which is then posted.  But then the argument is "well what if Javascript isn't turned on."
So, I'd say "yes you can" is the practical/pragmatic answer, while "no you can't" is the academic answer.


text:
Q: How to use delete on cascade in Laravel? I have a 'Roles' table:
$table->increments('id');
$table->string('name')->unique();
$table->text('description')->nullable();

and a 'Roles_Users' table:
$table->increments('id');
$table->integer('role_id')->unsigned()->index()->foreign()->references("id")->on("roles")->onDelete("cascade");
$table->integer('user_id')->unsigned()->index()->foreign()->references("id")->on("users")->onDelete("cascade");

When I run such a line:
Role::where('name','someString')->delete();

only the related row in the Roles table is deleted, and related rows in the Roles_Users table aren't. what is the solution?

A: Try to apply $table->index(['role_id', 'user_id']) and foreign keys after creating columns. So Your code will look like
Schema::table('role_users', function($table){
    $table->increments('id') ;
    $table->integer('role_id')->unsigned() ;
    $table->integer('user_id')->unsigned()
});
Schema::table('role_users', function($table){
    $table->index(['role_id', 'user_id'])
}) ;
Schema::table('role_users', function($table){
    $table->foreign()->references("id")->on("roles")->onDelete("cascade");
    $table->foreign()->references("id")->on("users")->onDelete("cascade");
}) ;

A: I recommend that you create a "foreign key" constraint for this case (as others mentioned). Also because this is a many-to-many relationship, you can use detach() method on your Eloquent model (if you sat the relations correctly in your user and role models)
$user = App\User::find(1);

// Detach all roles from the user...
$user->roles()->detach();

You can relate to the documentation for more details.


text:
Q: RxJava очередь запросов или запрос в цикле Использую Rx, обращаюсь в сеть и в запросе передаю параметр.
этих параметров несколько, List<String> paramsValue;
Выполняю так:
for(String p : paramsValue)
    Flowable f = QRequests.get(p);

Как можно создать очередь на выполнение средствами rx?

A: Kotlin:
Flowable.fromIterable(paramsValue).flatMap {
    QRequests.get(it)
}

Или
Flowable.fromIterable(paramsValue).concatMap {
    QRequests.get(it)
}


text:
Q: Replacing value in XML tags in C# using Regex I am trying to replace a value between two xml tags with a default numeric value.
In the following string, I need to replace the value of DOB w/ 1900-01-01.
Input:
<FirstName>TEST</FirstName>
<DOB>TEST</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>TEST</tt:DOB>

Desired Output:
<FirstName>TEST</FirstName>
<DOB>1900-01-01</DOB>
<tt:LastName>TEST</tt:LastName>
<tt:DOB>1900-01-01</tt:DOB>

This is what I currently have:
string pattern = @"<((DOB|tt:DOB).*>).*?</\1";
string input = "<FirstName>TEST</FirstName><DOB>TEST</DOB><tt:LastName>TEST</tt:LastName><tt:DOB>TEST</tt:DOB>";
string replacement = "<$1 1900-01-01 </$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Which gives me:
<DOB> 1900-01-01 </DOB>
<tt:DOB> 1900-01-01 </tt:DOB>

I'm able to set the default date, but not without putting a space between the value and the 1st subpattern in the replacement variable.  If I take out the spaces, it reads "1900" as part of the first subpattern.

Here is a link to my regex test: https://regex101.com/r/fK3yA5/6
Is there any way to replace the values with a number without using a space or quotes?

A: Jon Skeet is probably correct, you should use the XElement API. However, to answer your question, you can do it as follows by changing the Replacement regex to this:
string replacement = "<${1}1900-01-01 </$1";

Notice how $1 became ${1}. See here for more details


text:
Q: Expectation Involving Permutation Matrices Let $L$ be $n\times n$ bidiagonal matrix such that its diagonal is all $1$ and its
subdiagonal is all $-1$ (and zero elsewhere). Let $D$ be any diagonal matrix and $x,y$ be any $n$-dimensional column vectors.
What is the expectation:
$\mathbb E[x^TP^TL PDP^T L^TPy] $
where the expectation is taken over $P$ which runs over all $n!$ permutation matrices of $n\times n$?

A: The permutations are perhaps best understood as permuting $L$, that is, we want $\mathbb E[x^TL'DL'^Ty]$ with $L'=P^TLP$. We can write $L=I-A$, where $I$ is the identity and $A$ has $1$s on the subdiagonal and $0$ elsewhere. The identity is invariant under the permutation, and where $A$ has $1$s in off-diagonal elements along a chain of indices from $1$ to $n$, $A'=P^TAP$ has them along any of the $n!$ possible chains. Thus
$$
\begin{align}
\mathbb E[x^TP^TIPDP^TI^TPy]&=x^TDy\;,
\\
\\
\mathbb E[x^TP^TIPDP^TA^TPy]
&=\mathbb E[x^TDA'^Ty]
\\
&=\frac1{n!}\sum_{\sigma\in S_n}\sum_{i=1}^nx_iD_{ii}y_{\sigma^{-1}(\sigma(i)+1)}
\\
&=\sum_{i=1}^nx_iD_{ii}\frac1{n-1}\sum_{j\ne i}y_j
\\
&=\frac n{n-1}x^TD\langle y\rangle-\frac1{n-1}x^TDy\;,
\\
\\
\mathbb E[x^TP^TAPDP^TI^TPy]
&=
\frac n{n-1}\langle x\rangle^TDy-\frac1{n-1}x^TDy\;,
\\
\\
\mathbb E[x^TP^TAPDP^TA^TPy]
&=
\mathbb E[x^TA'DA'^Ty]
\\
&=
\frac1{n!}\sum_{\sigma\in S_n}\sum_{i=1}^nx_{\sigma^{-1}(\sigma(i)+1)}D_{ii}y_{\sigma^{-1}(\sigma(i)+1)}
\\
&=\sum_{i=1}^n\frac1{n-1}\sum_{j\ne i}x_jD_{ii}y_j
\\
&=\sum_{j=1}^n\frac1{n-1}\sum_{i\ne j}x_jD_{ii}y_j
\\
&=\frac n{n-1}x^T\langle D\rangle y-\frac1{n-1}x^TDy\;,
\end{align}
$$
so
$$
\mathbb E[x^TP^TLPDP^TL^TPy]=\frac n{n-1}\left(x^TDy-\langle x\rangle^TDy-x^TD\langle y\rangle+x^T\langle D\rangle y\right)\;,
$$
where $\langle x\rangle$ and $\langle y\rangle$ are constant vectors whose entries are the average of the entries of $x$ and $y$, respectively, and $\langle D\rangle$ is a multiple of the identity whose diagonal entries are the average of the diagonal entries of $D$.


text:
Q: Angular ngModelOptions allowInvalid not working i have code like this, where i set options {allowInvalid: true}
<input type="number" name="userName"
         ng-model="user.name"
         ng-model-options="{ allowInvalid: true }"
         ng-blur="test(user)"/>

When i input non number value into non number, example: abc,
why user.name still changed to undefined?
where i expected the model user.name should be 'abc'.
Full code: http://plnkr.co/edit/BsLk2GWVkchNgKaOV453?p=preview
i'm using angular v1.3.16

A: Following the link, you can't use allowInvalid with type="number" attribute.

Issues with HTML5 constraint validation
In browsers that follow the HTML5 specification, input[number] does not work as expected with ngModelOptions.allowInvalid. If a non-number is entered in the input, the browser will report the value as an empty string, which means the view / model values in ngModel and subsequently the scope value will also be an empty string.


text:
Q: Count all unique records I have a database with the following format:
myTable
productgroupID | productID | views | date
1              | 10        | 25    | 2013-05-23
4              | 105       | 15    | 2013-05-23
7              | 60        | 65    | 2013-05-23
7              | 60        | 55    | 2013-05-22
7              | 60        | 45    | 2013-05-21

Now I want to sum all views  of a product in the moth May.
Result should be:
productgroupID | productID | viewed | month
7              | 60        | 165    | 2013-05-01
1              | 10        | 25     | 2013-05-01
4              | 105       | 15     | 2013-05-01

I tried the query below, but this gives me all views of a specific productgroupID. But I need the sum of the unique productgroupID & productID.
SELECT COUNT( views ) AS viewed, productgroupID FROM product_stats_daily GROUP BY productgroupID

A: If you want the views totaled, then you can use the sum() aggregate function and then you can group by the month and year for the date:
select productGroupId,
  productId,
  sum(views) viewed,
  month(date) Month,
  year(date) Year
from myTable
group by productGroupId, productId, month(date), year(date);

See SQL Fiddle with Demo
You could also use Date_Format to get the date in the format that you want:
select productGroupId,
  productId,
  sum(views) viewed,
  DATE_FORMAT(date, '%Y-%m-01') date
from myTable
group by productGroupId, productId, DATE_FORMAT(date, '%Y-%m-01')

See SQL Fiddle with Demo

A: COUNT will count number of rows while SUM will sum up value of retrieved rows.
So your query becomes:
SELECT SUM( views ) AS viewed, productgroupID
FROM product_stats_daily
GROUP BY productgroupID

A: There's probably a more elegant way to force the date to the beginning of the month, but this should work:
SELECT
  ProductGroupID,
  ProductID,
  SUM(views) AS viewed,
  DATE_FORMAT(date, '%Y-%m-01') AS Month
FROM myTable
GROUP BY
  ProductGroupID,
  ProductID,
  DATE_FORMAT(date, '%Y-%m-01')


text:
Q: Throws test fails when promise is rejected I have this function
export async function trivialAsyncFail() {
    return new Promise((resolve,reject) => {
        reject("This is supposed to happen");
    });
}

And I have the following test to test it:
test("Async fail", async (t) => {
    const failedPromise = trivialAsyncFail();
    t.throws(failedPromise);
    await failedPromise;
});

However my test fails with message:

Async fail
Rejected promise returned by test
Rejection reason:
"This is supposed to happen"

I'm not sure if I have misunderstood how t.throws is supposed to work. I assumed that if you expect the promise to be rejected and it gets rejected the test should succeed.
Using ava 0.19

A: According to the documentation:

When testing a promise you must wait for the assertion to complete:
test('rejects', async t => {
  await t.throws(promise);
});

So do await t.throws(failedPromise) instead of await failedPromise


text:
Q: Sum by group in foxpro I'm newbie in foxpro programming. i have some issue how to fill "sum value" column with value data from second column by id_doc from first column. Thankyou
From this
table 1
Table1
Id_doc   Value   Sum_Value
AA       12      ??
AA       11      ??
AA       14      ??
BB       9       ??
BB       8       ??
CC       7       ??
CC       10      ??
CC       13      ??

To This Table
Table results
I have try this
  SELECT id_doc, SUM(NILAI) as Jml;
  FROM table2;
  GROUP BY Id_doc;

  INNER JOIN Jml_nilai as Jml ;
  ON Id_doc = Id_doc;
  ORDER BY Id_doc ASCENDING;

But it's not running well....

A: Your current description looks as if you want this:
CREATE CURSOR table1 (id_doc Char(20), value Int, sum_value Int)
INSERT INTO table1 (id_doc, value) VALUES ('AA', 12)
INSERT INTO table1 (id_doc, value) VALUES ('AA', 11)
INSERT INTO table1 (id_doc, value) VALUES ('AA', 14)
INSERT INTO table1 (id_doc, value) VALUES ('BB', 9)
INSERT INTO table1 (id_doc, value) VALUES ('BB', 8)
INSERT INTO table1 (id_doc, value) VALUES ('BB', 7)
INSERT INTO table1 (id_doc, value) VALUES ('CC', 7)
INSERT INTO table1 (id_doc, value) VALUES ('CC', 10)
INSERT INTO table1 (id_doc, value) VALUES ('CC', 13)

SELECT id_doc, SUM(value) FROM table1 GROUP BY id_doc

Edited: This could be the "running group sums self-Join" SQL as mentioned in the currently last comment:
SELECT T1.id_doc, T1.value, T2.grpSum FROM table1 T1 ;
    JOIN (SELECT id_doc, SUM(value) as grpSum FROM table1 GROUP BY id_doc) T2 ;
        On T2.id_doc = T1.id_doc

Later: learned that it's rather called [groupwise-maximum]
https://stackoverflow.com/questions/tagged/groupwise-maximum

A: Thank you so much for all response. Finally it's done....
Sharing for all. This is what i did.
CLOSE all
SET SAFETY OFF

******************************************************************

USE table1.dbf
INDEX on id_doc TO a
TOTAL ON id_doc TO table1_jumlah.dbf

CLOSE ALL
*************************************************************

sele 1
* data primer (master)
    use table1_jumlah.dbf
    index on id_doc to i

sele 2
* data sekunder (diisi)
    use table1.dbf
    index on id_doc to ii

sele 1
go top
do while .not. eof()
    iddocx=Id_doc
    valuex=Value

    sele 2
      loca for id_doc=iddocx
      if found()
        repl ALL Sum_Value with Valuex for id_doc=iddocx
    endi

   sele 1
   skip
   loop
endd

**********************************************************

CLOSE ALL
DELETE FILE *.bak
DELETE FILE *.idx


text:
Q: How can I find the maximum value within a string? For example, if a user were to input "ABZ748FJ9K" as a string, how would I pinpoint the max value of that string (in this case it is 9), and then output it back to the user.
Any non-numeric character is supposed to be ignored.
I tried doing some if-else ladder, but that would require me to list out every number, and it wasn't behaving the way I wanted it to anyways. I know there must be a better solution. Some help would be greatly appreciated. Thanks!
import java.util.Scanner;

public class Question{

public static void main(String args[]){

   Scanner input = new Scanner(System.in);

   System.out.println("Please enter a string");
      String userInput = input.next();

   int finalMax = max(userInput);

   System.out.println("The maximum value is " + finalMax);

}

public static int max(String s){

int x = s.length();

int y = 0;

   for (int i=0; i < x; i++){

         if (s.charAt(i) == 9){
            y=9;
         }
         else if (s.charAt(i) == 8){
            y=8;
         }
    }

return y;

}

}

    }

A: Try this:
public static int max(String s){
    s=s.replaceAll("\\D","");
    int x = s.length();
    int y = Character.getNumericValue(s.charAt(0));

    for (int i=1; i < x; i++){
         if (Character.getNumericValue(s.charAt(i)) > y){
            y=Character.getNumericValue(s.charAt(i));
         }
    }
    return y;
}

s=s.replaceAll("\\D","") will make sure all character in your string is a digit by replacing all non-digit character with ""

A: Use the function below instead of your version:
public static int max(String s){

int x = s.length();

int y = 0;
Character temp = null;
   for (int i=0; i < x; i++){
      char ch = s.charAt(i);

         if (ch >= '0' &&  ch <='9' && (temp == null || temp < ch )){
            temp = s.chartAt(i);
         }
    }

return Integer.valueOf(temp);

}

A: Start a max value with 0, then u will loop the string. Each loop u must verify if it is char or int, if int then check if it is > than the max value, if so, set the new max value.
I leave as a challenge to u, to think about each position of the string will be treated as a char.
Cheers. Good luck.

A: you should try something like:
public static int max(String s){
  int max = -1;
  char current;
  for(int i = 0; i<s.length; i++){
    current = s.charAt(i);
    if(current > '0' && current < '9')
      if(current > max)
        max = current;
  }
  return max;
}


text:
Q: Return a specific field using ForeignKey class Client(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    client_name = models.CharField('Nom et prénom', max_length=120)

    def __str__(self):
        return self.client_name

class OtherInfos(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    client_name = models.ForeignKey(Client, null=True, on_delete=models.CASCADE)
    client_detail = models.TextField('détails', blank=True)

    def __str__(self):
        return str(self.client_name)

class information(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    info_name = models.ForeignKey(patientlist, null=True, on_delete=models.CASCADE)
    info_data = models.TextField('More info', blank=True)
    info_evolution = models.ForeignKey(OtherInfos, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.info_name)

Hello everyone,
I have these 3 tables :
a "Client" can have multiple "information" and "OtherInfos", and i would like to show all data in one html page, i managed to do 90% of it using Foreignkey where i can get "information" and "Client" data in the html page, but it didn't work with "OtherInfos", any suggestions please ?
thank you

A: You can access data in this way
{% for info in information %}
      {{ info }}
     {% for other_info in info.info_evolution_set.all %}
         {{ other_info }}
      {% endfor %}
{% endfor %}

This is the pattern for it, you can add the third model to it, good luck

A: Well, the problem was that the uuid primary key change from one table to another even though it's the same Client, so when i try to do queries, it finds none, so what i did is i used AutoSlugField as primary key in all models :
slug = AutoSlugField(populate_from='NAME')

since all tables have the same 'NAME', that way i didn't need Foreignkeys...


text:
Q: control access to a folder using .htaccess - only if using particular domain i have 2 domains pointing to the same site - say a.com and b.com - i have a folder /admin on the site, that i only want to be accessible by people who access using b.com, so b.com/admin would work but a.com/admin would give an access error.
Can this be done through htaccess?
thanks in advance.

A: order deny,allow
deny from all
allow from 192.168.0.0/24

from http://corz.org/serv/tricks/htaccess.php
i havent tested this but the way he describes it on the website thats what it does.
Otherwise just go with htpasswd.

A: Use a RewriteCond to check for the current domain, like so:
RewriteCond %{HTTP_HOST}  ^a.com [NC]
RewriteRule ^admin/ http://%{HTTP_HOST}/ [R,NC,L]
This will redirect requests from a.com to the root of the site. Requests from b.com can access admin/ just fine.
(from the same site linked-to by slex)