text:
Q: Issue using maven which can't see default repositories My issue is that maven can't update my local repository since it can see I guess the default repositories.
Here is my settings.xml :
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <localRepository>D:\work\settings\localRepoMaven</localRepository>
    <interactiveMode>true</interactiveMode>
    <offline>false</offline>
    <pluginGroups/>
    <proxies/>
    <servers/>
    <mirrors/>
    <profiles>
        <profile>
            <id>maven-repository</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>

            <repositories>
                <repository>
                    <id>central</id>
                    <name>Maven Repository Switchboard</name>
                    <layout>default</layout>
                    <url>http://repo1.maven.org/maven2</url>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <name>Maven Plugin Repository</name>
                    <url>http://repo1.maven.org/maven2</url>
                    <layout>default</layout>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                    <releases>
                        <updatePolicy>never</updatePolicy>
                    </releases>
                </pluginRepository>
            </pluginRepositories>

        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>base</activeProfile>
    </activeProfiles>
</settings>

Here is my pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>MyApp</groupId>
    <artifactId>MyApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <tiles.version>3.0.1</tiles.version>
        <spring.version>3.0.5.RELEASE</spring.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.tiles</groupId>
                <artifactId>tiles-extras</artifactId>
                <version>${tiles.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.tiles</groupId>
                <artifactId>tiles-jsp</artifactId>
                <version>${tiles.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.tiles</groupId>
                <artifactId>tiles-servlet</artifactId>
                <version>${tiles.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.tiles</groupId>
                <artifactId>tiles-template</artifactId>
                <version>${tiles.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.tiles</groupId>
                <artifactId>tiles-el</artifactId>
                <version>${tiles.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-asm</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version }</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>org.springframework.web.servlet</artifactId>
                <version>${spring.version }</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

Please note that I don't have any proxy and tested without settings.xml (to force maven use default settings) but in vain.
I'm using Spring Tools Suite version 3.6.3.SR1
I can't see the issue. Please help !


text:
Q: How to handle melon of record in SQL server In SQL server every time i got Filegroup is full, Execution timeout. How can i release some space in SQL database.

System.Data.SqlClient.SqlException: Timeout expired. The timeout
  period elapsed prior to completion of the operation or the server is
  not responding. at
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
  Boolean breakConnection) at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection) at
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior
  runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
  BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
  stateObj)

A: You can shrink the SQL Server Database Size.
Step 1: Right-click on the database name >> Tasks >> Shrink >> Database.

Step 2: Then Click OK.

for more details you can read the following blog https://stackoverflow.com/a/18292136/1805776

redpajama_set_name: RedPajamaStackExchange


text:
Q: Почему функция не дожидается завершения работы другой функции NodeJS Не могу понять.
Вот есть функция, которая через 5 сек возвращает хеллоу
    function sayHello(){
               setTimeout(() => {
               var data='hello'
               return data;
            }, 5000)
    }

    module.exports = sayHello;

В другой функции хочу это вывести,
const getHello = require('../DB/remote/methods-api/getPopularProduct') // тут getHello() = sayHello()

 async function viewHello() {
      console.log("await "+ await getHello());
}

но выводит всегда undefined. Пробовал промисами, тоже самое.

A: У вас тут небольшая путаница:

*

*sayHello() через 5 секунд не возвращает 'hello'. Она устанавливает таймаут и тут же возвращает undefined, который и получает функция в импортирующем файле. 'hello' возвращает фукнция, установленная в таймауте, но возвращает его «в пустоту», потому что возвращённое значение нигде не принимается.

*Импортируемая функция не возвращает Promise и не является асинхронной, поэтому await перед её вызовом не имеет смысла.
Кажется, то, чего вы пытаетесь добиться, можно реализовать так:
function sayHello() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = 'hello';
      resolve(data);
    }, 5000);
  });
}

module.exports = sayHello;

const getHello = require('./module.js');

async function viewHello() {
  console.log("await " + await getHello());
}

viewHello();


text:
Q: php include file I have a common framework that resides in /var/www/fw/trunk path, and also have a virtual host that resides in /var/www/vhosts/aerosoftware.net/httpdocs/ on a http://aerosoftware.net/ domain.
I changed php.ini include path to include_path='.:/var/www/fw/trunk' but still I get an include error. Why is that?

A: /var/www/vhosts/aerosoftware.net/httpdocs/ looks like the standard layout of a Plesk box.
Try creating a .htaccess file inside your httpdocs directory with the following in it.
php_value include_path ".:/var/www/fw/trunk"

I'd also recommend creating a phpinfo.php file with
<? phpinfo(); ?>

in it so that you can check that the include_path value has been changed.

A: Be aware, that there may be two or more php.ini files. For example, on my OpenSuse machine there is two of them, one for apache environment, and one generic.

A: I found a solution, it was this thing I had to put in a config file for that virutal host:

php_admin_value safe_mode off
php_admin_value open_basedir none


text:
Q: How to get Get-ChildItem to handle path with non-breaking space I have the following code that works for most files.  The input file (FoundLinks.csv) is a UTF-8 file with one file path per line.  It is full paths of files on a particular drive that I need to process.
$inFiles = @()
$inFiles += @(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv")

foreach ($inFile in $inFiles) {
    Write-Host("Processing: " + $inFile)
    $objFile = Get-ChildItem -LiteralPath $inFile
    New-Object PSObject -Prop @{
        FullName = $objFile.FullName
        ModifyTime = $objFile.LastWriteTime
    }
}

But even though I've used -LiteralPath, it continues to not be able to process files that have a non-breaking space in the file name.
Processing: q:\Executive\CLC\Budget\Co  2018 Budget - TO Bob (GA Prophix).xlsx
Get-ChildItem : Cannot find path 'Q:\Executive\CLC\Budget\Co  2018 Budget - TO Bob (GA Prophix).xlsx'
because it does not exist.
At ListFilesWithModifyTime.ps1:6 char:29
+     $objFile = Get-ChildItem <<<<  -LiteralPath $inFile
    + CategoryInfo          : ObjectNotFound: (Q:\Executive\CL...A Prophix).xlsx:String) [Get-ChildItem], ItemNotFound
   Exception
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

