text:
Q: Stream radio is not working with Media Player in Android I'm working in an android application. I have a problem trying to playback a radio stream. The url is:
http://2583.live.streamtheworld.com/XHMFMAAC?type=.flv

I also try with:
http://2583.live.streamtheworld.com/XHMFMAAC

And with:
http://2583.live.streamtheworld.com/XHMFMAAC?type=.mp3

Also I tried to find the url with the .mp3 format but I didn't find it. Any idea how I can this to work?
Edit
I'm going to try with this library. https://code.google.com/p/android-openmxplayer/ . I have tested the above urls and it works great.


text:
Q: Java factorial method I'm looking for a little assistance on my factorial method. I can't seem to get it to sum correctly.
I'm only required to take in any number between 1 and 12 and then sum the multiplication...and return the summation.
User selects: 5
1*2*3*4*5 = 120
package cit130hmw07_laginess;

    import java.util.Scanner;

 public class CIT130HMW07_Laginess
 {

   public static void main(String[] args)
   {
     Scanner input = new Scanner(System.in);

     System.out.println("Please select a number between 0 and 12:");
     int factorial = input.nextInt();

     sumFactorials(factorial);
     int facSum = sumFactorials(factorial);
     System.out.println("");
     System.out.println("Your results are: " + facSum);
     System.out.println("");

   }//main

   public static int sumFactorials(int factorial)
   {

      int results = 1;
      for(int i = 1; i <= factorial; i++)
         results = results * factorial;

         return results;

   }//factorials
}//class

A: Some small flaws in your code. Look for the mistakes in comment under respective statement, and their corrections in code following. Notice the extra lines which were not required. You should always write code with as minimum lines as possible, without compromising the readability (i.e. with proper indenting as well).
package cit130hmw07_laginess;

import java.util.Scanner;

 public class CIT130HMW07_Laginess
 {

   public static void main(String[] args)
   {
     Scanner input = new Scanner(System.in);

     System.out.println("Please select a number between 0 and 12:");
     int factorial = input.nextInt();

     //sumFactorials(factorial);
     //this line was not required.

     int facSum = sumFactorials(factorial);

     //System.out.println("");
     //not required when you can use delimiters inside println

     System.out.println("\nYour results are: " + facSum + "\n");

     //System.out.println("");
     //same as before.

   }//main

   public static int sumFactorials(int factorial)
   {

      int results = 1;
      for(int i = 1; i <= factorial; i++)
         //results = results * factorial;
         //this was where your code was not correct.

         //Correct :
         results = results * i;
         return results;

   }//factorials
}//class

Inside println, I have used delimiters (look for \n) to minimize printing statements.

A: check comments for your mistakes:

*

*the only correction is:
results=results*i;
rest were some unnecessary stuff;
package cit130hmw07_laginess;
    import java.util.Scanner;

 public class CIT130HMW07_Laginess
 {

   public static void main(String[] args)
   {
     Scanner input = new Scanner(System.in);

     System.out.println("Please select a number between 0 and 12:");
     int factorial = input.nextInt();

     //sumFactorials(factorial);
     int facSum = sumFactorials(factorial);
     //System.out.println("");
     System.out.println("Your results are: " + facSum);
     //System.out.println("");

   }//main

   public static int sumFactorials(int factorial)
   {

      int results = 1;
      for(int i = 1; i <= factorial; i++)
         //results = results * factorial;
          results=results*i;

         return results;

   }//factorials
}//class

A: write a jave method called factorila that calulates and returns the factorial of a given non-negative integer(0!=1).
inculde your mehtod into java program that print the factorial of the numbers from 0 to 10 via invoking the method factorial .

redpajama_set_name: RedPajamaStackExchange


text:
Q: pyinstaller compiled .exe does nothing Wrote a game and compiled it with pyinstaller.  An EXE file was created but when I go to run it, it thinks for 3-4 seconds and then it returns to command prompt.
Clicking from the folder in Windows does nothing.
No errors, nothing!  Do I need something in my code to allow this to run?  The only imports are tkinter and random.
Edit 1: tested a "hello world" script to see if there were issues with pyinstaller, it ran fine.

A: I understand that the post is older, but it may be useful for other member who may come across the similar problem.
I had created a script using Jupiter notebook and it creates ipynb file.
When I create an exe file using pyinstaller, the exe was doing nothing.
I resolved it by first converting ipynb file to py file using below command:
pyinstaller my_script.py
It will create the py file under same location.
Now, execute below command to create exe file:
pyinstaller my_script.py
It will create exe file under dist folder.
And it works.


text:
Q: Getting JSON data from server and generating excel file I'm trying to generate an excel file from a json object which I get from the server.
My code is as follows:
[Route("api/Generate")]
        public IHttpActionResult Post(dynamic jsonObject)
        {
            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
                var fileFormat = "xlsx";
                formData.Add(new StringContent("Test"), "FileName");
                formData.Add(new StringContent(fileFormat), "FileFormat");
                formData.Add(new StringContent(jsonObject.ToString()), "Data");

                var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                if (!Directory.Exists(tempPath))
                    Directory.CreateDirectory(tempPath);

                var tempFilePath = Path.Combine(tempPath, String.Format("{0}.{1}", "Test", fileFormat));

                using (var newFile = File.Create(tempFilePath))
                {
                    //here's the error
                    jsonObject.Content.ReadAsStreamAsync().Result.CopyTo(newFile);
                }
                var si = new ProcessStartInfo();
                si.CreateNoWindow = true;
                si.FileName = tempFilePath;
                si.UseShellExecute = true;
                Process.Start(si);

                return Ok();
            }

However when I try to test I receive the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform
  runtime binding on a null reference'

Though jsonObject is not null, I've set a breakpoint on execution and it contains the data passed to it.

Thanks in advance.


text:
Q: How to derive approximation result from Levy 0-1 law? Let $(\Omega, \mathcal{F}, P)$ be a probability space. Let $\mathcal{E}_1, \mathcal{E}_2,...$ be a sequence of finite, measurable partitions of $\Omega$ such that each $\mathcal{E}_{n+1}$ is a refinement of $\mathcal{E}_n$, and assume that $\sigma(\cup_n \mathcal{E}_n) = \mathcal{F}$. Let $E_n(\omega)$ be the cell of $\mathcal{E}_n$ that contains $\omega$. For all $A$ and almost all $\omega$, the Levy 0-1 law says that
$$P(A \mid E_n(\omega)) \to \mathbf{1}_A(\omega)\tag{1}$$
In contemporary probability textbooks, this result is usually presented as an immediate consequence of the martingale convergence theorem for conditional expectations.
Interestingly, I have recently discovered a much more elementary proof of this result in Halmos's Measure Theory (Theorem 49.B). Besides the basic properties of conditional probability, the only result that Halmos's proof appeals to is the standard fact that measurable sets can be approximated by sets in a generating algebra. In our context, for all $A \in \mathcal{F}$ and all $\epsilon > 0$, there exists $n$ and $E_1,...,E_k \in \mathcal{E}_n$ such that
$$P(A \triangle E)< \epsilon, \tag{2}$$
where $E=E_1 \cup ... \cup E_k$.
From (2), Halmos's straightforwardly derives (1), which leads to my question:

Assuming (1), is there a straightforward way to derive (2)?

We might start by noticing that $P(A \mid E_n) \to \mathbf{1}_A$ a.s. iff $P(A^c \mid E_n) \to \mathbf{1}_{A^c}$ a.s. and for all $E \in \sigma(\mathcal{E}_n)$
$$P(A \triangle E) = P(A \cap E^c) + P(A^c \cap E) = \int_{E^c}P(A \mid E_n)dP + \int_E P(A^c \mid E_n)dP.$$
Then I thought about trying something like, let $F_n = \{\omega: P(A^c \mid E_n(\omega)) < 1- \epsilon\} \in \sigma(\mathcal{E}_n)$ so that $F_n^c = \{\omega: P(A \mid E_n(\omega)) \leq \epsilon\}$. Then,
$$P(A \triangle F_n) \leq \epsilon P(F_n^c) + (1-\epsilon) P(F_n).$$
But I'm stuck here and not sure this is going to work. Any hints are appreciated.

A: Yeah, I think you are on the right track by looking at the set where the conditional probability is large.  But you can be more crude.
Let $X_n(\omega) = P(A \mid E_n(\omega))$ be the conditional probability.  We are assuming $X_n \to 1_A$ a.s., but all we actually need is convergence in probability.  Let $G_n = \{X_n \ge 1/2\}$ which is $\mathcal{E}_n$ measurable and thus a finite union of the sets of that partition.  Then on $A \triangle G_n$ we have $|X_n - 1_A| \ge 1/2$, so $P(A \triangle G_n) \le P(|X_n - 1_A| \ge 1/2)$ which goes to zero by the convergence in probability.
Thus we can choose $n$ so large that $P(A \triangle G_n) < \epsilon$, and $G_n$ is the desired set.


text:
Q: Return multiple columns based on date range using pandas I'm basically trying to calculate revenue to date using pandas. I would like to return N columns consisting of each quarter end. Each column would calculate total revenue to date as of that quarter end. I have:
df['Amortization_per_Day'] = (2.5, 3.2, 5.5, 6.5, 9.2)
df['Start_Date'] = ('1/1/2018', '2/27/2018', '3/31/2018', '5/23/2018', '6/30/2018')
Date_Range = pd.date_range('10/31/2017', periods=75, freq='Q-Jan')

and want to do something like:
df['Amortization_per_Day'] * (('Date_Range' - df['Start_Date']).dt.days + 1)

for each date within the Date_Range. I'm not sure how to pass the Date_Range through the function and to return N columns. I've been reading about zip(*df) and shift but not fully grasping it. Thank you so much for your help.

A: Solution
Here's a complete solution:
from datetime import datetime
import pandas as pd

df = pd.DataFrame()
df['Amortization_per_Day'] = (2.5, 3.2, 5.5, 6.5, 9.2)
df['Start_Date'] = ('1/1/18', '2/27/18', '3/31/18', '5/23/2018', '6/30/2018')
df['Start_Date'] = pd.to_datetime(df['Start_Date'])
dr = pd.date_range('10/31/2017', periods=75, freq='Q-Jan')