I know my input file has the non-breaking space in the path because I'm able to open it in Notepad, copy the offending path, paste into Word, and turn on paragraph marks.  It shows a normal space followed by a NBSP just before 2018.
Is PowerShell not reading in the NBSP?  Am I passing it wrong to -LiteralPath?  I'm at my wit's end.  I saw this solution, but in that case they are supplying the path as a literal in the script, so I can't see how I could use that approach.
I've also tried: -Encoding UTF8 parameter on Get-Content, but no difference.
I'm not even sure how I can check $inFile in the code just to confirm if it still contains the NBSP.
Grateful for any help to get unstuck!
Confirmed that $inFile has NBSP
Thank you all!  As per @TheMadTechnician, I have updated the code like this, and also reduced my input file to only the one file having a problem.
$inFiles = @()
$inFiles += @(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" -Encoding UTF8)

foreach ($inFile in $inFiles) {
    Write-Host("Processing: " + $inFile)

    # list out all chars to confirm it has an NBSP
    $inFile.ToCharArray()|%{"{0} -> {1}" -f $_,[int]$_}

    $objFile = Get-ChildItem -LiteralPath $inFile
    New-Object PSObject -Prop @{
        FullName = $objFile.FullName
        ModifyTime = $objFile.LastWriteTime
    }
}

And so now I can confirm that $inFile in fact still contains the NBSP just as it gets passed to Get-ChildItem.  Yet Get-ChildItem says the file does not exist.
More I've tried:

*

*Same if I use Get-Item instead of Get-ChildItem

*Same if I use -Path instead of -LiteralPath

*Windows explorer and Excel can deal with the file successfully.

I'm on a Windows 7 machine, Powershell 2.
Thanks again for all the responses!

A: It's still unclear why Sandra's code didn't work: PowerShell v2+ is capable of retrieving files with paths containing non-ASCII characters; perhaps a non-NTFS filesystem with different character encoding was involved?
However, the following workaround turned out to be effective:
$objFile = Get-ChildItem -Path ($inFile -replace ([char] 0xa0), '?')

*

*The idea is to replace the non-breaking space char. (Unicode U+00A0; hex. 0xa) in the input file path with wildcard character ?, which represents any single char.

*For Get-ChildItem to perform wildcard matching, -Path rather than -LiteralPath must be used (note that -Path is actually the default if you pass a path argument positionally, as the first argument).

*Hypothetically, the wildcard-based paths could match multiple files; if that were the case, the individual matches would have to be examined to identify the specific match that has a non-breaking space in the position of the ?.

A: Get-ChildItem is for listing children so you would be giving it a directory, but it seems you are giving it a file, so when it says it cannot find the path, it's because it can't find a directory with that name.
Instead, you would want to use Get-Item -LiteralPath to get each individual item (this would be the same items you would get if you ran Get-ChildItem on its parent.
I think swapping in Get-Item would make your code work as is.
After testing, I think the above is in fact false, so sorry for that, but I will leave the below in case it's helpful, even though it may not solve your immediate problem.

But let's take a look at how it can be simplified with the pipeline.
First, you're starting with an empty array, then calling a command (Get-Content) which likely already returns an array, wrapping that in an array, then concatenating it to the empty one.
You could just do:
$inFiles = Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv"

Yes, there is a chance that $inFiles will contain only a single item and not an array at all.
But the nice thing is that foreach won't mind one bit!
You can do something like this and it just works:
foreach ($string in "a literal single string") {
    Write-Host $string
}

But Get-Item (and Get-ChildItem for that matter) accept pipeline input, so they accept multiple items.
That means you could do this:
$inFiles = Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" | Get-Item

foreach ($inFile in $inFiles) {
    Write-Host("Processing: " + $inFile)
    New-Object PSObject -Prop @{
        FullName = $inFile.FullName
        ModifyTime = $inFile.LastWriteTime
    }
}

But even more than that, there is a pipeline-aware cmdlet for processing items, called ForEach-Object, to which you pass a [ScriptBlock], in which $_ represents the current item, so we could do it like this:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
    Get-Item |
    ForEach-Object -Process {
        Write-Host("Processing: " + $_)
        New-Object PSObject -Prop @{
            FullName = $_.FullName
            ModifyTime = $_.LastWriteTime
        }
    }

All in one pipeline!
But further, you're creating a new object with the 2 properties you want.
PowerShell has a nifty cmdlet called Select-Object which takes an input object and returns a new object containing only the properties you want; this would make for a cleaner syntax:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
    Get-Item |
    Select-Object -Property FullName,LastWriteTime

This is the power of the the pipeline passing real objects from one command to another.
I realize this last example does not write the processing message to the screen, however you could re-add that in if you wanted:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
    Get-Item |
    ForEach-Object -Process {
        Write-Host("Processing: " + $_)
        $_ | Select-Object -Property FullName,LastWriteTime
    }

But you might also consider that many cmdlets support verbose output and try to just add -Verbose to some of your existing cmdlets. Sadly, it won't really help in this case.
One final note, when you pass items to the filesystem cmdlets via pipeline, the parameter they bind to is in fact -LiteralPath, not -Path, so your special characters are still safe.

A: I just run into the same issue. Looks like get-childitem ak gci expects the path in unicode (UTF-16). So either convert the csv file into unicode or convert the lines that include the path as unicode within your script.
Testet on PS 5.1.22621.608


text:
Q: Python Requests: Where is Crypto.dll? I am trying to use the Python requests module on Windows with Anaconda. After installing it with pip, attempting to import it fails because asn1crypto is required in the cryptography 2.2.2 module. After installing that with pip, it fails because the crypto library (that'd be crypto.dll on Windows) does not exist. Where the heck does this come from? The way asn1crypto uses it makes it seem like this is libcryptoXXX.dll, but I do not see any circumstance that it would be called crypto.dll. It looks like very old versions of pyOpenSSL (back when it was python-OpenSSL) came with crypto.so for Unix distributions, but I don't know where that came from and don't see any mention of a crypto.dll (and crypto.so was no longer distributed by the version of pyOpenSSL that requests says it requires). So what is this crypto.dll and where can I get it?

A: Setting expectations up front - all I've got to offer is a workaround and notes on my own experience.
I was faced with the same issue with Anaconda on Windows, and after going on a small adventure I simply removed asn1crypto from Anaconda. This raised an issue with a dependent package, so I removed that. 5 or 6 packages later I had a subset of Anaconda where Python code seems to successfully build and run.
My assessment is that this is an issue with Anaconda on Windows, specifically with asn1crypto (why do you expect and need "crypto.dll" on machines that don't have it, and offer no alternative?). I'd love to be wrong and for someone to tell me why.
My small adventure had me fruitlessly looking for the mysterious crypto library. I describe this below.
Looking for the "crypto.dll", I came across some questionable leads before landing here, which suggested I could pick up "libcrypto.dll" as part of an older version of OpenSSH for Windows. Not quite what I was looking for, but worth a try. Didn't work. Tried the 32 bit version (in path via system32) and the 64 bit version (in path via SysWOW64) with no luck. Tried the new and renamed to "libeay32.dll" version from a later release of OpenSSH on Windows. Didn't work. Tried the versions from OpenSSL on Windows (inexplicably renamed in the other direction). Tried masquerading these dlls as "crypto.dll", which just caused other errors.
Once again, I'd love for a more satisfying answer to exist (hint hint, future readers).


text:
Q: Split, apply linear model, combine I have a dataframe as follows:
df

Date       Hour ID Par1  Par2  Par3
08-01-15     0   A   2    3      4
08-01-15     0   B   4    5      6
08-01-15     1   N   2    9      10
08-01-15     1   A   3    7      23
08-01-15     1   B   4    7      22
08-02-15     0   E   2    4      12
08-02-15     0   A   3    7       9

So I want to split this dataframe by Hour as follows:
splitdata<-split(df<-split(df, df$Hour)

After splitting it, I want to apply a linear model to the split dataset.
result <- lapply(splitdata, function(df){
  lm1 <-lm(Par1~Par2,data=df)
  summary <- (lm1$summary)
  data.frame(as.list(summary))
})
result

My results do not show anything. Though if I changed summary to:
summary <- (lm1$coef)
data.frame(as.list(summary))

Then it will produce a result.
So the main question is, how do I get a list of the summaries of each of the linear models by Hour and not just the coefficients?
Thanks!

A: Try using lmList from nlme
library(nlme)
fits <- lmList(Par1 ~ Par2 | Hour, data=df)

This splits the data by hour and fits linear models for you.  Then, you can just do summary(fits).  Or, you can look at each summary individually with
lapply(fits, summary)

A: If you're looking for a table form (which I usually prefer):
> dt = data.table(df)
> dt[,{S = summary(lm(Par1 ~ Par2))$coefficients; list(Coef = S[2,1], Intercept = S[1,1], Sig = S[2,4])}, by = Hour]
   Hour      Coef Intercept      Sig
1:    0  0.314286   1.25714 0.439388
2:    1 -0.750000   8.75000 0.333333


text:
Q: Using multiple "myhostname" in postfix Does postfix allow to dynamically change "myhostname" ? I rtfmed a lot but did not found anything qualitative. My installation is a postfix multiple domain, multiple ip (tweaked in master.cf) and multiple dkim sig but the myhostname directive in master.cf isn't included.
That kind of stuff:
192.168.1.12:smtp inet n - n - - smtpd -o myhostname=mail.mail2.com -o smtpd_banner=mail.mail2.com -o smtp_helo_name=mail.mail2.com

Anyway, banner and helo are OK, but myhostname is still the one included in main.cf

A: After a lot of testing, i must conclude that you cannot do this. It IS possible to dynamically change myhostname, it just doesn't affect the Received header.
With a test having banner use $myhostname, i can see that it changes when i use
-o myhostname=test.test.test

but the received header does not.
I tried using, in main.cf
mydomain=test.test.test
myhostname=$mydomain

This does affect both the Received header and banner. But trying to override the $mydomain
-o mydomain=test.test.test

only affects the banner again.
Thus it seems that the variable used in the Received header is filled from $myhostname before overriding $myhostname from the command line arguments.

A: Postfix is highly configurable. so much so that rtfming seems only slightly more advantageous than perusing the source (only joking).
There are in fact numerous ways of dynamically overriding the static configuration. At a very minimum, some understanding of the Postfix workflow is required. this is in the overview.
It is also useful to understand:

*

*different Postfix daemons reference different portions of the main.cf
static configuration.

*most built-in Postfix services are customisable;

*ad-hoc custom services
(milters etc) can be
plugged into the workflow;

*if all else fails, multiple Postfix instances can be deployed; each
referring to separate main.cf and master.cf static configurations

Per the OP, wrt conditionally sending mail to some external recipients:
Methods of interest are those that are conditional upon either:

*

*the smptd listening port

*the sender domain name

Apparently specifically in this regard, and for reasons that will soon hopefully become clear,  Wietse Venema made some *key changes in Postfix 2.7 to do with content filtering &so to summarise:
pre Postfix 2.7 :

where unspecified, the default nexthop destination is $myhostname (ie: localhost).

Postfix 2.7:

where unspecified, the default nexthop destination is the recipient
  domain.
transport conditional upon sender domain is supported out-of-the-box via the use of
  sender_dependent_default_transport_maps

This distinction is of issue because there are still folk stuck on pre 2.7 Postfix installs.. ie: for some Red Hat users relying upon the official rpms, then for example, users still on centOS 5x => Postfix 2.3 & for centOS 6x => Postfix 2.6 (but i might be wrong, dyor etc)

Postfix 2.7:
Things got easier! below are a couple of methods.
The first method involves setting up a couple of smtpd daemons listening on different non-standard ports and uses custom transports conditional upon which smtpd port we submit our outbound email to:

*

*port 10026 => custom1_smtp

*port 10027 => custom2_smtp

This is made possible by dynamically defining a custom filter service & overriding the content_filter directive in the smtpd service. the filter is a dummy. we're not really going to be writing & deploying our own custom filter service. instead we just hijack a postfix smtp service instance for the sole purpose of gaining access to and dynamically overriding the myhostname directive before the email is finally pushed out to the wild.
This can only happen in Postfix 2.7 (and maybe subsequent versions above) because the specified transports' default nexthop destination is defined to be the recipient domain. In versions below Postfix 2.7, it is defined as $myhostname and so the email loops back into Postfix, causing it to bork.

The second method is by the book and uses sender_dependent_default_transport_maps to conditionally route our outbound email to a couple more custom-defined transports;  and depends upon the sender's domain name:

*

*parrots.tld   =>  custom3_smtp:

*penguins.tld  =>  custom4_smtp:

The sender_dependent_default_transport_maps act like sender_dependent_relayhost_maps but instead of routing outgoing mail from a specified sender domain to a specified destination domain, sender_dependent_default_transport_maps are used to internally route the outgoing mail from a specified sender (domain) to a specified (custom-defined) transport defined in master.cf.

We add the following directive to /etc/postfix/main.cf:
sender_dependent_default_transport_maps = hash:/etc/postfix/sender_transports

Then create the mapping file /etc/postfix/sender_transports:
@parrots.tld    custom3_smtp:
@penguins.tld   custom4_smtp:

&build the database using postmap:
postmap hash:/etc/postfix/sender_transports

Then we define all our custom transports in /etc/postfix/master.cf:
custom4_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.penguins.tld
             -o smtp_bind_address=m.n.o.p
             -o smtp_helo_name=penguins.tld

custom3_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.parrots.tld
             -o smtp_bind_address=i.j.k.l
             -o smtp_helo_name=parrots.tld

custom2_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.cats.tld
             -o smtp_bind_address=e.f.g.h
             -o smtp_helo_name=cats.tld

custom1_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.dogs.tld
             -o smtp_bind_address=a.b.c.d
             -o smtp_helo_name=dogs.tld

# our main internal entry for the dogs site; all outgoing dogs traffic is
# sent to this (non-standard) port and routed to our custom1_smtp transport
10026             inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.dogs.tld
             -o content_filter=custom1_smtp:

# our main internal entry for the cats site; all outgoing cats traffic is
# sent to this (non-standard) port and routed to our custom2_smtp transport
10027             inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.cats.tld
             -o content_filter=custom2_smtp:

# default smtpd entry;  outgoing traffic sent to this port (25) will get routed
# subject to the conditions in our sender_dependent_default_transport_maps file
smtp              inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.tld

# hoorah.
#

before Postfix 2.7 :
The way commonly suggested by the Postfix pixies is to set up multiple Postfix instances.
But here's where an understanding of the Postfix workflow comes in handy.. because by devising a custom-defined Postfix service chain, it is also achievable with just a single Postfix instance. nothing in main.cf needs to be changed. static configuration is dynamically overridable from within the custom service chains we define in master.cf.
Each service reads it's own subset of all the directives residing in the main.cf config. so as we progress along our custom service chain, we can override any settings as may be permitted from within each respective Postfix service in the chain.
(Additionally, note that we could even write our own custom replacement
for any of the default Postfix daemons. which is pretty cool).

In /etc/postfix/master.cf:
# each Postfix service reads it's own subset of directives from main.cf config.
# many settings can be dynamically overridden as we move thro the service chain..
# here we override the $myhostname setting depending upon which port we send our
# outgoing smtp email to.

# custom2  cats service chain
custom2_cleanup   unix  n       -       -       -       0        cleanup             -o queue_service_name=custom2_qmgr
custom2_qmgr      fifo  n       -       n       300     1        qmgr                -o rewrite_service_name=custom2_rewrite
custom2_rewrite   unix  -       -       n       -       -        trivial-rewrite     -o default_transport=custom2_smtp:
custom2_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.cats.tld
             -o smtp_bind_address=e.f.g.h
             -o smtp_helo_name=cats.tld

# custom1 dogs service chain
custom1_cleanup   unix  n       -       -       -       0        cleanup             -o queue_service_name=custom1_qmgr
custom1_qmgr      fifo  n       -       n       300     1        qmgr                -o rewrite_service_name=custom1_rewrite
custom1_rewrite   unix  -       -       n       -       -        trivial-rewrite     -o default_transport=custom1_smtp:
custom1_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.dogs.tld
             -o smtp_bind_address=a.b.c.d
             -o smtp_helo_name=dogs.tld

# our main internal entry for the dogs site; all outgoing dogs traffic is
# sent to this (non-standard) port and routed to our custom1 service chain
10026             inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.dogs.tld
             -o cleanup_service_name=custom1_cleanup
           # NB: attempting to override the content_filter directive
           # *will not work* in postfix < 2.7 since an unspecified nexthop
           # destination defaults to localhost and causes the email to loop
           # -o content_filter=custom1_smtp:

# our main internal entry for the cats site; all outgoing cats traffic is
# sent to this (non-standard) port and routed to our custom2 service chain
10027             inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.cats.tld
             -o cleanup_service_name=custom2_cleanup

# yeehar! acu ;)
#

NOTE1: is a caveat:
while directives such as cleanup_service_nameand rewrite_service_name are documented in the configuration parameters, they do not appear to be documented as configurable options parameters for any of the Postfix daemons?!
So at least this seems to be an undocumented approach and hence may well be frowned upon or even possibly deemed as evil in official circles. ~i wouldn't know as i was never able to form a cogent enough question to ever brave the postfix-users@postfix.org official mailing lists!

NOTE2:
there are some folk out there attempting to do this kind of thing in other imaginative ways such as setting up a header_checks FILTER in order overcome the default localhost nexthop destination by dynamically cooking-up a complete transport:recipient-domain-destination:
In /etc/postfix/master.cf:
custom2_smtp      unix  -       -       n       -       -        smtp
             -o myhostname=mailer.external.cats.tld
             -o smtp_bind_address=e.f.g.h
             -o smtp_helo_name=cats.tld

custom2_cleanup   unix  n       -       -       -       0        cleanup
             -o header_checks=regexp:/etc/postfix/custom2_header_checks

#conditional processing contingent upon entry via some non-standard port
10027             inet  n      -        n       -       -        smtpd
             -o myhostname=mailer.internal.cats.tld
             -o cleanup_service_name=custom2_cleanup

Then in /etc/postfix/custom2_header_checks, pull the recipient domain out of the header-fields with a regex and provide it to the filter directive thus :
/^To:.*@(.*)$/      FILTER    custom2_smtp:$1

While this may seem like a good idea, & partially does work, it is nevertheless certainly a horrid hack; is potentially insecure & at least fails if/when
the outgoing email contains multiple recipients. duh!

NOTE3:
if none of the above makes any sense whatsoever, then you probably need to do a bit more rtfming ;)
But seriously, i know there's quite a lot of stuff here.. for various reasons beyond my control, the business is stuck on Postfix 2.3 and i have needed to spend more than 5mins sorting their requirements out; to the extent that my hourly rate has diminished to that of a costa rican pineapple picker (only i do not benefit from their costa' living). so i have tried to lay this all out while it's fresh in my mind and in terms that do not just parrot the official documentation; hopefully so this may help the next poor soul who happens down this particular path ;)


text:
Q: How to make a single list of all the entities of an output of a loop Below is the code which returns a print out of 8 figures:
for i in range(A,A+30):
        for j in range(6,7):
            if "X" in str(sh1.cell(i,j).value):
                print(i)

Commandline Output:
44
55
57
61
65
69
71
72

How can I store these entities in their order in a single list like this:
["44", "55", "57", "61", "65", "69", "71", "72"]

A: I suppose you want to create a new list and add the items to it:
values = []
for i in range(A,A+30):
    for j in range(6,7):
        if "X" in str(sh1.cell(i,j).value):
            print(i)
            values.append(str(i))

values == ["44", "55", "57", "61", "65", "69", "71", "72"]
Getting familiar with lists (and other basic python data structures) can get very handy: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists


text:
Q: Java @Pathparam with POST Method I have to make request with only one parameter for example:

example.com/confirm/{unique-id-value}

I don't expect to get any data in body, only interested in Response Code.
Need advice which method to use GET or POST
GET i think is also OK because, making request with pathparam, but on the other hand POST is also right to use, because i don't expect to receive any data from body, just making informative request and interested in only status code of request result.

A: One disadvantage of using GET is that its response is often cached, so if you inquire about the same ID repeatedly, you might not get the results you expect, unless you do some shenanigans to prevent caching (such as appending a unique timestamp to the GET URL for every request). POST requests, on the other hand, are never cached, so you would get the correct result every time without any additional work.

A: The confirm suggests that a request to this URL will change some state on a server by 'confirming' some 'task' that is identified by a unique ID. So we talk about the Reource (the R in REST) of a 'task confirmation'. A GET request will get the current state of such a Resource. GET must not have side effects like changing the state of the 'task confirmation' resource. If it is unconfirmed before a GET request, it must be unconfirmed after such a request.
If you want to change the state of the 'task confirmation' Resource, you must use a different HTTP verb. But since you write that you will not pass any request body, it is hard to recommend a RESTful approach.


text:
Q: Predefine a specific twitter feed to display In the code below, a tableview displays the twitter feed of the user of the phone. All I want to do is display the feed of a user that I predefine in the code. I looked online but can't find any tutorials on this. I would like to edit this code instead of restarting with a third party API.
ViewController.m
#import "TwitterViewController.h"
#import <Accounts/Accounts.h>
#import <Social/Social.h>

@interface TwitterViewController ()

@property (strong, nonatomic) NSArray *twitterArray;

@end

@implementation TwitterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self twitterTimeline];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)twitterTimeline {

    ACAccountStore *account = [[ACAccountStore alloc] init]; // Creates AccountStore object.

    // Asks for the Twitter accounts configured on the device.

    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
     {
         // If we have access to the Twitter accounts configured on the device we will contact the Twitter API.

         if (granted == YES){

             NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType]; // Retrieves an array of Twitter accounts configured on the device.

             // If there is a leat one account we will contact the Twitter API.

             if ([arrayOfAccounts count] > 0) {

                 ACAccount *twitterAccount = [arrayOfAccounts lastObject]; // Sets the last account on the device to the twitterAccount variable.

                 NSURL *requestAPI = [NSURL URLWithString:@"http://api.twitter.com/1.1/statuses/user_timeline.json"]; // API call that returns entires in a user's timeline.

                 // The requestAPI requires us to tell it how much data to return so we use a NSDictionary to set the 'count'.

                 NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

                 [parameters setObject:@"100" forKey:@"count"];

                 [parameters setObject:@"1" forKey:@"include_entities"];

                 // This is where we are getting the data using SLRequest.

                 SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];

                 posts.account = twitterAccount;

                 // The postRequest: method call now accesses the NSData object returned.

                 [posts performRequestWithHandler:

                  ^(NSData *response, NSHTTPURLResponse
                    *urlResponse, NSError *error)
                  {
                      // The NSJSONSerialization class is then used to parse the data returned and assign it to our array.

                      self.twitterArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

                      if (self.twitterArray.count != 0) {

                          dispatch_async(dispatch_get_main_queue(), ^{

                              [self.twitterFeedTable reloadData]; // Here we tell the table view to reload the data it just recieved.

                          });

                      }

                  }];

             }

         } else {

             // Handle failure to get account access
             NSLog(@"%@", [error localizedDescription]);

         }

     }];

}

#pragma mark Table View Data Source Mehtods

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Returns the number of rows for the table view using the array instance variable.

    return [_twitterArray count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Creates each cell for the table view.

    static NSString *cellID =  @"CELLID" ;

    UITableViewCell *cell = [self.twitterFeedTable dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

    }

    // Creates an NSDictionary that holds the user's posts and then loads the data into each cell of the table view.

    NSDictionary *tweet = _twitterArray[indexPath.row];

    cell.textLabel.text = tweet[@"text"];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // When a user selects a row this will deselect the row.

    [self.twitterFeedTable deselectRowAtIndexPath:indexPath animated:YES];

}

@end

A: The information is here in the docs.
You need to add either a user_id parameter or a screen_name parameter to your http://api.twitter.com/1.1/statuses/user_timeline.json request, and that's all.
Example as provided in the documentation:
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi


text:
Q: How do I have to mock patch in this use case? The initial scenerio is writing tests for functions from a library (lib.py).
lib.py:
def fun_x(val):
  # does something with val
  return result

def fun(val):
  x = fun_x(val)
  # does seomthing with x
  return result

test__lib.py
import pytest
import lib

def lib_fun_x_mocked(val):
  return "qrs"

def test_fun():
  assert lib.fun("abc") == "xyz"

But lib.fun_x() does something very expensive or requires a resource not reliably available or not determinisitc. So I want to subsitute it with a mock function such that when the test test_fun() is executed lib.fun() uses lib_fun_x_mocked() instead of fun_x() from its local scope.
So far I'm running into cryptic error messages when I try to apply mock/patch recipes.