def betweendates(x, y):
    xv = x.values.astype('datetime64[D]')
    xpad = np.zeros(xv.size + 2, dtype=xv.dtype)
    xpad[1:-1] = xv
    xpad[0],xpad[-1] = np.datetime64(datetime.min), np.datetime64(datetime.max)

    yv = y.values.astype('datetime64[D]')

    return (xpad[:-1] <= yv[:,None]) & (xpad[1:] >= yv[:,None])

# get a boolean array that indicates which dates in dr are in between which dates in df['Start_Date']
btwn = betweendates(df['Start_Date'], dr)

# based on the boolean array btwn, select out the salient rows from df and dates from dr
dfsel = df[btwn[:, 1:].T]
drsel = dr[btwn[:, 1:].sum(axis=1, dtype=bool)]

# do the actual calculation the OP wanted
dfsel['Amortization_per_Day'] * ((drsel - dfsel['Start_Date']).dt.days + 1)

Output:
0       77.5
2      170.5
4      294.4
4     1140.8
4     1987.2
4     2806.0
4     3652.4
4     4498.8
4     5345.2
4     6173.2
      ...
4    52394.0
4    53212.8
4    54059.2
4    54905.6
4    55752.0
4    56570.8
4    57417.2
4    58263.6
4    59110.0
4    59938.0
Length: 74, dtype: float64

Explanation
The boolean btwn array looks like this:
[[ True False False False False False]
 [False  True False False False False]
 [False False False  True False False]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 [False False False False False  True]
 ...

The ith row of btwn corresponds to the ith datetime in your date range. In each row, exactly one value will be True, and the others will be False. A True value in the 0th column indicates that the datetime is before any of the Start_Times, a True value in the 1st column indicates that the datetime is in between the 0th and the 1st dates in Start_Times, and so forth. A True value in the last column indicates that the datetime is after any of the Start_Times.
By slicing btwn like this:
btwn[:, 1:]

it can be used to match up datetimes in your date range with the immediately preceding Start_Time. If you instead change the slices of btwn to be like this:
btwn[:, :-1]

you would end up matching each datetime to the next Start_Time instead.


text:
Q: How do I avoid code duplication and apply Boolean operator only to the source of image? How can I make this code better so that there is no code duplication and the boolean operator is only applied to src of the image. So, when the link named car is clicked the car image shows up otherwise when it is the other link clicked then bike image shows up.
{props.type == 'car'?  : }

A:


text:
Q: flex (python PLY) regex for strings I'm using the python module PLY to write a parser, and I am implementing as I go. I have a simple rule to detect strings:
r'("|\').*("|\')'

When lexer errors are thrown I have this:
def t_error (t) :
    print 'Illegal lexer input line ' + str(t.lineno) + ' ' + t.value[:16]
    sys.exit(-1)

When I feed my parser the following input:
parse("preg_match('%^[\*\%]+$%', $keywords)")

I get back this in return:
Illegal lexer input line 1 %^[\*\%]+$%', $k

My questions are:
1) Why am I not parsing this string? It seems like my regex should properly handle this string.
2) How can I fix this?
edit:
I have narrowed the problem down a bit. The following strings throw illegal lexer input errors by themselves:
'%'
'^'

A: Even if this regex were working it isn't quite doing what you want it to, for example it would accept "this', which isn't really a string. This is also the cause of the "illegal lexer input"...
After having done it's job and found the first string in "preg_match(' the lexer is then upset when each of the next 11 characters %^[\*\%]+$% are illegal (and not in t_ignore), since they don't even start with " or '.
.
Try doing this with two cases for " and ': "Starts with quote, some things which aren't quote, ends with quote." That is:
r'("[^"]*")|(\'[^\']*\')'

Or, if you want to include escaped speech marks:
r'("(\\"|[^"])*")|(\'(\\\'|[^\'])*\')'


text:
Q: How to autoincrement versionCode in Android Gradle I'm experimenting with new Android build system based on Gradle and I'm thinking, what is the best way to autoincrease versionCode with it. I am thinking about two options

*

*create versionCode file, read number from it, increase it and write it back to the file

*parse AndroidManifest.xml, read versionCode from it, increase it and write it back to the AndroidManifest.xml

Is there any more simple or suitable solution?
Has anyone used one of mentiod options and could share it with me?

A: If you are holding the version code in the build.gradle file use the next snippet:
import java.util.regex.Pattern
task('increaseVersionCode') << {
    def buildFile = file("build.gradle")
    def pattern = Pattern.compile("versionCode\\s+(\\d+)")
    def manifestText = buildFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode " + ++versionCode)
    buildFile.write(manifestContent)
}

A: I have decided for second option - to parse AndroidManifest.xml. Here is working snippet.
task('increaseVersionCode') << {
    def manifestFile = file("AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

versionCode is released for release builds in this case. To increase it for debug builds change task.name equation in task.whenTaskAdded callback.

A: Gradle Advanced Build Version is a plugin for Android that makes generating versionCode and versionName automatically. there are lots of customization. here you can find more info about it
https://github.com/moallemi/gradle-advanced-build-version

A: I'm using this code to update both versionCode and versionName, using a "major.minor.patch.build" scheme.
import java.util.regex.Pattern

task('increaseVersionCode') << {
    def manifestFile = file("src/main/AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

task('incrementVersionName') << {
    def manifestFile = file("src/main/AndroidManifest.xml")
    def patternVersionNumber = Pattern.compile("versionName=\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcherVersionNumber = patternVersionNumber.matcher(manifestText)
    matcherVersionNumber.find()
    def majorVersion = Integer.parseInt(matcherVersionNumber.group(1))
    def minorVersion = Integer.parseInt(matcherVersionNumber.group(2))
    def pointVersion = Integer.parseInt(matcherVersionNumber.group(3))
    def buildVersion = Integer.parseInt(matcherVersionNumber.group(4))
    def mNextVersionName = majorVersion + "." + minorVersion + "." + pointVersion + "." + (buildVersion + 1)
    def manifestContent = matcherVersionNumber.replaceAll("versionName=\"" + mNextVersionName + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig' || task.name == 'generateDebugBuildConfig') {
        task.dependsOn 'increaseVersionCode'
        task.dependsOn 'incrementVersionName'
    }
}

A: To take both product flavors and build types into account and using @sealskej's logic for parsing manifest:
android.applicationVariants.all { variant ->
    /* Generate task to increment version code for release */
    if (variant.name.contains("Release")) {
        def incrementVersionCodeTaskName = "increment${variant.name}VersionCode"
        task(incrementVersionCodeTaskName) << {
            if (android.defaultConfig.versionCode == -1) {
                def manifestFile = file(android.sourceSets.main.manifest.srcFile)
                def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
                def manifestText = manifestFile.getText()
                def matcher = pattern.matcher(manifestText)
                matcher.find()
                def versionCode = Integer.parseInt(matcher.group(1))
                android.defaultConfig.versionCode = versionCode + 1
                def manifestContent = matcher.replaceAll("versionCode=\"" + android.defaultConfig.versionCode + "\"")
                manifestFile.write(manifestContent)
            }
        }
        def hookTask = variant.generateBuildConfig
        hookTask.dependsOn(incrementVersionCodeTaskName)
    }
}

A: it doesn't seem to be the exact setup you're using, but in my case the builds are being run by jenkins and i wanted to use its $BUILD_NUMBER as the app's versionCode. the following did the trick for me there.
defaultConfig {
    ...
    versionCode System.getenv("BUILD_NUMBER") as Integer ?: 9999
    ...
}

A: Increment VersionCode Task(Integer):
This works by incrementing the Version Code by 1, for example:
  android:versionCode="1"

1 + 1 = 2

import java.util.regex.Pattern

task incrementVersionCode << {
    def manifestFile = file('AndroidManifest.xml')
    def matcher = Pattern.compile('versionCode=\"(\\d+)\"')
    .matcher(manifestFile.getText())
    matcher.find()
    def manifestContent = matcher.replaceAll('versionCode=\"' +
        ++Integer.parseInt(matcher.group(1)) + '\"')
    manifestFile.write(manifestContent)
}

Increment VersionName Task(String):
Warning: Must contain 1 period for Regex
This works by incrementing the Version Name by 0.01, for example:
You can easily modify and change your increment or add more digits.
android:versionName="1.0"

1.00 + 0.01 -> 1.01
1.01 + 0.01 -> 1.02
1.10 + 0.01 -> 1.11
1.99 + 0.01 -> 2.0
1.90 + 0.01 -> 1.91

import java.util.regex.Pattern

task incrementVersionName << {
    def manifestFile = file('AndroidManifest.xml')
    def matcher = Pattern.compile('versionName=\"(\\d+)\\.(\\d+)\"')
    .matcher(manifestFile.getText())
    matcher.find()
    def versionName = String.format("%.2f", Integer
        .parseInt(matcher.group(1)) + Double.parseDouble("." + matcher
            .group(2)) + 0.01)
    def manifestContent = matcher.replaceAll('versionName=\"' +
        versionName + '\"')
    manifestFile.write(manifestContent)
}

Before:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exmaple.test"
    android:installLocation="auto"
    android:versionCode="1"
    android:versionName="1.0" >

After:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exmaple.test"
    android:installLocation="auto"
    android:versionCode="2"
    android:versionName="1.01" >

A: If you write your versionCode in gradle.build file(most case currently), here is a workaround. A little bit stupid(update "self"), but it works!
import java.util.regex.Pattern

task('increaseVersionCode') << {
    def buildFile = file("build.gradle")
    def pattern = Pattern.compile("versionCode(\\s+\\d+)")
    def buildText = buildFile.getText()
    def matcher = pattern.matcher(buildText)
    matcher.find()
    def versionCode = android.defaultConfig.versionCode
    def buildContent = matcher.replaceAll("versionCode " + ++versionCode)
    buildFile.write(buildContent)

    System.out.println("Incrementing Version Code ===> " + versionCode)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

A: UPDATE
As google play warning:

The greatest value Google Play allows for versionCode is 2100000000.

We might change the format as below to reduce the risk of reaching limit:
def formattedDate = date.format('yyMMddHH')

ORIGINAL
I am using time stamp for the version code:
def date = new Date()
def formattedDate = date.format('yyMMddHHmm')
def code = formattedDate.toInteger()

defaultConfig {
    minSdkVersion 10
    targetSdkVersion 21
    versionCode code
}

A: To add on to @sealskej's post, this is how you can update both your version code and version name (Here I'm assuming your major and minor version are both 0):
task('increaseVersion') << {
    def manifestFile = file("AndroidManifest.xml")
    def patternVersionCode = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcherVersionCode = patternVersionCode.matcher(manifestText)
    matcherVersionCode.find()
    def versionCode = Integer.parseInt(matcherVersionCode.group(1))
    def manifestContent = matcherVersionCode.replaceAll("versionCode=\"" + ++versionCode + "\"")

    manifestFile.write(manifestContent)

    def patternVersionNumber = Pattern.compile("versionName=\"0.0.(\\d+)\"")
    manifestText = manifestFile.getText()
    def matcherVersionNumber = patternVersionNumber.matcher(manifestText)
    matcherVersionNumber.find()
    def versionNumber = Integer.parseInt(matcherVersionNumber.group(1))
    manifestContent = matcherVersionNumber.replaceAll("versionName=\"0.0." + ++versionNumber + "\"")
    manifestFile.write(manifestContent)
}

A: what about this ?
add to build.gradle (app module)
def getBuildVersionCode() {
    def date = new Date()
    def formattedDate = date.format('yyyyMMdd')
    def formattedSeconds = date.format('HHmmssSSS')
    def formatInt = formattedDate as int;
    def SecondsInt = formattedSeconds as int;
    return (formatInt + SecondsInt) as int
}

   defaultConfig {
    applicationId "com.app"
    minSdkVersion 17
    targetSdkVersion 22
    versionCode getBuildVersionCode()
    versionName "1.0"
}

A: So as I was looking into most of the solution, they were nice but not enough so I wrote this, one increment per multi-deploy:
This will increment the build when compiling debug versions, and increment the point and version code when deploying.
import java.util.regex.Pattern

def incrementVersionName(int length, int index) {
    def gradleFile = file("build.gradle")
    def versionNamePattern = Pattern.compile("versionName\\s*\"(.*?)\"")
    def gradleText = gradleFile.getText()
    def matcher = versionNamePattern.matcher(gradleText)
    matcher.find()

    def originalVersion = matcher.group(1)
    def originalVersionArray = originalVersion.split("\\.")
    def versionKeys = [0, 0, 0, 0]
    for (int i = 0; i < originalVersionArray.length; i++) {
        versionKeys[i] = Integer.parseInt(originalVersionArray[i])
    }
    def finalVersion = ""
    versionKeys[index]++;
    for (int i = 0; i < length; i++) {
        finalVersion += "" + versionKeys[i]
        if (i < length - 1)
            finalVersion += "."
    }

    System.out.println("Incrementing Version Name: " + originalVersion + " ==> " + finalVersion)

    def newGradleContent = gradleText.replaceAll("versionName\\s*\"(.*?)\"", "versionName \"" + finalVersion + "\"")
    gradleFile.write(newGradleContent)
}

def incrementVersionCode() {
    def gradleFile = file("build.gradle")
    def versionCodePattern = Pattern.compile("versionCode\\s*(\\d+)")
    def gradleText = gradleFile.getText()
    def matcher = versionCodePattern.matcher(gradleText)
    matcher.find()

    def originalVersionCode = Integer.parseInt(matcher.group(1) + "")
    def finalVersionCode = originalVersionCode + 1;
    System.out.println("Incrementing Version Code: " + originalVersionCode + " ==> " + finalVersionCode)

    def newGradleContent = gradleText.replaceAll("versionCode\\s*(\\d+)", "versionCode " + finalVersionCode)
    gradleFile.write(newGradleContent)
}

task('incrementVersionNameBuild') << {
    incrementVersionName(4, 3)
}

task('incrementVersionNamePoint') << {
    incrementVersionName(3, 2)
}

task('incrementVersionCode') << {
    incrementVersionCode()
}

def incrementedBuild = false
def incrementedRelease = false

tasks.whenTaskAdded { task ->
    System.out.println("incrementedRelease: " + incrementedRelease)
    System.out.println("incrementedBuild: " + incrementedBuild)
    System.out.println("task.name: " + task.name)

    if (!incrementedBuild && task.name.matches('generate.*?DebugBuildConfig')) {
        task.dependsOn 'incrementVersionNameBuild'
        incrementedBuild = true
        return
    }

    if (!incrementedRelease && task.name.matches('generate.*?ReleaseBuildConfig')) {
        task.dependsOn 'incrementVersionCode'
        task.dependsOn 'incrementVersionNamePoint'
        incrementedRelease = true
        return
    }
}

A: My approach is to read manifest file from build folder and get buildVersion out of there, than I delete a folder. When task creates new manifest, my incremented buildVersion variable is already there.
def versionPattern = "Implementation-Version=(\\d+.\\d+.\\d+.\\d+\\w+)"

task generateVersion (dependsOn : 'start') {
    // read build version from previous manifest
    def file = file("build/libs/MANIFEST.MF")
    if (file.exists()) {
        def pattern = Pattern.compile(versionPattern)
        def text = file.getText()
        def matcher = pattern.matcher(text)
        matcher.find()
        buildNumber = Integer.parseInt(matcher.group(1))
        // increment build version
        version = "${majorVer}.${minorVer}.${patchVer}.${++buildNumber}${classifier}_${access}"
    }
    else
        version = "${majorVer}.${minorVer}.${patchVer}.1${classifier}_${access}"
}

task specifyOutputDir (dependsOn : 'generateVersion', type : JavaCompile) {
    // create a folder for new build
    destinationDir = file("build/${version}/")
}

task clean (dependsOn : 'generateVersion', type : Delete) {
    doLast {
        delete "build/${version}"
        println 'Build directory is deleted'
    }
}

task configureJar (dependsOn : 'generateVersion', type : Jar) {
    baseName = applicationName
    version = project.version
    archiveName = "${applicationName}_ver${version}.${extension}"
    manifest {[
            "Main-Class" : mainClassName,
            "Implementation-Title" : name,
            "Implementation-Version" : version,
            "Access" : access,
            "Developer" : developer
    ]}
}


text:
Q: string u' encoding problem the goal of my program is to retrieve data from a field one after another at the end to compare with other values of another table
when I execute the code that allows me to point to the values of the first field I get a string that starts with u '
What should I do to remove the u'
DataSource= Shapefile
cursor=arcpy.da.SearchCursor("Feuil1$","LIAISON_NOM")
for row in cursor:
print(str(row))

i get this
>>>>(u'ROAD 1',)
    (u'ROAD 2',)

A: The u'' just indicates that the string is encoded as unicode rather than ASCII. If you print just the string with print(row[0]) (instead of the whole row tuple) you should see the values as you'd expect, e.g. ROAD 1.


text:
Q: Detect SQL injections in the source code Consider the following code snippet:
import MySQLdb

def get_data(id):
    db = MySQLdb.connect(db='TEST')
    cursor = db.cursor()
    cursor.execute("SELECT * FROM TEST WHERE ID = '%s'" % id)

    return cursor.fetchall()

print(get_data(1))

There is a major problem in the code - it is vulnerable to SQL injections attacks since the query is not parameterized through DB API and is constructed via string formatting. If you call the function this way:
get_data("'; DROP TABLE TEST -- ")

the following query would be executed:
SELECT * FROM TEST WHERE ID = ''; DROP TABLE TEST --

Now, my goal is to analyze the code in the project and detect all places potentially vulnerable to SQL injections. In other words, where the query is constructed via string formatting as opposed to passing query parameters in a separate argument.
Is it something that can be solved statically, with the help of pylint, pyflakes or any other static code analysis packages?

I'm aware of sqlmap popular penetration testing tool, but, as far as I understand, it is working against a web resource, testing it as a black-box through HTTP requests.

A: Not sure how this will compare with the other packages, but to a certain extent you need to parse the arguments being passed to cursor.execute.  This bit of pyparsing code looks for:

*

*arguments using string interpolation

*arguments using string concatenation with variable names

*arguments that are just variable names
But sometimes arguments use string concatenation just to break up a long string into - if all the strings in the expression are literals being added together, there is no risk of SQL injection.
This pyparsing snippet will look for calls to cursor.execute, and then look for the at-risk argument forms:
from pyparsing import *
import re

identifier = Word(alphas, alphanums+'_')
integer = Word(nums)
LPAR,RPAR,PLUS,PERCENT = map(Literal, '()+%')

stringInterpRE = re.compile(r"%-?\d*\*?\.?\d*\*?s")
def containsStringInterpolation(s,l,tokens):
    if not stringInterpRE.search(tokens[0]):
        raise ParseException(s,l,"No string interpolation")
tupleContents = identifier | integer
tupleExpr = LPAR + delimitedList(tupleContents) + RPAR
stringInterpArg = identifier | tupleExpr
interpolatedString = originalTextFor(quotedString.copy().setParseAction(containsStringInterpolation) +
                                    PERCENT + stringInterpArg)

stringTerm = interpolatedString | OneOrMore(quotedString.copy()) | identifier
stringTerm.setName("stringTerm")

unsafeStringExpr = (stringTerm + OneOrMore(PLUS + stringTerm)) | identifier | interpolatedString
def unsafeExpr(s,l,tokens):
    if not any(term == interpolatedString or term == identifier
                for term in tokens):
        raise ParseException(s,l,"No unsafe string terms")
unsafeStringExpr.setParseAction(unsafeExpr)
unsafeStringExpr.setName("unsafeExpr")

func = Literal("cursor.execute")
statement = func + LPAR + unsafeStringExpr + RPAR
statement.setName("execute stmt")
#statement.ignore(pythonComment)

for tokens in statement.searchString(sample):
    print ' '.join(tokens.asList())

This will scan through the following sample:
sample = """
import MySQLdb

def get_data(id):
    db = MySQLdb.connect(db='TEST')
    cursor = db.cursor()
    cursor.execute("SELECT * FROM TEST WHERE ID = '%s' -- UNSAFE" % id)
    cursor.execute("SELECT * FROM TEST WHERE ID = '" + id + "' -- UNSAFE")
    cursor.execute(sqlVar + " -- UNSAFE")
    cursor.execute("SELECT * FROM TEST WHERE ID = 'FRED' -- SAFE")
    cursor.execute("SELECT * FROM TEST WHERE ID = " +
                        "'FRED' -- SAFE")
    cursor.execute("SELECT * FROM TEST "
                        "WHERE ID = "
                        "'FRED' -- SAFE")
    cursor.execute("SELECT * FROM TEST "
                        "WHERE ID = " +
                        "'%s' -- UNSAFE" % name)
    return cursor.fetchall()

print(get_data(1))"""

and report these unsafe statements:
cursor.execute ( "SELECT * FROM TEST WHERE ID = '%s' -- UNSAFE" % id )
cursor.execute ( "SELECT * FROM TEST WHERE ID = '" + id + "' -- UNSAFE" )
cursor.execute ( sqlVar + " -- UNSAFE" )
cursor.execute ( "SELECT * FROM TEST " "WHERE ID = " + "'%s' -- UNSAFE" % name )

You can also have pyparsing report the location of the found lines, using scanString instead of searchString.

A: There is a tool that tries to solve exactly what the question is about, py-find-injection:

py_find_injection uses various heuristics to look for SQL injection
  vulnerabilities in python source code.

It uses ast module, looks for session.execute() and cursor.execute() calls, and checks whether the query inside is formed via string interpolation, concatenation or format().
Here is what it outputs while checking the snippet in the question:
$ py-find-injection test.py
test.py:6   string interpolation of SQL query
1 total errors

The project, though, is not actively maintained, but could be used as a starting point. A good idea would be to make a pylint or pyflakes plugin out of it.

A: About the best that I can think you'd get would be grep'ing through your codebase, looking for cursor.execute() statements being passed a string using Python string interpolation, as in your example:
cursor.execute("SELECT * FROM TEST WHERE ID = '%s'" % id)

which of course should have been written as a parameterized query to avoid the vulnerability:
cursor.execute("SELECT * FROM TEST WHERE ID = '%s'", (id,))

That's not going to be perfect -- for instance, you might have a hard time catching code like this:
query = "SELECT * FROM TEST WHERE ID = '%s'" % id
# some stuff
cursor.execute(query)

But it might be about the best you can easily do.

A: It's a good thing that you're already aware of the problem and trying to resolve it.
As you may already know, the best practices to execute SQL in any DB is to use prepared statements or stored procedures if these are available.
In this particular case, you can implement a prepared statement by "preparing" the statement and then executing.
e.g:
cursor = db.cursor()
query = "SELECT * FROM TEST WHERE ID = %s"
cur.execute(query, "2")


text:
Q: In python, how can I run a command-line program that does not return until I send Ctrl+D to it I'm writing python unit tests that test against a REST API that needs to be running as another process.
The REST server is a tomcat application that I call from the shell to run in development mode, so what I am looking to do in the python test is:

*

*Start the server, return when the server is up.

*Run unit tests

*Send the server Ctrl+D so it shuts down gracefully.

Is there a way to use a single point of entry for python so that the server starts and unit tests run all from one python script call?
I've look around at python subprocess and multithreading in python, but I still don't quite see how to get there from here.
For those that are familiar, this is an Atlassian JIRA plugin we are developing, so the actual shell command is "atlas-run".

A: Since no one has offered any code to help with this problem, I would do something like the following.  Turns out pexpect is very powerful and you don't need the signal module.
import os
import sys
import pexpect

def run_server():
    server_dir = '/path/to/server/root'
    current_dir = os.path.abspath(os.curdir)

    os.chdir(server_dir)
    server_call = pexpect.spawn('atlas-run')
    server_response = server_call.expect(['Server Error!', 'Sever is running!'])
    os.chdir(current_dir)
    if server_response:
        return server_call #return server spawn object so we can shutdown later
    else:
        print 'Error starting the server: %s'%server_response.after
        sys.exit(1)

def run_unittests():
    # several ways to do this. either make a unittest.TestSuite or run command line
    # here is the second option
    unittest_dir = '/path/to/tests'
    pexpect.spawn('python -m unittest discover -s %s -p "*test.py"'%unittest_dir)
    test_response = pexpect.expect('Ran [0-9]+ tests in [0-9\.]+s') #catch end
    print test_response.before #print output of unittests before ending.
    return

def main():
    server = run_sever()
    run_unittests()
    server.sendcontrol('d') #shutdown server

if __name__ == "__main__":
    main()


text:
Q: Alt tag being broken up by spaces. How to pass text? Trying to update an editor from FCKeditor from 2006 to (CKeditor 4) with a custom plugin made back then. I am almost there but when I try and insert an alt tag (alternative text) I get strange results as the alt tag has spaces. The editor breaks up the text value for the alt tag into various parts each time it hits a space. Here is my code snippet. The alt tag gets broken at the first space.
Quite new to this, any advice or help appreciated. :-)
Kind regards
Abbey
function onClose(){

    var imgUrl = hidFileName.value;
    var altTag = "this is a test";

        var result="<img src="+'<%=strImagePath%>'+imgUrl+" alt="+altTag+" >";
        var element = window.opener.CKEDITOR.dom.element.createFromHtml( result );
        var CKEDITOR   = window.opener.CKEDITOR;
        for ( var i in CKEDITOR.instances ){
           var currentInstance = i;
           break;
        }

        var oEditor   = window.opener.CKEDITOR.instances[currentInstance];
        oEditor.insertElement(element);
        window.close();
    }


text:
Q: LoadControl for same ascx control multiple times in a placeholder I have a UserControl that has a simple repeater inside.  It has a property called data which when passed into the control populates the repeater using the standard databinding.
On a page I have a placeholder.
I have a loop which does the following
        Dim qDetail As New UserControls_ReportDataTable
        qDetail = DirectCast(LoadControl("~/UserControls/ReportDataTable.ascx"), UserControls_ReportDataTable)
        qDetail.data = result
        phBCPSACustomQuestions.Controls.Add(qDetail)

Where result is different each time.
The problem is that at the end of the loop where I see my page all the instances of the control are populated with the last set of result data.
Any idea why this is happening?
--Update --
Just some further details based on comments.
The property "data" in the control is defined as follows:
Property data As IEnumerable
I have verified that the result is different in each loop iteration.
This is the full code for the loop itself
    For Each tblRow As DataRowView In dSet.Tables(0).DefaultView

        Dim result As DataView = dSet.Tables(1).DefaultView
        result.RowFilter = "QID = " & tblRow("QID").ToString

        Dim qDetail As UserControls_ReportDataTable
        qDetail = DirectCast(LoadControl("~/UserControls/ReportDataTable.ascx"), UserControls_ReportDataTable)
        qDetail.data = result
        phBCPSACustomQuestions.Controls.Add(qDetail)

    Next

A: Without seeing all of your code I can't say for sure, but I'd guess that you are defining "result" outside of your loop and then setting it's value inside the loop.  This will lead to an "Access to Modified Closure" situation (don't know if that's just a resharper term or a global one).
In any case, define a variable inside the loop and set the value of the result there and then set it into your control.  It should solve your issue.


text:
Q: Удалит ли деструктор по умолчанию объект, хранящийся в классе в виде ссылки? Если поле класса хранит ссылку на объект, удалит ли деструктор по умолчанию объект, на который ссылается поле?

A: Нет, ведь ссылка не обязательно указывает на объект, созданный new.
Деструктор по умолчанию только вызывает деструкторы всех полей и базовых классов, если они есть.

A: Деструктор вызывается при смерти обьекта. Если обьект А хранит ссыльку на  обьект В, то при уничтожении обьекта А  вызовится его деструктор, который не обязательно должен уничтожать объект В(деструктор по умолчанию точно это не сделает), если только вы так не захотите(часто это плохая идея). А если объект В не находится в динамической памяти, то никакой деструктор не сможет его уничтожать. P.S. Тут главное заботится о том, чтобы обьект  В не был удален раньше чем А станет не нужным.


text: Q: How to solve the "program not responding" problem when calling matlab function from python? It's my first time to call matlab function from python. I defined a matlab function in a '''.mat''' file, then used the matlab.engine to call the function by passing a 8000000*1 mlarray parameter. Then the application turned to unresponsive and it taked about 30s to recover. So i guess it was because the function call may passing value copy instead of reference or pointer that took a long time. I'm wondering am i right, and if i'm right, how can i solve the problem?


text:
Q: Mathematical expression for mean of sum of pairs Hello everyone I have a matrix such as :

and I do the mean of sum of all pair such as
(H1H2)+(H1H3)+(H1H4)+(H1H5)+(H2H3)+(H2H4)+(H2H5)+(H3H4)+(H3H5)+(H4H5)/nb pairs

and I wondered how can I exprime that expression into a mathematical expression and then into a latex code please?

A: I can think of at least two representations of the "mean of sum of pairs" in LaTeX code.

\documentclass{article}
\usepackage{mathtools} % for "\smashoperator" macro
\begin{document}
\raggedright % optional
The ``mean of sum of pairs'' of $H_{n\times n}$ may be expressed as either
\[
\frac{2}{n(n-1)} \sum_{i=1}^n \sum_{j>i} H_{i,j}
\quad\text{or as}\quad
(n(n-1)/2)^{-1}\smashoperator{\sum_{\substack{i=1,\dots,n\\j>i}}} H_{i,j}\,.
\]
\end{document}

\end{document}


text:
Q: Azure DataFactory - A database operation failed with "Invalid object name" I have a Data Factory datasets where the connection is working, but when I try to "preview" the table structure I get the following error:
Error details

Error code
22301

Details
A database operation failed with the following error: 'Invalid object name 'dbo.[my_table]'.' Invalid object name 'dbo.[my_table]'., SqlErrorNumber=208,Class=16,State=1, . Activity ID: 05746029-7365-4d9d-b60a-2cdc06b126ec

I've checked, and the table in question exists and is accessible via the connection credentials being used. I don't know why it's giving me this error if that is the case?

A: Select table name from drop down, instead of edit and typing table name manually. Then try to preview table structure.
If that doesn't solve:

*

*Ensure that if you have a case sensitive collation on your database
that the object names in your query match the exact case.

*Check that the default schema for your user hasn't changed on this
database. Although the default schema is usually [dbo], it can be
changed.

*If you are using stored procedures or parameters, the parameter name
of the stored procedure should be the same as the tableName defined
in the dataset. Please verify it.


text:
Q: Which open source database is the best option for an accounting-related system? I am in the early stages of planning and designing a custom accounting application for my firm. My goal is to utilize an open source relational database for the data storage portion and I'm aware of two solid databases that are widely supported: MySQL and PostgreSQL.
For a system that will require transactions, stored procedures, functions, and security, are there any opinions on which of these two databases would be best suited for an accounting application or is there another database I'm missing?
I'm more familiar with MySQL and MS SQLServer 2005, but I'm trying to move away from the latter due to license costs.
Let me add: This is not an accounting need like Quickbooks or Peachtree. This is basically a system that handles accounting for a specific business service we provide. There are maybe two or three systems that cater to this need, are priced in the six figure range before any customization, and would require my small firm to be married to a vendor for the long-term. Thus, we are building the application in-house.
Also, while I appreciate the Buy vs. Build argument, I'd like to move away from that particular religious question because the Buy road was already taken and the vendor failed miserably. Sometimes you just need to do the job yourself and this particular project and budget warrants it.
Thanks for everyone's replies thus far.

A: I agree strongly with answers from duffymo and tuinstoel and others.  Reconsider your build vs. buy decision.  Let me tell you a story:
While I was working at a mid-sized company (international, >$100M/yr revenue), the CFO decided to replace the financial systems with Oracle Financials.  Only that package didn't exactly match the accounting practices used by this company.
So the CFO hired a team of contract programmers, and paid them to customize Oracle Financials to the preferred accounting practices.  She sunk 12 months of time, $1 million in programmer wages, plus the initial cost of the software, just to duplicate the accounting system that they had intended to replace.
She said if she had to do it over again, she would buy the commercial package, but adapt the company's accounting habits to the defaults supported by the software.  That would be far easier, quicker, and more likely to succeed.
So consider the cost of building your own custom package.  Also consider the ongoing cost to your company of maintanance, debugging, and enhancement for that software.  Even if buy a six-figure commercial package, that'll probably be less expensive than paying the programmers to develop and maintain such a system.

To answer your stated question more directly, I don't think there's a significant difference between PostgreSQL and MySQL that is relevant to your project.  Since you are comfortable with MySQL, you might as well go with that.
I would like to offer an obligatory reminder not to use inexact data types like FLOAT or DOUBLE PRECISION for financial data.

A: For any application that wants to use an open source database, the hands-down answer is Postgres.  It's a LOT more "enterprise-ready" than MySQL, not to mention that it follows the SQL standard a lot better.  MySQL has improved a lot with its later versions, but Postgres still beats it in every category.

A: There are four main open-source relational database management systems of note that might be appropriate to this sort of application: Postgresql, MySQL, Firebird and Ingres.  There are other systems such as SQLite, but they do not have this type of architecture and are not really designed for this type of workload.  Some other open-source database management systems of this type do exist, but do not appear to be strongly viable for some reason, such as a lack of apparent vendor commitment.  An example of a system that has this type of issue is SAP-DB.
Postgresql has the best feature set of any of the open-source databases, and support for XA transactions, which you will probably want if your application is a three-tier system and supports transactions of non-trivial complexity.  In particular you will want this if you want to do transactions spanning more than one call to the database.
Several commercial variants of PostgreSQL have been built over the years, such as Illustra, Greenplum and EnterpriseDB.  Illustra was a commercial release of PostgreSQL which was subsequently bought by Informix.  Greenplum is a mofified version designed for data warehousing applications.  EnterpriseDB is a company that provides supported commercial versions of PostgreSQL with some value-added software.
MySQL 5.x has a feature set that supports a reasonable cross section of capabilities, but it is not as feature-rich as PostgreSQL.  It has more widespread mainstream acceptance and would be the easiest of the open-source database management systems to recruit skilled developers for.  Although older versions did not have robust transaction support, transactional storage engines such as InnoDB have been available for some time.  The current politics surrounding the acquisition by Sun have generated code forks and the MySQL landscape is somewhat messy, with controversy about quality issues in the 5.1 release.  However, MySQL is by far the most popular and best known of the open-source database management systems and is the only one with significant brand recognition outside of open-source circles.
Firebird is an open-source version of Interbase.  Last I looked, it did not have XA support but would be fine if your application was set up as a two-tier client-server system.  Update: I can't find a definitive specification on this, but the documentation does indicate that it has support for two-phase commit, but what I could find was not specific on whether it supported the XA protocol.  The documentation implies that the JDBC driver does have support for two-phase commits.
An interesting variant on this system is Fyracle, which is designed to offer a degree of compatibility with Oracle.  This was originally developed for use as a back-end to Compiere, which was built against Oracle and quite tightly coupled to it.
Ingres is now available with an open-source license, but has been greeted with a bit of a collective yawn by the open-source community.  However It is quite feature-rich and very mature - I know people who were doing INGRES apps in 1990, and it dates back to the 1980s.

A: There are open source free accounting systems. Like osFinancials. I really can't understand why you want to build your own system?

A: My advice?  Don't.  Better to buy one.  People who know more about accounting have written good packages that already deal with GAAP.  They have a larger user base than you'll ever have, which will uncover defects faster.  This is a classic "buy versus build".  There's no competitive advantage to your firm by writing their own.  If you're doing it because you're worried about license costs, I'd say you haven't accounted for the development time properly.  That's the only way you could justify doing this in-house.
With that said, if you are worried about SQL Server licensing costs, I'd recommend PostgreSQL first or MySQL second as your database of choice.

A: For your application, it won't really matter. Anything from sqlite to MySQL to Postgres would probably work just fine. Pick the one you're most familiar with.

A: Firebird - http://www.firebirdsql.org/

A: If you are familiar with MySQL then use it.
But select proper database engine instead of default MyISAM
List of Storage Engines

A: Honestly, any of the usual suspects will do the job.  Maintaining the chart of accounts and related data tables is the root issue that drove most all of the relational model.  In fact, if you think about the general journal view of an accounting system, all you have is the chart-of-accounts and the general journal, composed of transaction number, date, description, debit account and amount, credit account and amount.  Everything else you do is a SELECT on those.
That said, though, there are so many perfectly adequate, well-tested and accepted financial packages, including open-source free (as in beer) versions, that unless you mean it for an etude, a study project, I'd put my effort into googling and selecting one.
Saw your update.  The thing is, this is an issue that's mostly going to be determined by nonfunctional requirements.  Are you going to distribute the database across more than one server?  how much load do you expect?  Transactions per second or transactions per day?  I've built systems around both in the last couple of years, and it's usually reliability and avilability requirements that are the most decisive: PostgreSQL deals with concurrent updates of a single row more effectively, by enforcing row atomicity and serializing concurrent updates.  On the other hand, MySQL seems to deal with really large databases better.  Yet a third question is backup --- one of them (I don't recall which one right now) more or less requires some down time to backup.

A: For an in-house web-based accounting application, you might be better off with Gemstone as a free but not open source object database and Seaside as the web framework. Otherwise known as GLASS.
For an in-house application, you're going to be limited in developer effort. Gemstone, as a smalltalk image, provides the best developer productivity by far. Its support for migrating objects when changing their definition allows real iterative development. Seaside replaces templates by a well-designed domain-specific language for building web applications.

A: I build accounting software on PostgreSQL.  It works very well.  I would highly recommend it.  In fact (shameless plug), you might consider working with us to improve our project and using it as a jumping off point.
There are a couple reasons in particular:

*

*LISTEN/NOTIFY gives you an ability to hook other programs into your accounting db when something changes without having to check tables every so often.

*We've found extremely good performance with most complex queries.

Firebird and Ingres will give you a very rock-solid relational solution.  MySQL I wouldn't recommend because you are really tying everything to one app only that can write to the db (sql mode soup means relations are basically a private API instead of the public API they are in PostgreSQL, Firebird, and Ingres), and this means less flexibility down the road.
However, with PostgreSQL, you get a top-notch, extensible development platform in a box.  Pace of development is high.  It is rock solid.   The advanced features are very helpful. You won't be disappointed.  We haven't been.

A: If this is a desktop application you might want to look at SQLite. It's very well known, in the public domain, and not terribly difficult to work with.

A: Since you don't need stored procedures, take that off your list.
You'll be a lot happier putting business logic in code, not in the database.  If you have the chance to start "clean", then use the database for what makes the most sense -- persistence not processing.
Once you make that decision, the subtle differences between MySQL and PostgreSQL go away.  Both are relational engines that handle nearly identical SQL.  Focus on the things they do best.
Recommendation: Make your application independent of any database peculiarities.


text:
Q: Improper decoding of raw H264 video stream using android MediaCodec I am building a screen sharing app and trying to receive raw H264 video stream from a socket and displaying it using surfaceview by decoding using MediaCodec class. However I am successfully able to receive data and display on surface. But the problem where I am stuck from two days is the video is very laggy,jittery and having green bands and patches. You can see the issue in the youtube video link. If I save this video to sdcard and play it using MxPlayer then it is playing fine.Also I tried with Gstreamer and everything is fine.
This is my class calling from Activity when surfaceview is created.
//New Edited Code
public class Server {
static final int socketServerPORT = 53515;
MainActivity activity;
ServerSocket serverSocket;

public Server(MainActivity activity, Surface surface) {
    Log.e("constructor()", "called");
    this.activity = activity;
    Thread socketServerThread = new Thread(new SocketServerThread(surface));
    socketServerThread.start();
}

private static MediaCodecInfo selectCodec(String mimeType) {
    int numCodecs = MediaCodecList.getCodecCount();
    for (int i = 0; i < numCodecs; i++) {
        MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);

        if (codecInfo.isEncoder()) {
            continue;
        }

        String[] types = codecInfo.getSupportedTypes();
        for (int j = 0; j < types.length; j++) {
            if (types[j].equalsIgnoreCase(mimeType)) {
                Log.e("codecinfo", codecInfo.getName());
                return codecInfo;
            }
        }
    }
    return null;
}

private class SocketServerThread extends Thread {
    InputStream is;
    Socket socket;
    private MediaCodec codec;
    private Surface surface;

    public SocketServerThread(Surface surface) {
        this.surface = surface;
    }

    @Override
    public void run() {
        Log.e("socketthread", "called");
        try {
            selectCodec("video/avc");
            codec = MediaCodec.createByCodecName(selectCodec("video/avc").getName());

            MediaFormat format = MediaFormat.createVideoFormat("video/avc", 800, 480);
            //  format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
            format.setInteger(MediaFormat.KEY_BIT_RATE, 1024000);
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 25);
            codec.configure(format, surface, null, 0);
            codec.start();
            serverSocket = new ServerSocket(socketServerPORT);
            while (true) {
                socket = serverSocket.accept();
                Log.e("connection", "accepted");
                is = socket.getInputStream();
                if (is != null) {
                    //          File file = new File(Environment.getExternalStorageDirectory() + "/stream.mp4");
                    //              OutputStream output = new FileOutputStream(file);
                    byte[] buff = new byte[4 * 1024]; // or other buffer size
                    int read;
                    while ((read = is.read(buff)) != -1) {
                        //              output.write(buff, 0, read);
                        if (buff.length == 1)
                            continue;

                        int inIndex = codec.dequeueInputBuffer(10000);
                        if (inIndex >= 0) {
                            ByteBuffer inputBuffer = codec.getInputBuffer(inIndex);
                            inputBuffer.clear();
                            inputBuffer.put(buff);

                            codec.queueInputBuffer(inIndex, 0, buff.length, 16, 0);
                        }

                        MediaCodec.BufferInfo buffInfo = new MediaCodec.BufferInfo();
                        int outIndex = codec.dequeueOutputBuffer(buffInfo, 10000);

                        switch (outIndex) {
                            case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
                                break;
                            case MediaCodec.INFO_TRY_AGAIN_LATER:
                                break;
                            case -3:
                                break;
                            default:
                                codec.releaseOutputBuffer(outIndex, true);
                        }
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (codec != null) {
                codec.release();
            }
            if (socket != null) {
                try {
                    socket.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  }
}

I tried the way you mentioned to create MediaCodec as
MediaCodec.createByCodecName(selectCodec("video/avc").getName());

   private static MediaCodecInfo selectCodec(String mimeType) {
    int numCodecs = MediaCodecList.getCodecCount();
    for (int i = 0; i < numCodecs; i++) {
        MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);

        if (!codecInfo.isEncoder()) {
            continue;
        }

        String[] types = codecInfo.getSupportedTypes();
        for (int j = 0; j < types.length; j++) {
            if (types[j].equalsIgnoreCase(mimeType)) {
                Log.e("codecinfo",codecInfo.getName());
                return codecInfo;
            }
        }
    }
    return null;
}

but it gives me error
I/OMXClient: MuxOMX ctor
I/MediaCodec: [OMX.qcom.video.encoder.avc] setting surface generation   to 28345345
W/ACodec: [OMX.qcom.video.encoder.avc] Failed to set standard   component role 'video_decoder.avc'.
E/ACodec: [OMX.qcom.video.encoder.avc] configureCodec returning error -1010
E/ACodec: signalError(omxError 0x80001001, internalError -1010)
E/MediaCodec: Codec reported err 0xfffffc0e, actionCode 0, while in state 3
E/MediaCodec: configure failed with err 0xfffffc0e, resetting...
I/OMXClient: MuxOMX ctor
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.androidsrc.server, PID: 27681
android.media.MediaCodec$CodecException: Error 0xfffffc0e
at android.media.MediaCodec.configure(MediaCodec.java:1884)
at com.androidsrc.server.Server$SocketServerThread.run(Server.java:70)
at java.lang.Thread.run(Thread.java:761)

Also I tried to create Mediacodec earlier by this method
codec =  MediaCodec.createDecoderByType("video/avc");

but the video quality remains same as in the video shared on youtube.

A: I'd rather comment this but still missing the required points :D
I think you (or i'm not aware that it' works otherwise) are missing some important bits. The video you provided shows signs of missing information on how to interpret things.

*

*Are you sending and using SPS and PPS? I'm not sure if the MediaFormat you create contains all the needed information.

*MediaCodec requires entire frames to be fed to it. Are you sure that you receive a full frame using this sort of logic?

*Some Decoders expect the frames without a NAL header. Are you sending frames without NAL headers?

*I don't see you transfer any presentation time
I suggest you Look at RTP/RTSP protocol on how to transfer media.
To further help you i suggest you provide the producer logic as well

A: OMX.google.h264.decoder is a software codec with a limited functionality (at least on some devices and api levels).
Try to use createDecoderByType instead of createDecoderByName or to choose another codec as in the example here:
https://developer.android.com/reference/android/media/MediaCodecInfo.html
(modify it to choose decoder other than OMX.google.h264.decoder)

A: Try to reduce timeout on dequeue (codec.dequeueInputBuffer(10000);), unless you think it does take so much time to decode.
Also setup following flags:

mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);

You mentioned that you changed code to select by type but original post had errors when decoder was created. Are you able to fix those errors?
You do need to use hardware decoder to ensure that you can play without significant performance cost. New video definitely is worst than first attempt, which means you had decoder selection issue. You can use ffplay with -f h264 option and confirm that format is correct.
Lastly, look into video dimensions and you can read back buffer from decoder (by passing false in releaseOutputBuffer) and write it to disk to confirm your dimensions are correct. Raw video to final video will have different dimension. Read width, height from codecFormat to confirm it is able to decode correctly.


text:
Q: Looking for a book on a 1st differential equations course I'm currently taking differential equations but the guide book (Elementary differential equations and boundary value problems) is aimed for engineers (much like the calculus one from Stewart). I'm looking for a book with the classic mathematical format (definition, theorem, corollary...) and not too much talk or applications.
Thanks

A: I'm certainly no expert, but I have particularly enjoyed An Introduction to Ordinary  Differential Equations by Earl Coddington. I used it along side Elementary Differential Equations and Boundary Value Problems by Boyce and Diprima and it is definitely a nice complement to that.

A: The books

*

*Differential Equations : Theory, Technique, and Practice by G.F simmons and Steven Krantz

*An introduction to Ordinary Differential Equations by E.A. Coddington

fulfills your requirements!


text:
Q: Why is exact matching in regular expressions ({n}) not working in command line? I am trying to match an expression which occurs in a line exactly 2 times.
I tried:
find . * | egrep "(prune){2}"
This shows no output.
However, when I try:
find . * | egrep "(prune){1}"
It shows both 1 as well as 2 matches in the line.

A: The {n} syntax means: match the previous expression n times. So using (prune){2} will only ever match pruneprune.
Try .*prune.*prune.* instead.

A: For your case to use regex "(prune){2}" you need to find at least one file that contains the word "pruneprune" in the file name, you  dind't find nothing becasue you don't have file that contains "pruneprune" word.
to test it try to create some files with this :
touch {a..b}pruneprune{1..9}.log

and run your command with "(prune){2}" again.


text:
Q: Checkbox inside Select dropdown ia not working I am using bootstrap multiple select in ASP.Net website. I added these links
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">

and then in my .cshtml

        Secondary License Statuses:

            <select class="form-control" id="SecondaryLicenseStatuses" data-bind="options: TabLicense.SecondaryLicenseStatuses, selectedOptions: TabLicense.SecondaryLicenseStatusesSelections, optionsText: 'name'" size="5" multiple="multiple"></select>

and in JS file
$('#SecondaryLicenseStatuses').multiselect();

It says

TypeError: $(...).multiselect is not a function

Right now my app can select multiple select options by pressing CTRL but I want to make checkboxes with it.
Thanks!


text:
Q: C++ local libraries and relative path I have so many includes like this in my application
#include "../../libs/helper.hpp"

I am glad to remove there ../../libs/ from every include. Is there any way to fix this problem so I can call the library this way?
#include "helper.hpp"

one possible way is to use -I switch in make file. But the problem is that then I should use angular brackets < and > for calling libraries. It is undesirable since I prefer to distinguish between my local libraries and the installed libraries. So I am looking for a way to call it with " around the name of the libraries.
Is there any way?

A:
-iquotedir
      Add the directory dir to the head of the list of directories to be searched for header files only for the case of #include "file"; they are not searched for #include <file>, otherwise just like -I.

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Directory-Options.html#Directory-Options


text:
Q: How do you turn on the camera flash without taking pictures?
Possible Duplicate:
wp8 - Reflection API issue - Please check

I know you can control the camera flash but that only seems to actually turn on the flash when you take a picture or record video. I also found one other way to turn it on by focusing the camera.
Is there a way to turn the LED flash on without either of these battery intensive hacks?

A: Yep, it's possible to do that on WP8 using public APIs, please see my answer @ Reflection failure when attempting to access Microsoft.Phone.Media.Extended
There's also a way to do that for WP7, see @ http://www.locked.nl/wp7-flashlight-getting-started


text:
Q: boost spirit qi numeric parsing of integer and floating points i am trying to make sense of the following result. The test case code is
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/spirit/home/support/context.hpp>
#include <boost/spirit/home/phoenix.hpp>
#include <boost/foreach.hpp>

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>

namespace sp = boost::spirit;
namespace qi = boost::spirit::qi;
using namespace boost::spirit::ascii;

namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;

using phoenix::at_c;
using phoenix::push_back;
using phoenix::bind;

template <typename P>
void test_parser(
    char const* input, P const& p, bool full_match = true)
{
    using boost::spirit::qi::parse;

    char const* f(input);
    char const* l(f + strlen(f));
    if (parse(f, l, p) && (!full_match || (f == l)))
        std::cout << "ok" << std::endl;
    else
        std::cout << "fail" << std::endl;
}

int main() {

test_parser("+12345", qi::int_ ); //Ok
test_parser("+12345", qi::double_ - qi::int_ ); //failed, as expected
test_parser("+12345.34", qi::int_ );  // failed, as expected
test_parser("+12345.34", qi::double_ - qi::int_ );  //failed but it should be Ok!
};

the motivation here is that i want to match numbers '12345' as integers and NEVER as floating points. '12345.34' will match double_ and never int_ but the reciprocal case is not true; '12345' matches both integers (int_ )  and floating point (double_ ). I tried double_ - int_ and it successfully failed to match '12345'. However my hope was that the last test case '12345.34' would positively match double_ - int_, but the result i get is fail to match.
Why this is so, and how do i get a parser that only matches integers and another that only matches floating points (like in c, 5.0 would be interpreted as floating point)

A: The problem with the double-not-int qi::double_ - qi::int_ is that an individual parser doesn't have to match the whole input to be a successful match. For "+12345.34", qi::double_ makes a successful match on the whole thing and qi::int makes a successful match on "+12345", so that qi::double_ - qi::int_ is a non-match.  For difference operator, think about applying each parser separately and whether there is a valid match for each for even the first part of the input.
You can get the behavior you want by requiring some kind of boundary after qi::int_.  What follows when an qi::int_ matches the first part of a float is a valid float (e.g. qi::int_ on "+12345.34" matches "+12345", leaving ".34" next on the stream). Therefore, you can do a negative look ahead for a float:
int_rule %= qi::int_ >> !qi::double_;

double_rule %= qi::double_ - int_rule;

or
double_rule %= qi::double_ - (qi::int_ >> !qi::double_);

!qi::double is also true for whitespace and eoi, so I think this should be pretty general for standard format.  This won't work for scientific notation though.

A: For your specific example, I think it's actually described in the Boost Spirit documentation under RealPolicies Specialization. To make things a bit easier for you, I whipped out a quick "real" parser, that only parses real numbers and not integers(or at least it worked with your simplified examples):
template <typename T>
struct strict_real_policies : qi::real_policies<T>
{
    static bool const expect_dot = true;
};

qi::real_parser< double, strict_real_policies<double> > real;

And you can use this just like any other parser(like int_ and double_). You might have to add:
#include <boost/spirit/include/qi_numeric.hpp>

To get it to compile.


text:
Q: GNUPLOT - How to check if "multiplot" is set If a script breaks in the middle of a multiplot sequence gnuplot is left in multiplot mode.
Before being able to re-run the script I need to manually put it back to normal mode or it will fail if I change terminal:
Example:
gnuplot> load "script.gnuplot"
         "script.gnuplot", line 35: warning: Cannot find or open file "inputDataFile.dat"
         "script.gnuplot", line 35: No data in plot

multiplot> load "script.gnuplot"

multiplot> set term wxt 666
                    ^
           "script.gnuplot", line 30: You can't change the terminal in multiplot mode

multiplot> unset multiplot
gnuplot>

Is there a variable that is set when in multiplot mode? A check at the beginning of the script could then be executed and, in case, multiplot mode disable. Alternative solutions are welcome.

A: In fact, after I wrote down the question I just realized I could stick a
unset multiplot

at the beginning of the script.
No warnings if the multiplot mode is not set so it does the job neately.


text:
Q: How to properly display images to html template in Django framework? I've been trying for a day to try to get the images that are saved to the media folder to display in my template file, but to no avail. The images are uploaded to the media/images folder, but I can't figure out how to display them. I can't figure out what I'm doing wrong because I see many people use these methods and get a result. I'm thinking maybe my post function isn't returning the correct data to the template?
I'm extremely new in Django and html, so please forgive my mistakes.
This is my current setup:
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

models.py
from django.db import models

class Post(models.Model):
    post = models.ImageField(upload_to="images")

forms.py
from django import forms
from imageDetection.models import Post

class HomeForm(forms.ModelForm):
    class Meta:

        model = Post
        fields = ('post',)

views.py
class HomeView(TemplateView):
    template_name = 'imageDetection/test.html'

    @staticmethod
    def detect(request):
        return render(request, 'imageDetection/detection.html')

    def get(self, request):
        form = forms.HomeForm()
        return render(request, self.template_name, {'form': form})

    def post (self, request):
        context = {}
        if request.method == "POST":
            form = forms.HomeForm(request.POST, request.FILES)
            if form.is_valid():
                image_form = models.Post()
                image_form.post = form.cleaned_data['post']
                image_form.save()
                context['form'] = image_form
                return render (request, 'imageDetection/detection.html', context)
            else:
                form = forms.HomeForm()
                context['form'] = form
        return render(request, self.template_name, context)

urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('imageDetection.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

template/ Detection.html
{% for post in form %}
    {% if post.image %}

    {% endif %}
{% endfor %}

Thank you, any help will be appreciated

A: Here I didn't see any field with name image in your model.You have define the image with field name post .
 {% if post.post %}

 {% endif %}

And also here better use the meaningful variable for your fields and context.You can name your image field with image instead of post and context  images instead of forms


text:
Q: Continuous Map on Compact Oriented Manifold of Higher Degree Let $M$ be a compact oriented manifold of dimension $\ge 3$.
Is there any known obstructions of $M$ for it to admit a continuous self-map of degree $>1$?
Note: the case when $\dim(M) = 2$ is known (see this post).
Remark: In (the top answer of) the post above, it was explained that if $M$ has positive simplicial volume (denoted as $||M||$), then it does not admit a self-map of degree $>1$. However, if $M$ is simply-connected, we have $||M|| = 0$. So 2 follow-up questions are:

*

*Let $M$ be a simply-connected compact oriented manifold of dimension $\ge 3$.
Is there any known obstructions of $M$ for it to admit a continuous self-map of degree $>1$?

*Original question, replace "obstruction" with "obstruction other than simplicial-volume".

A: This was studied quite a bit in the 3-dimensional case. The main obstruction is positive simplicial volume, e.g. hyperbolic manifolds do not admit such maps. For details see
Sun, Hongbin; Wang, Shicheng; Wu, Jianchun; Zheng, Hao, Self-mapping degrees of 3-manifolds, Osaka J. Math. 49, No. 1, 247-269 (2012). ZBL1241.55002.


text:
Q: Convert matrix's coordinate to respective array's coordinate I want to convert matrix's (n, m) coordinates as i, j to respective array's (n * m) coordinates as k, thus matrix[i, j] will be equivalents to array[k]. I don't know how to create an expression that makes this conversion.
I want to find who is k
Thanks a lot

A: Sounds suspiciously like homework.
Assuming the matrix size is known already as n and m... Here's an algorithm in JavaScript:
var a = new Array(  );
for( i = 0; i < n; i++) {
    for( j = 0; j < m; j++) {
         a[ (i * m) + j ] = matrix[ i ][ j ];
    }
}

EDIT: fixed the index expression for a[]


text:
Q: Special numbers consecutive A number is said special if it has two or more digits and is a multiple of the sum of its
digits.
(a) Find three consecutive special numbers.
(b) Find four consecutive special numbers.
Well, as I understand it, a special number is for example: $12$ is special because it's a multiple of $ 1 + 2 = 3$

A: http://oeis.org/A060159
$110,111,112$
$510,511,512,513$
$131052,131053,131054,131055,131056$
are all "special numbers" (more commonly called Harshad or Niven numbers in literature)
C. N. Cooper and R. E. Kennedy proved in a paper submitted to Fibonacci Quarterly in 1993 that there are not sequences of $21$ or more consecutive such numbers.
It is also known that there does exist sequences of $20$ consecutive of these numbers, the smallest known sequence of $20$ consecutive of these numbers being on the order of $10^{44363342786}$.  It is not yet known what the smallest possible such sequence of $20$ consecutive numbers is, but by the well ordering principle it must exist. [$\dagger$]
Even more generally, when considering these numbers represented instead in base $b$, H. G. Grundman in 1994 extended this result to show that there cannot exist sequences of $2b+1$ consecutive numbers for any base $b$, which was later expanded on by Brad Wilson to show that there will however exist sequences of $2b$ consecutive numbers for any base $b$, which was later expanded on even further by T. Cai in 1996 to show that for $b=2$ or $b=3$ there are infinitely many such sequences.


text:
Q: Cannot retrieve Selected option value I can able to get the selected option value in onchange event. But, when clicking the ok button in the same page , I can't get the value selected. Please help me..
Code is as follows:
<select  id ="userstoassign">
<option value="s1">S1</option>
<option value="s2" selected="selected">S2</option>
<option value="s3">S3</option>
</select>
<input type="button" name="ok" id="ok" value="ok"/>

$("#ok").live('click', function(){
       var username= $("#userstoassign option:selected").val();
       alert(username);

    });

Note: In onchange event, I can get the selected value. Temp fix is I'm getting that value in onchange event in a variable and will use it in onclick event. Even in onchange event I'm getting default value if I use the code "$("#userstoassign option:selected").val();"
    $('#userstoassign').live('change',function(){                    selectedUser=this.value;
alert(selectedUser);
    });

A: var username= $("#userstoassign option:selected").val();

Demo - http://jsfiddle.net/qsYwr/1/

A: simple:
var username=  $("#userstoassign").val();

A: Reason being I'm including my jsp in another jsp which is creating this issue. But, if I create select box dynamically, then I'm not getting that issue. But, stil couldn't find why this bug is occuring.
<%@ include file="Common.jsp" %>

In this common.jsp, I'm using select box, which is creating this issue. I removed select box from this jsp and creating it dynamically in the js.


text: Q: Why command create-react-app opens file explorer I'm trying to create react application, but every time I put command create-react-app react-app it opens file explorer and that's it. Folder where I began cannot be deleted and it won't create application. Please help.


text:
Q: In static block call .phtml file for specific product id I have a template which uses banners on the homepage,these banners get filled by a static block like the following:

Product ABC

$99,99

            Buy Now

This is static however as I need to put in the image and write down the product name and so on by hand. What I would like to to from the stativ block is something like this:

    {{block type="core/template" name="product_id" pid="1" template="myfolder/product_id.phtml"}}

And then have a .phtml file where I get the product ID from the static block as follows:
<?php echo $this->getPid();?>

and then create the input for the banner there, so that I can just change the pid in the static block, because as far as I know I cannot get the image, product price and name of a product and URL in a static block or not?
UPDATE
I also would need to pass on a flag to the template file to differentiate between two types of products and the URL

A: Well, if you know those data you can definitely do something like this:

    {{block type="core/template" name="product_id" pid="1" pimage="imageurl" template="myfolder/product_id.phtml"}}

Then call
<?php echo $this->getPimage(); ?>

But that would be painful and you will have to change several arguments each time you use that block for a different product.
What you can do is get those data directly in your template using the pid:
Either by loading the product (not recommended, loading an entire product to get just a few attributes is very bad in terms of performance):
$_product = Mage::getModel('catalog/product')->load($this->getPid());
$_productImage = Mage::helper('catalog/image')->init($_product, 'image');
$_productName = $_product->getName();
$_productPrice = $_product->getPrice();

Or using a collection (more code but way better in terms of performance):
$_collection = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('price')
    ->joinAttribute('image', 'catalog_product/image', 'entity_id', null, 'left')
    ->addAttributeToFilter('entity_id', $this->getPid())
    ->setPageSize(1);

if ($_collection->getSize()) {
    $_product = $_collection->getFirstItem();
    $_productImage = Mage::helper('catalog/image')->init($_product, 'image');
    $_productName = $_product->getName();
    $_productPrice = $_product->getPrice();
}


text:
Q: unexpected Inifite loop using switch and some function Basically I have a piece of code that has a switch statement and some functions. It goes to the switch statement using a parameter given by the browser "?step=X" and then selects the appropriate function.
My problem is even when at the end of each function I specify to go to the next switch statement it never does it and somehow it becomes an infinite loop of the function that I selected with the "step=x" in the browser...
Why is getting stuck in 1 function and not iterating through them? (the code for the step is highlighted at the end of the script)
I get the output in the browser of any selected function. so It enters the switch and the selected function... but then it becomes and infinite loop because in the broswer i get 300 of the same echo statements. It is never able to iterate through them or exit the selected function.
<?php
//DB Config File
$dbFile = 'dbconfig.php';

$username = $_GET['username'];
$password = $_GET['password'];
$server = $_GET['server'];
$dbname = $_GET['dbname'];
$step = $_GET["step"];

function createfile ($dbFile) {
        //Creates File and populates it.
        $fOpen = fopen($dbFile, 'w');
global $username, $password, $server, $dbname;
            $fString .= "<?php\n";
            $fString .= "// Database Constants\n";
            $fString .= "\$DB_SERVER =" . "\"" . $server . "\";\n";
            $fString .= "\$DB_USER =" . "\"" . $username . "\";\n";
            $fString .= "\$DB_PASS =" . "\"" . $password . "\";\n";
            $fString .= "\$DB_NAME =". "\"" . $dbname . "\";\n";
            $fString .= "?>";

        fwrite($fOpen, $fString);
        fclose($fOpen);
return true;
}

try {
$db = new PDO ('mysql:host=' .$server.';dbname='.$dbname,$username,$password);

if ($db) { //if succesful at connecting to the DB

if (file_exists($dbFile)){
    if (is_readable($dbFile) && is_writable($dbFile)){

        //Creates File, populates it and redirects the user

    if (createfile($dbFile)) {
    echo "nelxt";
    stepFunction($step);
    exit ();
            }

        } else {

        echo "The file {$dbFile} cannot be accessed. Please configure the file manualy or grant Write and Read permission.";  }

    } else {

        //Creates File, populates it and redirects the user

    if (createfile($dbFile)) {

    echo "next";
        stepFunction($step);
    exit ();
            }

        }

}

} catch (PDOException $e) { //Catchs error if can't connect to the db.
    echo  'Connection failed: ' . $e->getMessage();
}

// Prepare SQL Statements
$IDB = $db->prepare(
 "CREATE TABLE pages (
  id int(11) NOT NULL auto_increment,
 subject_id int(11) NOT NULL,
  menu_name varchar(30) NOT NULL,
  position int(3) NOT NULL,
  visible tinyint(1) NOT NULL,
  content text NOT NULL,
  PRIMARY KEY  (id)
)ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8");

$IDB2 = $db->prepare("
CREATE TABLE subjects (
  id int(11) NOT NULL auto_increment,
  menu_name varchar(30) NOT NULL,
  position int(3) NOT NULL,
  visible tinyint(1) NOT NULL,
  PRIMARY KEY  (id)
)ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8");

$IDB3 = $db->prepare("
CREATE TABLE users (
  id int(11) NOT NULL auto_increment,
  username varchar(50) NOT NULL,
  hashed_password varchar(40) NOT NULL,
  PRIMARY KEY  (id)
)ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8");

//Set Option to True or False
if (empty ($_GET['fot']) ) {
    $fOT = false;
    } else { $fOT = true;
        }

///////////////////////////////
// PROBLEMATIC STEP BEGINS HERE
///////////////////////////////

function createTablePages (){

    global $db,$IDB;

                echo "0
";
                stepFunction (1);

}
function createTableSubjects ($fOT){

    global $db,$IDB2;

                echo "1
";
                stepFunction (2);
}

function createTableUsers ($fOT){

    global $db,$IDB3;
    echo "3
";

}

function stepFunction ($step,$fOT){
global $db,$IDB1,$IDB2,$step,$fOT;

switch ($step) {
    case 0: echo "hola";
            createTablePages ($fOT);
            break;
    case 1: echo "hola2";
            createTableSubjects($fOT);
            break;
    case 2: createTableUsers ($fOT);
            break;
    }

}
?>

A: Fix
function stepFunction ($step,$fOT){
global $db,$IDB1,$IDB2,$step,$fOT;

to
function stepFunction ($step){
global $db,$IDB1,$IDB2;

You are overriding your $step variable with the global one of the same name. Thus when you come with ?step=0 you call stepFunction with 0 then it goes to createTablePages then it goes to stepFunction with 1, but is immediately replaced with 0 (because that's what the global $step's value is) and again and again...


text:
Q: Debugging incosistent LUKS/cryptsetup behaviour I've encountered this issue a few times but so far I've been unable to reliably reproduce this/find the root cause.
Where do I go from here? It seems like taking hexdump of the header might help, so maybe keep taking snapshots of hexdump of the first key slot area until it does this again?
Symptom:

*

*After a reboot/shutdown, sometimes the passphrase for the first key slot is rejected with No key available for this passphrase.

*Sometimes Header backup does not seem to help. Running something like cryptsetup -v --header backupheader.bin open /dev/device test still returns No key... for the first slot. But one out of five times recovery from header backup works (again this sometimes works, sometimes does not). cryptsetup luksHeaderRestore produces the same result.

Observations:

*

*The partition itself seems to be fine. lsblk and cryptsetup isLuks shows nothing abnormal.

*cryptsetup luksDump always works and shows the first slot is enabled.

*I've since added a few more keys and these keys always work. It's the first key slot that seems to have issues.

*If I unlock the partition using the second or any other key but the first one, the first key slot usually works on the next boot.

Env:

*

*X1 Carbon Gen 6, Fedora 28


text:
Q: Can I declare normal functions in an Interface? i was studied Java in oracle website. on that, i saw the example like
public class Horse {
   public String identifyMyself() {
      return "I am a horse.";
   }
}
public interface Flyer {
   default public String identifyMyself() {
       return "I am able to fly.";
   }
}
public interface Mythical {
   default public String identifyMyself() {
       return "I am a mythical creature.";
   }
}
public class Pegasus extends Horse implements Flyer, Mythical {
   public static void main(String... args) {
       Pegasus myApp = new Pegasus();
       System.out.println(myApp.identifyMyself());
   }
}

Can i write interface like this? I hope that i can only write abstract functions in interface. then why in oracle website they are gave example like this?

A: This feature is avaialble in java 8, it is called default method or defender method.

Default methods enable you to add new functionality to the interfaces
  of your libraries and ensure binary compatibility with code written
  for older versions of those interfaces.

Find more about default method here.
java 8 snapshoot version is available jdk8 Build b129 .

There is one common question that people ask about default methods when they hear about the new feature for the first time: "What if the class implements two interfaces and both those interfaces define a default method with the same signature?".
but it is handled during compile time, get more explanation with example Here

A: In Java 8, this is possible. And, it's called as default methods in the interfaces.

Default methods enable you to add new functionality to the interfaces
  of your libraries and ensure binary compatibility with code written
  for older versions of those interfaces.

Check here for more details

A: As other SO users saying its available from java 8 .
but otherwise ..
No you cant , in the interface all the methods ar abstract methods by default .
Hope that Helps .


text:
Q: Ubuntu packaging : why separate for 32-bit and 64-bit Why we have to do separate packaging to applications for 32-bit and 64-bit Ubuntu Operating systems.I mean why some applications are making 32-bit and 64-bit separately and why some applications are not ?
is there any advantage if we made 64-bit packaging for a 64-bit OS ?

A: Simply, not all applications are compiled 32bit or 64bit binaries.

*

*Most Python libraries scripts are "compiled" at runtime by the native Python binary (which will be running in 32 bit or 64bit mode, depending on the system). Same with Java.

*Some packages are just resources for another package and can be shared between 32bit and 64bit packages (eg Kernel source packages).

The packages that are separated into architecture are either compiled to machine code, rely too much on architecture-related dependencies or otherwise have architecture-dependent code inside (seems unlikely though).

"Fat" packages and binaries are something that has been toyed with in the past but you're really talking about doubling the size of most binaries and libraries, as well as introducing unforeseen bugs. It's simply not an advantage worth the cost.
It's also worth considering that in most cases developers don't really have to do anything to get architecture specific packages. They'll push them to a build platform like Launchpad and Launchpad will return a bunch of 32bit, 64bit and ARM variant packages.


text:
Q: Allow collapsing vote-count This is a minor, OCD driven, request but that's never stopped me before...
After showing the vote counts for a post, I would like to re-collapse to the regular view. So far the only way I know to get this is to refresh the whole page. I think that another click on the expanded vote count should re-collapse the votes to the normal total.