A: You can use the built-in fixture monkeypatch provided by pytest.
import lib

def lib_fun_x_mocked(some_val):  # still takes an argument
    return "qrs"

def test_fun(monkeypatch):
    with monkeypatch.context() as mc:
        mc.setattr(lib, 'fun_x', lib_fun_x_mocked)
        result = lib.fun('abc')
    assert result == 'qrs'

Also as a side note, if you are testing the function fun you shouldn't be asserting the output of fun_x within that test. You should be asserting that fun behaves in the way that you expect given a certain value is returned by fun_x.


text:
Q: JPA Hibernate configuration troubles I've been trying to configure JPA in many ways in different enviroments and I'm slowly becoming desperate. Can anyone tell me what I'm missing?
Exceptions:
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
etc.
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySSQL5Dialect] as strategy [org.hibernate.dialect.Dialect]
etc...
    ... 37 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySSQL5Dialect]
etc...
    ... 47 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySSQL5Dialect

etc...
    ... 48 more

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="BoatsPU" transaction-type="RESOURCE_LOCAL">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.dante.jpa.Boat</class>

        <properties>

            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/boats" />
            <property name="javax.persistence.jdbc.password" value="4dm1n" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.user" value="boats_admin" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySSQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create.drop"/>

        </properties>

    </persistence-unit>
</persistence>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dante</groupId>
    <artifactId>JPATest2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- JPA implementation. -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.0.Final</version>
        </dependency>

        <!-- Driver for desired SQL server. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

    </dependencies>
</project>

Whole app currently consists of Main with transaction and model class...
I can't even paste all exception code because stackoverflow says i have to add some more details -_-

A: The class name is MySQL5Dialect, not MySSQL5Dialect

A: java.lang.ClassNotFoundException mean that your class name is wrong. The exactly name is MySQL5InnoDBDialect.
So, you should change your xml to:
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>


text:
Q: javascript error in IE8 compatibitlity mode I have the following jQuery code that works fine in IE8, FF but in IE8 comp mode it gives this error
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Creative AutoUpdate v1.30.00)
Timestamp: Fri, 29 Oct 2010 22:12:03 UTC
Message: Object doesn't support this property or method
Line: 162
Char: 44
Code: 0
Here is line 162
$(this).attr('onChange', function(iii,vvv){return vvv.replace('_','');});

Here is the full script
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("select[name^=SELECT___]").each(function(){
$(this).attr('onChange', function(iii,vvv){return vvv.replace('_','');});
});
$("a[href^='javascript:change_option']").each(function(){
$(this).attr('href', function(ii,vv){return vv.replace('_','');});
});
});
</script>

What is causing this error? Is there another way to do what I want to do?
What I need to do is change the "change_option" to "changeoption" in each instance of the following code on the page, Perhaps there is a better way of doing it.
Here is the HTML code. I do not have access to this html code
EDIT:
<select onChange="change_option('SELECT___100E___7',this.options[this.selectedIndex].value)" name="SELECT___100E___7">

This is the doc declaration.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

A:
What I need to do is change the
  "change_option" to "changeoption" in
  each instance of the following code on
  the page, Perhaps there is a better
  way of doing it.

Perhaps. Why can't you just create an alias of changeoption (assuming you have defined the function)?
var change_option = changeoption;


text:
Q: Packaging of MATLAB code In the recent question "How to organize MATLAB code?" Andrew Janke mentioned in his answer using classes to organize MATLAB functions into packages:

... consider rewriting some of the code as objects, using stateless utility
  classes with class methods and private functions as ways of packaging related
  functions together and providing some encapsulation. ... In
  classic MATLAB, classes are your only way of doing some sort of packages.

Would you please provide more information on it? Links, code examples to understand the concept.

A: Loren hosted a guest blogger to discuss this issue:
http://blogs.mathworks.com/loren/2008/08/18/when-to-create-classes-in-matlab/
I made a simple video about this:
http://blogs.mathworks.com/videos/2008/07/07/advanced-matlab-class-system-for-oop-in-matlab-introduction/
Of course the MATLAB documentation for this:
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brh2rgw.html

A: Don't use classes for packaging
Classes in Matlab has known limitaitons (starting with performance scalability, etc).
Before going into using OOP in MATLAB, first learn "+" packaging (i.e. not "@" or handles).
Statements like import foo.bar work just as expected (also check this).
A word of caution: if you really need OOP, just consider picking another language before doing it in MATLAB. I had to rewrite my OOP MATLAB code back to functions and packages because OOP implementation by Mathworks is just "immature". First troubles start with parfor where stuff has to be serialized with an overhead and then still breaks way too often.


text:
Q: How to import sqlite file into my project? I am making an sqlight using eclipse outside the android project
what should I add into my android manifest in order to make it work?
thank you Mathias, lets take this q to another project who generate a SQL file using java
assuming this. How can I set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase()?
my code over there is
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
/*
*some code
*/
   Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists "+TABLE_NAME+";");
    //stat.executeUpdate("create table "+TABLE_NAME+" (name, occupation);");
    stat.executeUpdate("create table "+TABLE_NAME+" ("+VALUE+","+TYPE+","+LETTER+");");
    PreparedStatement prep = conn.prepareStatement(
      "insert into "+TABLE_NAME+" values (?, ?,?);");

Even when I use:
  db = SQLiteDatabase.openDatabase(myPath, null,  SQLiteDatabase.NO_LOCALIZED_COLLATORS);

when I use the query :
     String s = "Israel";
Cursor cursor = db.query(TABLE_NAME, new String[] {VALUE}
        ,VALUE + " like " + "'%" + s +"%'", null, null, null, null);

I get an exception .

A: You don't need to add anything special into the android manifest. You can open the database from anywhere, i.e. also from your sdcard or else. Otherwise, A common place to put the database is in to the assets folder of your application.
When you create the db outside the android project, just make sure you either create the metadata table (as mentioned in the Android docs) or set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase(). Also you should note that the primary key in all tables is _id. These are the most important things to consider when creating a new DB.
Also helpful regarding the metadata-table might be:
What is the android_metadata table?
No such table android_metadata, what's the problem?
Helpful blog:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/


text:
Q: Calling base component's methods/features Having Base.vue
<template><div>{{ name }}</div></template>
<script>
  export default {
    data() {
      return {name: 'Example Component'};
    }
  };
</script>

And Extended.vue:
<script>
  import Base from './Base.vue';
  export default {
    extends: Base,
    data() {
      return {name: 'Extended Example Component'};
    }
  };
</script>

Is it possible to reuse data from base one instead of hardcoding Extended Example Component? Some kind of super from OOP? Looking for generic solution involving stuff like mount, methods, computed, etc.
UPDATE
When using OOP we use such approach (Python example):
class Base:
   def __init__(self):
       self.name = 'Example Component'

class Extended(Base):
   def __init__(self):
       super().__init__()
       self.name = f'Extended {self.name}'

This way we reuse self.name field.

A: extends and mixins merge options in a specified way, this is the official way to inherit component functionality. They don't provide full control over the inheritance.
For static data that may change between component definitions (Base and Extended) custom options are commonly used:
export default {
  myName: 'Component',
  data() {
    return { name: this.$options.myName };
  }
}

and
export default {
  extends: Base,
  myName: `Extended ${Base.options.myName}`
}

Notice that name is existing Vue option and shouldn't be used for arbitrary values.
Any reusable functions can be extracted from component definition to separate exports.
For existing components that cannot be modified data and other base component properties can be accessed where possible:
  data() {
    let name;

    name = this.$data.name;
    // or
    name = Base.options.data.call(this).name;

    return { name: `Extended ${name}` };
  }

This approach is not future-proof and not compatible with composition API, as there's no clear distinction between data, etc, and this is unavailable in setup function. An instance can be accessed with getCurrentInstance but it's internal API and can change without notice.

A: The data object is a kind of state for a single component, hence the data object inside a component can only be accessed in that component and not from outside or other components.
For your specific requirement, you can use Vuex. It helps you access the state in multiple components. Simply define a state in the vuex store and then access the state in the component.
If you don't want to use Vuex, then another simple solution is to store the data in localStorage and then access the data in multiple components.

A: You can access your data, from child component. You can do that by this.$parent.nameOfTheDataYouHave.
This cheatsheet can help you with the basics of the component anatomy and lifecycle hooks(mounted,created,etc..).
And last this is the proper way of two-way binding data (parent-child).


text:
Q: Make Script A interact with Script B (Bash) I have this bash script that runs calculus operations for me. It starts off with "read"...
How can I make Script A enter a value into Script B, read the output and dismiss Script B again?
Example:
#ScriptA.sh
a=12
b=4
[open Script B, enter $a and $b and read the result]
echo "The result is [the result of Script B]."

#ScriptB.sh
read x y
echo $(($x+$y))

Desired Output:
bash ScriptA.sh
The result is 16.

Of course it's about more complex maths but you get the idea. Note that, for convenience purposes, I don't want to change the structure of Script B (read x y). But I hope that there are some guys here that can solve this problem.
Thanks in advance.

A: You should do something like this:
#!/bin/bash

a=12
b=4

result=$(echo $a $b | ./script_b.sh)
echo "the result is $result"

A: Script B should work like -bc does.
Example:
echo `echo "4^3.5" | -scriptb.sh`
[result]

Edit: I just came up with a part of the solution by myself and thought I'd share it:
# ScriptA.sh

echo `echo "44 33" | bash ScriptB.sh`

# ScriptB.sh

read x y
echo $(($x+$y))

Output:
bash ScriptA.sh
77

The next problem is my ScriptB.sh looks a little more like this:
# ScriptB.sh

until [[ 1 = 2 ]]; do
echo Enter x and y
read x y
    if [[ x = q ]]; then
    break 1
    fi
echo $(($x+$y))
done

This is in order to allow multiple inputs, if I want to use ScriptB manually. If I let ScriptA use ScriptB in the above mentioned way the output looks like this:
bash ScriptA.sh
b.sh: line 9: +: syntax error: operand expected (error token is "+")
Enter x and y 77 Enter x and y

It seems to be the case that after ScriptA inputs 44 and 33 and hits enter, like it should, but it hits enter right away a second time triggering the syntax error message and ending ScriptB. This is suboptimal, because in the case of the real ScriptB it will enter a "(standard_in) 1: parse error"-chain, resulting in no result at all. The solution to this problem would be by teaching ScriptA to read what ScriptB promts as result and ending it right after this. Or making it enter "q" as a second input instead of just hitting enter.
Edit 2:
Ok. Got it. Script A should look like this in order to work as desired:
e=2.7182818285
pi=3.141
a=$(printf "$e $pi \n q \n" | bash ScriptB.sh)
a=${a:14:20}
echo $a


text:
Q: Measure of curve smoothness Could someone please give me the intuition behind using integral of squared second derivative as a measure of curve smoothness?
I was thinking that since curvature measures how fast a curve changes, should we not be integrating the square of curvature? Basically why are we ignoring the denominator from the definition of curvature before even checking if first derivative is small enough.
This is also used in Smoothing Splines so I guess there is something to it then just being a mere approximation.

A: You are correct. Second derivatives are not really the right thing to be considering. The main issue is that second (and other) derivatives are dependent on the parameterization of the curve, whereas "smoothness" is a geometric property that is independent of parameterization. We should really be considering parameterization-independent quantities like curvature and derivative of curvature with respect to arclength. But curvature is a nasty non-linear function, and using derivatives is much easier.
In fact, you might even say that the whole idea of cubic splines (enforcing continuity of second derivatives) is wrong. We ought to be enforcing continuity of curvature, instead. This has been done -- there are splines that have so-called "geometric continuity". This is an old idea, going back to Even Mehlum's KURGLA system in the 1970s. Again, it's more correct, but the computations are much more difficult, and the results often don't justify the effort.
The answers to this question have some further discussion.

A: Using integral of squared second derivatives allows the functional to be minimized to become a quadratic form of the unknowns (i.e., control points of the spline), which eventually will result in a linear equation set, which is easy to solve. This is actually similar to the famous "least square" method which minimizes the sum of the squared errors, instead of the sum of errors, so as to result in a linear equation set.

A: Indeed, it is analogous to root mean square computations. When profile changes, curvature and smoothness change and the former is a good differential computable index of the latter parameter.
If such a powerful indicator as curvature is anyway taken as a feel factor, the denominator with its first degree is  not anymore considered as a better physical indicator of smoothness retaining its inclusion, as any how next derivative change is reported into the numerator. Result is practically same for roughness levels normally encountered.
From Mechanics of Materials Beam theory an example can be given. For low slopes of beam center line when  $ \frac{dy}{dx}<<1$ no practical extra advantage is seen when curvature is defined as $ \frac{d^2y}{dx^2}$ or $ \frac{d^2y/dx^2}{(1+ (dy/dx)^2)^{1.5}}.$


text:
Q: Pre-processing emails sent with external client through AWS SES SMTP I have several external email clients configured to send from alias (my domain) address through SES SMTP using TLS. I'd like to catch emails to modify and then to send to destinations.
As i can guess, the straight approach is to launch a public AWS instance capable of TLS connection + SMTP receiving, doing my job and sending with SES API. Taking such emails are sent only by my colleagues from remote locations, credentials+TLS are enough, and AWS SES will provide with DKIM/DMARC. So I need to implement the first two steps the simplest way.
Please advice me a robust Linux software for this task. Or the most primitive, but reliable node.js library(-ies). Or, maybe, another solution?
Thank you in advance, this is not "save me a cent" case, indeed. I just need to add some automation to manually sent emails.


text:
Q: How to get list of data from foreign key associated table is json format in mvc I have created two tables(question,answer) with foreign key association,I need list of answers based on questionID column for that I need linq query. I am beginner to mvc,Can anyone help to me

Controller code:

public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  join a in Db.answers on q.Qid equals a.questionID
                  select new { q.QText, q.Qid, a.answer1 };
     return Json(result, JsonRequestBehavior.AllowGet);
}

json Result:
[
    {"QText":"result of 2+2","Qid":2,"answer1":"2"},
    {"QText":"result of 2+2","Qid":2,"answer1":"4"},
    {"QText":"result of 2+2","Qid":2,"answer1":"6"},
    {"QText":"result of 2+2","Qid":2,"answer1":"8"}
]

But i need like below:
{
   "QText": "result of 2+2",
   "Qid": 2,
   "answer1": [
      { "option1": "2" },
      { "option1": "4" },
      { "option1": "6" },
      { "option1": "8" }
   ]
}

A: Don't do a join, instead, get the question information you want and then do a subquery to get the answers for the specific question:
public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  select new {
                    q.QText,
                    q.Qid,
                    answer1 = (from a in Db.answers
                               where a.questionID == q.Qid
                               select new { option1 = a }).ToList()
                  };

     return Json(result, JsonRequestBehavior.AllowGet);
}


text:
Q: How to run the Node API tests for browser-perf I am trying to configure browser-perf for measuring browser performance metrics. I am able to run it via commandline using
browser-perf --selenium=http://localhost:4444/wd/hub http://yourwebsite.com

However, I want to configure the Node Module API for browser-perf.
Following is the issue:
1. I am not able to find a command to execute the node API browser-perf tests.
2. Also, where do I place the call to browserPerf() - In conf OR in spec ??
If someone can provide steps for the Node API setup, that would be really helpful!
PS: I found protractor-perf conf.js command is used to protractor-perf tests. Just not able to find something similar for browser-perf!

A: The below link gives all the necessary steps to setup and execute browser-perf tests
https://gist.github.com/axemclion/9594795


text:
Q: errors when i'm compiling my project when i'm compiling my project i will get a lot of errors:
1>------ Build started: Project: cpp-uri, Configuration: Debug x64 ------
1>  uri_builder.cpp
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(45): error C2065: 'void_': undeclared identifier
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(46): error C2923: 'network_boost::mpl::is_void_': 'void_' is not a valid template type argument for parameter 'T'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(51): error C2913: explicit specialization; 'network_boost::mpl::is_void_' is not a specialization of a class template
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(63): error C2065: 'void_': undeclared identifier
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(64): error C2923: 'network_boost::mpl::is_not_void_': 'void_' is not a valid template type argument for parameter 'T'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(69): error C2913: explicit specialization; 'network_boost::mpl::is_not_void_' is not a specialization of a class template
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2913: explicit specialization; 'network_boost::mpl::is_void_' is not a specialization of a class template
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2988: unrecognizable template declaration/definition
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2143: syntax error: missing ';' before '<'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2059: syntax error: '<'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2143: syntax error: missing ';' before '{'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): error C2447: '{': missing function header (old-style formal list?)
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(72): error C2913: explicit specialization; 'network_boost::mpl::is_not_void_' is not a specialization of a class template
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(72): error C2977: 'network_boost::mpl::lambda': too many template arguments
1>  c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(71): note: see declaration of 'network_boost::mpl::lambda'
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(72): error C3646: 'is_le': unknown override specifier
1>  c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(72): note: see reference to class template instantiation 'network_boost::mpl::lambda<Tag>' being compiled
1>c:\gta-five\multiplayer\vendor\cpp-uri\src\boost/mpl/void.hpp(72): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

i must get a cpp-uri.lib but i get a huge list of errors
vs2015 boost 1.58

A: The below link could help you fix this,
Undeclared identifier (error C2065) in c++
Basically, looks like you have not included the "using namespace" or missing out on adding few headers


text:
Q: Can a range-based for loop take a type argument? From what I can tell, range-based for loops can only take a c-style array, an object of a type that has the member functions begin() and end() defined, or an object of a type Type for which the free functions begin(Type) and end(Type) can be found with ADL.
Is there a way to make the loop take a type argument, so code like this compiles?
class StaticVec{
//shortened implementation
    static myIterator begin();
    static myIterator end();
};

void foo() {
    for(auto elem : StaticVec){
       dosomething(elem);
    }
}

I would like to omit the necessity of writing StaticVec::values() in the loop.

A: As a general solution you can define
template< class Type > struct Static_collection {};

template< class Type >
auto begin( Static_collection<Type> const& )
    -> decltype( Type::begin() )
{ return Type::begin(); }

template< class Type >
auto end( Static_collection<Type> const& )
    -> decltype( Type::end() )
{ return Type::end(); }

and then you can write e.g.
auto main() -> int
{
    for( auto elem : Static_collection<Static_vec>() )
    {
        std::cout << elem << ' ';
    }
    std::cout << '\n';
}

Addendum:
In most practical cases it will however suffice to just create an instance of the class holding the static begin and end member functions, as shown in Jarod42's and Matt McNabb's answers (the former already posted when I posted the above), e.g.
for( auto const& elem : StaticVec() )
{
    // ...
}

If instance creation can have undesirable side effects, now or perhaps after some future maintainance work, then use the general solution.
Otherwise, if instance creation is essentially free, I'd go for that.

A: You may still (if applicable) construct a dummy object:
for (auto&& elem : StaticVec{}) {
    // ...
}

A: It's definitely not possible. The range variable in your example is StaticVec (which is not a variable) so the code it expands to would involve either auto it = StaticVec.begin() or auto it = begin(StaticVec) and neither of those expressions is valid, the function calls require an object not a type.

A: This works because static member functions can still be called via . notation:
#include <iostream>
using namespace std;

struct StaticVec
{
    typedef int *myIterator;
    static int x[5];
    static myIterator begin() { return x; }
    static myIterator end() { return x + 5; }
};

int StaticVec::x[5] = { 10, 20, 30, 40, 50 };

void dosomething(int i)
{
cout << i << endl;
}

int main()
{
    for(auto elem : StaticVec())
    {
       dosomething(elem);
    }
}


text:
Q: Visual Studio add CN= in Identity Publisher Field in appxmanifest File I'm currently developping an UWP application for another company. I don't have the real certificate used to sign the app so i tried to generate a temporary certificate using a given publisher name. The publisher name should look like this so the other company could override the appxbundle signature:

E=email@company.com, CN=COMPANY NAME, O=COMPANY NAME, L=City, S=Region, C=FR

I tried to generate a certificate using these commands:
"C:\Program Files (x86)\Windows Kits\10\bin\x64\makecert.exe" -r -n "E=email@company.com, CN=COMPANY NAME, O=COMPANY NAME, L=City, S=Region, C=FR" -sv mycert.pvk mycert.cer

"C:\Program Files (x86)\Windows Kits\10\bin\x64\pvk2pfx.exe"  –pvk infoliaison.pvk –spc mycert.cer –pfx mycert.pfx –po mycert

or
New-SelfSignedCertificate -Type Custom -Subject "E=email@company.com, CN=COMPANY NAME, O=COMPANY NAME, L=City, S=Region, C=FR" -KeyUsage DigitalSignature -FriendlyName myproject -CertStoreLocation "Cert:\LocalMachine\My"

but Visual studio 2015 refuses to import them. I checked and they are not expired
If I try to generate a test certificate with visual studio with my publisher, the manifest in the appxbundle is modified like this:

<Identity Name="[...]" Publisher="CN="E=email@company.com, CN=COMPANY NAME, O=COMPANY NAME, L=City, S=Region, C=FR""/>

Is there any way i can do this?

A: I finally managed to create a valid certificate, working with Visual Studio with the following command in powershell with admin rights
New-SelfSignedCertificate -Type Custom -Subject "E=email@company.com, CN=COMPANY NAME, O=COMPANY NAME, L=City, S=Region, C=FR" -KeyUsage DigitalSignature -FriendlyName myproject -CertStoreLocation "Cert:\LocalMachine\My" -TextExtension '2.5.29.37={text}1.3.6.1.5.5.7.3.3','2.5.29.19={critical}{text}ca=0'

I then exported the certificate in a pfx file and used it to sign my app


text:
Q: Connecting from Azure Automation to Office 365 PowerShell Endpoint fails half way through script I have a script running under an Azure Automation account. The script connects to the Office 365 endpoint (https://outlook.office365.com/powershell-liveid/), and uses Set-Contact to update some contact information for 5000 contacts (I inherited this so please don't ask :)). The script is running for just over 57 minutes.
The issues I am now starting to get is that 2000 contacts are being updated, then I get the following errors in the logs:
Starting a command on the remote server failed with the following error message : The I/O operation has been aborted because of either a thread exit or an application request. For more information, see the about_Remote_Troubleshooting Help topic.

I get this once, then I get:
Exception calling "GetSteppablePipeline" with "1" argument(s): "Exception calling "PromptForCredential" with "4" argument(s): "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Enter your credentials for https://outlook.office365.com/powershell-liveid/.""

The commands being used to connect are (nothign complicated):
$a = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/powershell-liveid/' -Credential $Credential -Authentication Basic -AllowRedirection -Erroraction Stop
Import-PSSession -Session $s -CommandName New-MailContact, Set-Contact, Remove-MailContact -AllowClobber | Out-Null

What it looks like is the remote session is re-requesting login. If that is the case I'm wondering under what circumstances it would do that (for example does the session have a set time and then asks for authentication).
Can anybody shed any light on why this is occurring and what I can do to resolve it?

A: Don't ask why, but just delete and import a new session every 50 contacts. I do that to update the picture of +1000 users. And I still get this issue.
I don't think MS want to provide a better solution for massive update.


text:
Q: Hover Submenu (jQuery) I have a hover submenu set up that is ALMOST working 100%.... only problem is that on page load the menu is not hidden. Once you hover it one time it works normally but I am trying to hide it on page load. Any ideas would be much appreciated
<script>

$(document).ready(function() {

$('.nav2').hide();
$(".nav").hover(function() {
$(this).find('.nav2').show();
},
function() {
$(this).find('.nav2').hide();
});

});
</script>

A: Maybe add a "display: none" style property to your .nav2 container


text:
Q: Bash syntax errors like `syntax error: operand expected (error token is "{1 % 2 ")` Please tell why printing odd numbers in bash script with the following code gives the error:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done

A: To print odd numbers between 1 to 99
seq 1 99 | sed -n 'p;n'

With GNU seq, credit to gniourf-gniourf
seq 1 2 99

Example
$ seq 1 10 | sed -n 'p;n'
1
3
5
7
9

if you reverse it will print even
$ seq 1 10 | sed -n 'n;p'
2
4
6
8
10

A: This is working example:
for i in {1..99}
do
        rem=$(($i % 2))
        if [ "$rem" -ne "0" ]; then
                echo $i
        fi
done

*

*used for loop have a typo in minimum and maximum number, should be {1..99} instead of {1 to 99}

*brackets of the if statement needs to be separated with whitespace character on the left and on the right side

*Comparision is done with ne instead of neq, see this reference.

As already pointed out, you can use this shell checker if you need some clarification of the error you get.

A: One liner:
for odd in {1..99..2}; do echo "${odd}"; done

Or print in a cluster.
for odd in {1..99..2}; do echo -n " ${odd} "; done

Likewise, to print even numbers only:
for even in {2..100..2}; do echo "${even}"; done

OR
for even in {2..100..2}; do echo -n " ${even} "; done

A: Not really sure why nobody included it, but this works for me and is simpler than the other 'for' solutions:
for (( i = 1; i < 100; i=i+2 )); do echo $i ; done

A: Replace {1 to 99} by {1..99}.

A: for (( i=1; i<=100; i++ ))
do
    ((b = $i % 2))
  if [ $b -ne 0 ]
    then
    echo $i
fi
done

A: for i in {1..99}
do
    rem=`expr $i % 2`
    if [ $rem == 1 ]
    then
        echo  "$i"
    fi
done

A: for i in {0..49}
do
 echo $(($i*2+1))
done


text:
Q: Initializing struct member of type struct pointer to null I'm having an issue with assigning a null value to a pointer to a struct member (that is also a pointer to a struct). The following code correctly sets the headNode->right variable equal to null, but not the headNode->left variable.
typedef struct node {
    char *key;
    int frequency;
    struct node *left;
    struct node *right;
    struct node *parent;
} node;

void addKey(char key[]) {
    extern node *headNode;
    node *newNode;

    if (headNode != NULL) {
        printf("Head node is initialized\n");
        if (headNode->left != NULL) printf("    Left is not null\n");
        if (headNode->right != NULL) printf("    Right is not null\n");
    }

    newNode = malloc(sizeof(node*));
    newNode->key = malloc(sizeof(char) * (strlen(key) + 1));
    newNode->left = malloc(sizeof(node*));
    newNode->right = malloc(sizeof(node*));
    newNode->parent = malloc(sizeof(node*));

    newNode->left = newNode->right = NULL;
    newNode->frequency = 1;
    newNode->right = NULL;
    strcpy(newNode->key, key);

    // If this is the first node, assign it as the root
    if (headNode == NULL) {
        newNode->parent = NULL;
        headNode = newNode;
        return;
    }
}

However, if I add the following two lines right before the return statement, it works correctly.
if (headNode->left == NULL) printf("L is null\n");
else printf("L is NOT null\n");

I don't understand how an if statement can make a difference. There is nowhere else that assigns or changes the value of this variable anywhere else in my code.

A: All the malloc(sizeof(node*)) should be malloc(sizeof(node)). You're only alloocating enough space for a pointer, not the whole structure. This is causing undefined behavior with all the following code that indirects through these pointers.

A: Take a step back. There are a number of serious mistakes here.
You declare a pointer to a node:
node *newNode;
So far, so good. However, when you try to allocate memory for this new node, you only allocate enough to store a pointer, instead of the node itself:
newNode = malloc(sizeof(node*));
You already have storage for the pointer: newNode.
Change this line to:
newNode = malloc(sizeof(node));
A little later you make three more unnecessary calls to malloc:
newNode->left = malloc(sizeof(node*));
newNode->right = malloc(sizeof(node*));
newNode->parent = malloc(sizeof(node*));

If you had requested enough memory (i.e. sizeof(node)) in the previous call, there would be no need to allocate any more memory for these internal fields. You would already have memory for them; it would already exists at the address pointed to by newNode.
Worse still, you then go on to leak memory on the next line:
newNode->left = newNode->right = NULL;
Here you are throwing away the addresses of the memory you allocated unnecessarily.
I think you need to read up on memory management further before we can troubleshoot this problem for you.


text:
Q: Task module popup content sometimes fail to load on MacOS Teams desktop client When invoking the task module popup from Teams macOS desktop client, sometimes the content never loads. We have previously been able to replicate this issue on the windows desktop client (less frequently than macos) but that seems to have resolved itself without us making any changes. We are unable to replicate the issue on Web, android and IOS clients. We do not see anything unusual on the application, console and fiddler logs. This makes me think that there is an issue with the Macos client. See linked recording of the issue
1: https://share.cleanshot.com/QrjT3s. Wait till the end when the last attempt fails to render.
Here is a link to the manifest file:


text: Q: Meu Xamarin só está funcionando na versão debug! Durante minhas aplicações, meu xamarin começou a rodar só em debug, quando altero para solução release, ele continua usando o debug. Já tentei reiniciar o pc, baixar o projeto novamente, alterar algumas configs, porém NADA. Alguém já teve esse problema? obrigado.


text:
Q: Write CSV file into vectors I have 8x14800 matrix that has been  extracted from matlab as CSV file ("moves.mo").
I need to read this file into 14800 vectors with 8 values each. Can you please navigate me here?
So far, I am here:
std::fstream inputfile;
inputfile.open("moves.mo");
std::vector< std::vector<int>* >  vectorsmovesList;

while (!inputfile.eof()) {
    std::string line;
    getline (inputfile,line);
    if(""!=line) {        //if line is nonempty

       std::vector<int>* mvec = new std::vector<int>(); //allocate a vector vec(N)
 /* loop to read file has to go here */
           }
inputfile.close();

}

return 0;
}

Thank you very very much!!!!

A: see Split a string in C++?


text:
Q: How to clean up these types of duplicated else blocks? I find myself frequently working on codebases that contain logic like this:
var _deliveryType = new Dictionary<String, String>();
if (_deliveryType.ContainsKey(fileName)) {
      if (contactPreference == SAMPLE_ENUM) {
         //Perform Action 1
      } else {
         //Perform Action 2
      }

} else {
    //Perform Action 2
}

The gist of the issue is that if there's nothing matching that key/value pair, it falls into the outer else block, but if the key does exist and it doesn't have a certain value associated with it, the exact same action as the outer else is performed.
What's the best way to simplify this logic so that I'm not calling the same method twice? This is really stupid but I just can't think of a good way to clean this up.

A: A very simple answer to this could be to just merge the two if statements into one.
var _deliveryType = new Dictionary<String, String>();
if (_deliveryType.ContainsKey(fileName) && contactPreference == SAMPLE_ENUM) {
    //Perform Action 1
} else {
    //Perform Action 2
}

A: if your method call is like return Foo(), then u dont need else. But this is only if you are returning
var _deliveryType = new Dictionary<String, String>();
if (_deliveryType.ContainsKey(fileName)) {
      if (contactPreference == SAMPLE_ENUM) {
         return action1()
      }
         return action2();

}
  return action2();

A: Try something like
var _deliveryType = new Dictionary<String, String>();
if (!_deliveryType.ContainsKey(fileName) && contactPreference != SAMPLE_ENUM ) {
  //Perform Action 2
}else {
  //Perform Action 1
}

A: If the real problem is repeated code: remember to stay DRY (Don't Repeat Yourself). Refactor.
A first cut might be to extract the repeated code into stand-alone methods:
void DoAction1( Dictionary<string,string> dict )
{
  // perform action 1
}
void DoAction2( Dictionary<string,string dict )
{
  // perform action 2
}

Dictionary<string,string> _deliveryType = GetDeliveryType() ;
if (_deliveryType.ContainsKey(fileName))
{
  if (contactPreference == SAMPLE_ENUM)
  {
    DoAction1(_deliveryType) ;
  }
  else
  {
    DoAction2(_deliveryType) ;
  }
}
else
{
  DoAction2(_deliveryType) ;
}

That's helpful, but you still have to expend cycles in the wetware contemplating the 3-way branch. A further refactoring might be, as noted, to then refactor the if-then-else logic itself:
Dictionary<string,string> _deliveryType = GetDeliveryType() ;
bool isAction1 = _deliveryType.ContainsKey(fileName) && contactPreference == SAMPLE_ENUM ;
if ( isAction1 )
{
  DoAction1(_deliveryType) ;
}
else
{
  DoAction2(_deliveryType) ;
}

You could use a delegate and simplify things further:
Dictionary<string,string> _deliveryType = GetDeliveryType() ;
Action<Dictionary<string,string>> action = _deliveryType.ContainsKey(fileName) && contactPreference == SAMPLE_ENUM ? DoAction1 : DoAction2 ;

action(_deliveryType) ;

Now your down to pretty much a straight-line flow of control.


text:
Q: How to automate an upload process with talend whenever a file is moved into a specific folder I have zero experience with ETL.
Whenever a file(a .csv) is moved into a specific folder, it should be uploaded to SalesForce I don't know how to get this automated flow.
I hope I was clear enough.
I gotta use the opensource version, any helpful links or resources will be appreciated.
Thank you in advance

A: You could definitely use Talend Open Studio for ESB : this studio contains 'Routes' functionalities : you'll be able to use a cFile component, which will check your folder for new files, and raise an event that will propagate throughout the route to a designed endpoint (for example a salesForce API). Talend ESB maps Apache Camel components , which are well documented.
Check about Routes with Talend for ESB, it should do the trick.

A: We have tFileExists component, you can use that and configure to check the file.
Also you have tFileWait component, where you can defile the frame of the arrival of he files and the number of iterations it has to check the file.
But i would suggest id you have any scheduling tool, use file watcher concept and then use talend job to upload the file to a specific location.
Using talend itself to check the file arrival is not a feasible way as the jobs has be in running state continuously which consumes more java resource


text:
Q: ToolTip on DatagridView freezes application when PerMonitorV2 DPI awareness is enabled This issue can be fully recreated in the VS WinForms designer + manifest, hence why the question is devoid of any code.
The setup is as follows:

*

*Have two screens, main screen scaled to 100%, second to 125%

*Create a new .NET Framework 4.7.2 WinForms application

*Add a DatagridView and ToolTip from the toolbox

*Via the designer, assign some tooltip text to the DatagridView (calls SetTooltip)

*Add an application manifest that enables PerMonitorV2 awareness:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
        <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
    </windowsSettings>
</application>

*

*Start the application on the main screen, then move it over to the secondary screen

*Hover the mouse over the DatagridView
The application freezes with a single CPU core fully busy. It seems to be stuck at
System.Windows.Forms.dll!System.Windows.Forms.ToolTip.WmShow(), or a DefWndProc, fluctuating on where I "Break all" to get the call stack. Unfortunately I couldn't debug it further than this. Please find a full call stack at the end.
Further observations are:

*

*It does not happen if PerMonitor instead of PerMonitorV2 is used.

*If the secondary screen is unplugged or even just scaled to 100% in-situ, the application immediately unfreezes.

*It seems to be independent of the targeted framework. I tested 4.5 through 4.8 and even the new .NET 5.0 template in VS.

*It works fine if other control types are used - I only found the DatagridView to have this issue

*It's independent of the EnableWindowsFormsHighDpiAutoResizing setting in app.config

My system is:

*

*Windows 10 Pro 21H1

*OS build 19043.1526

*Experience Windows Feature Experience Pack 120.2212.4170.0

Is there something that must be implemented in PerMonitorV2 vs. PerMonitor that could cause this issue? Is it just a bug in the .NET Framework?
A full call stack of the main thread while it is hanging. It is fluctuating somewhat depending on where I break all. But the main parts are captured here:
    [Managed to Native Transition]
    System.Windows.Forms.dll!System.Windows.Forms.ToolTip.WmShow()  Unknown
    System.Windows.Forms.dll!System.Windows.Forms.ToolTip.WndProc(ref System.Windows.Forms.Message msg) Unknown
    System.Windows.Forms.dll!System.Windows.Forms.ToolTip.ToolTipNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown
    System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg = 8270, System.IntPtr wparam, System.IntPtr lparam)   Unknown
    [Native to Managed Transition]
    [Managed to Native Transition]
    System.Windows.Forms.dll!System.Windows.Forms.Control.WmNotify(ref System.Windows.Forms.Message m)  Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m)   Unknown
    System.Windows.Forms.dll!System.Windows.Forms.DataGridView.WndProc(ref System.Windows.Forms.Message m)  Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown
    System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg = 78, System.IntPtr wparam, System.IntPtr lparam) Unknown
    [Native to Managed Transition]
    [Managed to Native Transition]
    System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DefWndProc(ref System.Windows.Forms.Message m = {System.Windows.Forms.Message})  Unknown
    System.Windows.Forms.dll!System.Windows.Forms.ToolTip.WndProc(ref System.Windows.Forms.Message msg) Unknown
    System.Windows.Forms.dll!System.Windows.Forms.ToolTip.ToolTipNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown
    System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg = 275, System.IntPtr wparam, System.IntPtr lparam)    Unknown
    [Native to Managed Transition]
    [Managed to Native Transition]
    System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(System.IntPtr dwComponentID, int reason = -1, int pvLoopData = 0) Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason = -1, System.Windows.Forms.ApplicationContext context = {System.Windows.Forms.ApplicationContext})   Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) Unknown
    System.Windows.Forms.dll!System.Windows.Forms.Application.Run(System.Windows.Forms.Form mainForm)   Unknown
>   CrashTest.exe!CrashTest.Program.Main() Line 19  C#

Addendum:
On Jimi's suggestion (see comment) I experimented with cell-specific tooltips and found out that it doesn't freeze if...

*

*dgv.ShowCellToolTips is set to false
or with ShowCellToolTips = true...

*The mouse is on a cell or header that displays a tooltip on its own e.g. via cell.ToolTipText
In the latter case, it still freezes when the mouse is moved to e.g. the background instead.
Demo:


text:
Q: Bash script not piping through commands I have the following bash script running on Mac El Capitan that does not produce the correct output, but when I  ran a sequence of these same commands on the command line, it worked. I am trying to create a bash script so I don't have to do these commands every time I want to find the parent directories of the files in the logs that generate a certain error code.
Here is a redacted excerpt of a log file:
[2016/06/16 18:11:38] [12.34.56.789] [username] [R] D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/001 Drafts/
[2016/06/16 18:11:39] [12.34.56.789] [username] [R] D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/
--
--
[2016/06/17 15:57:20] [12.34.56.789] [username] [R] [Upload] [D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/12-15-13 IW CCTV Inspect/My Pane/3637/2013.08.14_0922/SnapShots/36_37_MGP_101.4.jpg] [182.27 KB]
[2016/06/17 15:57:26] [12.34.56.789] [username] [R] [Upload] [D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/12-15-13 IW CCTV Inspect/My Pane/3637/2013.08.14_0922/SnapShots/36_37_MGP_330.2.jpg] [174.96 KB]
[2016/06/17 15:57:26] [12.34.56.789] [username] [R] Number of files considered for upload: 999
[2016/06/17 15:57:26] [12.34.56.789] [username] [R] Number of files uploaded: 135
[2016/06/17 15:57:27] [12.34.56.789] [username] [R] Number of files in sync: 864
[2016/06/17 15:57:27] [12.34.56.789] [username] [R] idevs error: some files could not be transferred (code 23) at main.c(1234) [generator=1.0.19]

[2016/06/17 09:37:08] [12.34.56.789] [username] [R] receiving file list
[2016/06/17 09:37:17] [12.34.56.789] [username] [R] D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/12-15-13 IW CCTV Inspect/My Pane/3738/
[2016/06/17 09:37:17] [12.34.56.789] [username] [R] D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/12-15-13 IW CCTV Inspect/My Pane/3738/2013.08.14_0941/
[2016/06/17 09:37:17] [12.34.56.789] [username] [R] D/Data/Shared/Files/ABC Real Estate - Not the bridge Project/Formal Discovery/2016-04-27 Docs from OC (to be processed)/12-15-13 IW CCTV Inspect/My Pane/3738/2013.08.14_0941/Reports/

Here is my current script that I have tried so many things on:
#!/bin/bash

code23() {

egrep 'code\ 23' -C5 $1 | egrep '\[[A-Z]\/.*' | awk -F\] '{print $6}' | tee ${1}_code_error_files.txt

awk -F\/ '{print $1 "/" $2 "/" $3 "/"}' ${1}_code_error_files.txt | sed 's/\[//g' | sed 's/^\s*\[//g' | sort -u | tee ${1}_code23_errors_dirs.txt

}

if [[ -z $1 ]]; then
   echo "Usage: $ bash get_errors logfile.txt"
   echo "Please use a file containing the IDrive or IBackup command logs."
else
   code23
fi

The series of commands I ran were in the above-referenced function code23()
What I do is download the logs from my UI as rtf files. I cat those files into one file. Bash has no problem reading these as text files. I ran the following series of commands on these files and it have me the desired output, which is to get the parent directories of the lines that have a code 23 error:
`egrep 'code\ 23' -C5 error_file.txt egrep '\[[A-Z]\/.*' | awk -F\] '{print $6}' | sort -u > output_file.txt`
# This successfully printed the full file path of the file that caused the error.

`awk -F\/ '{print $1 "/" $2 "/" $3 "/" }' output_file.txt | sort -u`
 # This successfully prints the first three directories of the folders that contain errors.

 'sed 's/\[//g' output_file.txt
 # I edited the output file with vim to clean it up, by removing the spaces in front of each line, and remove the `[` in front of each directory.

Please let me know what I am doing incorrectly.
Thanks to all of your help, I edited the code as follows and it works great now:
#!/bin/bash

code23() {

egrep 'code\ 23' -C5 $1 | egrep '\[[A-Z]\/.*' | awk -F\[ '{print $7}' | sort -u | tee $1_code23_error_files.txt | awk -F\/ '{print $1 "/" $2 "/" $3 "/"}' | sed 's/^\s*\[//g' | sort -u | tee $1_code23_error_dirs.txt

}

if [[ -z "$1" ]]; then
   echo "Usage: $ bash get_errors logfile.txt"
   echo "Please use a file containing the ABC Company or XYZ Company command logs."
else
   code23 "$1"
fi

Thank you!

A: Your script doesn't forward its arguments to code23. Functions in bash don't inherit the command line arguments ($1, $2, etc) of the parent script. You must call a bash function, explicitly providing arguments to it (as if it were a separate program):
code23 "$1"


text:
Q: How to change the view of the previous fragment after returning to it using the back button? I have an activity with two fragments.
The second one is called when I click on something to the first.
What I want is this : if i click on "back" button, I want to go back to the first fragment (that is working), but I want to set the visibility to VISIBLE on an element (if the first fragment is called with back press only)
How do I do that ?
I tried something like this (in my main fragment), I've found the idea in another topic, but this is trigger always in my main activity :
    override fun onResume() {
    super.onResume()
    view?.isFocusableInTouchMode = true
    view?.requestFocus()
    view?.setOnKeyListener { v, keyCode, event ->
        if(event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
            Log.i(TAG, "backpress pressed")
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }
}

Temporary solution :
I've created a companion object with a value true or false and I change it everytime I need it, but it's temporary only.

A: Assuming your second Fragment replaces the first (i.e. using FragmentTransaction#replace), your first Fragment (we'll call them FragmentA and FragmentB) will be paused (i.e. onPause() will be called on FragmentA).
When you press the back button, the backstack will be popped, and FragmentA will be resumed (i.e. onResume() will be called).
What I would recommend, is to save a boolean flag in FragmentA, and set it to true when you show FragmentB. Then, in FragmentA#onResume, you can check if the flag is set to true, and set it back to false while handing the case that you wanted.
For example, something like:
private const val STATE_WAITING_FOR_FRAGMENT_B = "state_waiting_b"

class FragmentA : Fragment() {
    private var isWaitingForFragmentB: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {
            isWaitingForFragmentB = savedInstanceState.getBoolean(STATE_WAITING_FOR_FRAGMENT_B)
        }
    }

    override fun onResume() {
        super.onResume()
        if (isWaitingForFragmentB) {
            isWaitingForFragmentB = false
            // handle your view state here
        }
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        savedInstanceState.putBoolean(
            STATE_WAITING_FOR_FRAGMENT_B,
            isWaitingForFragmentB
        )
    }

    private fun showFragmentB() {
        isWaitingForFragmentB = true
        // do fragment transaction here
    }
}

A: I'm not good at grammar.
First fragment do not call resume function when returning.
You must create callback with interface.

A: A good approach should be passing some flag, on the second fragment, by activity intent and to capture it on the first Fragment on onResume()
If you need extra info, just let me know


text:
Q: how to combine two update statements I have two following update statements:
update tb1
set col1=1
where id in ('1', '2', '3')

update tb1
set col1=0
where id not in ('1', '2', '3')

Can I combine above two update statements into one?

A: Try this:
UPDATE tb1 SET col1= CASE WHEN id in ('1', '2', '3') THEN 1 ELSE 0 END

A: UPDATE tb1
SET col1 = CASE WHEN id in (1, 2, 3)
                    THEN 1
                WHEN id NOT IN (1, 2, 3)
                    THEN 0
                ELSE
                    col1
           END ;