Java object to JSON using GSON gives stackoverflow error

Question: I am trying to use GSON to convert a java object, in list format, to JSON, I have tried a few ways, but am running into the same error.
1st attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
Gson gson = new Gson();
String json = gson.toJson(techs);

2nd attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
Type listType = new TypeToken<List<Techinv>>() {}.getType();
Gson gson = new Gson();
String json = gson.toJson(techs, listType);

3rd attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
GsonBuilder gsonBuilder = new GsonBuilder();

new GraphAdapterBuilder()
    .addType(Techinv.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = gson.toJson(techs);

All of the above fail, with either a stackoverflow error or a can't convert java int (one of the members in my Techinv class) to a java vector, all in the GSON library.
Please tell me I am missing something simple in all these examples :)
Techinv class (if required)
package org.cchit.inv.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * The persistent class for the techinv database table.
 *
 */
@Entity
@NamedNativeQueries ({
    @NamedNativeQuery(name="Techinv.deleteByOrgId",
            query="DELETE FROM techinv where org_id = ?")
})
@NamedQueries ({
    @NamedQuery(name="Techinv.removeUser",
            query="UPDATE Techinv t SET user_id = 0 where t.id = :techid"),
    @NamedQuery(name="Techinv.getAllByOrg",
            query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid"),
    @NamedQuery(name="Techinv.getById",
            query="SELECT t FROM Techinv t where t.id = :id"),
    @NamedQuery(name="Techinv.getByProdOrg",
            query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid and p.product.id = :prodid"),
    @NamedQuery(name="Techinv.delete",
            query="DELETE FROM Techinv t where t.id = :id")
    })
@Table(name="techinv")
public class Techinv implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Column(name="mu_mask")
    private long muMask;

    @Column(name="mu_assigned_mask")
    private long muAssignedMask;

    @Column(name="mu_asked_assign_mask")
    private long muAskedAssignedMask;

    @Column(name="mu_cert_mask")
    private long muWillCertMask;

    @Column(name="mu_ask_will_cert_mask")
    private long muAskedWillCertMask;

    @Column(name="certType")
    private String certType;

    @Temporal(TemporalType.DATE)
    @Column(name="Apply_date")
    private Date applyDate;

    @Temporal(TemporalType.DATE)
    @Column(name="Cert_date")
    private Date certDate;

    @Lob()
    private String notes;

    //bi-directional many-to-one association to OrgUser
    @ManyToOne
    @JoinColumn(name="user_id")
    private OrgUser orgUser;

    //bi-directional many-to-one association to Organization
    @ManyToOne
    @JoinColumn(name="org_id")
    private Organization organization;

    //bi-directional many-to-one association to Product
    @ManyToOne
    @JoinColumn(name="prod_id")
    private Product product;

    //bi-directional many-to-one association to Certification
    @ManyToOne
    @JoinColumn(name="cert_id")
    private Certification certification;

    public void setCertification(Certification certification) {
        this.certification = certification;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Techinv() {
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNotes() {
        return this.notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    public OrgUser getOrgUser() {
        return this.orgUser;
    }

    public void setOrgUser(OrgUser orgUser) {
        this.orgUser = orgUser;
    }

    public Organization getOrganization() {
        return this.organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public long getMuMask() {
        return muMask;
    }

    public void setMuMask(long muMask) {
        this.muMask = muMask;
    }

    public long getMuAssignedMask() {
        return muAssignedMask;
    }

    public void setMuAssignedMask(long muAssigned) {
        this.muAssignedMask = muAssigned;
    }

    public Certification getCertification() {
        return certification;
    }

    public long getMuWillCertMask() {
        return muWillCertMask;
    }

    public void setMuWillCertMask(long muWillCertMask) {
        this.muWillCertMask = muWillCertMask;
    }

    public long getMuAskWillCertMask() {
        return muAskedWillCertMask;
    }

    public void setMuAskedWillCertMask(long muAskedWillCertMask) {
        this.muAskedWillCertMask = muAskedWillCertMask;
    }

    /**
     * This will set the question to true. Once asked and answered, this cannot be unset.
     * @param mu
     */
    public void setMuAskedAssignedMask(Mu mu) {
        this.muAskedAssignedMask |= mu.getMask();
    }

    public boolean isCertified(Mu mu) {
        return getCertification() != null && (getCertification().getMuMask() & mu.getMask()) > 0;
    }

    public boolean isAssigned(Mu mu) {
        return (getMuAssignedMask() & mu.getMask()) > 0;
    }

    public boolean hasAskedToCertify(Mu mu) {
        return isAssigned(mu) && !isCertified(mu) && (getMuAskWillCertMask() & mu.getMask()) > 0;
    }

    public boolean isWillCertify(Mu mu) {
        return hasAskedToCertify(mu) && (getMuWillCertMask() & mu.getMask()) > 0;
    }

    public boolean hasMu(Mu mu) {
        return (getMuMask() & mu.getMask()) > 0;
    }

    public boolean hasAskedToAssign(Mu mu) {
        return (muAskedAssignedMask & mu.getMask()) > 0;
    }

    public String getCertType() {
        return certType;
    }

    public void setCertType(String certType) {
        this.certType = certType;
    }

    public Date getApplyDate() {
        return applyDate;
    }

    public void setApplyDate(Date applyDate) {
        this.applyDate = applyDate;
    }

    public Date getCertDate() {
        return certDate;
    }

    public void setCertDate(Date certDate) {
        this.certDate = certDate;
    }
}

Comment: What is your tech class look like?
Answer: You should check for circular references in your serialized classes and mark the appropriate properties @Transient. Post your TechModel class if you want help with that.
edit: as using @Transient is not an option for you , use Gson's @Expose .
From the GSON user guide :

This feature provides a way where you can mark certain fields of your
  objects to be excluded for consideration for serialization and
  deserialization to JSON. To use this annotation, you must create Gson
  by using new
  GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The
  Gson instance created will exclude all fields in a class that are not
  marked with @Expose annotation.
Comment: Ain't your @ManyToOne mappings bidirectional? Does the Organization  class (for example) has a List of TechInv ?
Comment: Yes it does actually.  Problem is, if i set it transient, it fails even before it gets to the GSON code.
Comment: I am facing the same issue and not using Expose doesn't help. I didn't dig into the source, but my guess is that GSON calls peek() before checking if the object is marked as Expose or not, thus triggering the same stack overflow.
Answer: Type listType = new TypeToken<ArrayList<Techinv>>() {}.getType();

Comment: nope, that still gives
java.lang.StackOverflowError
 at java.util.ArrayList.get(ArrayList.java:322)
 at com.google.gson.stream.JsonWriter.peek(JsonWriter.java:354)
 at com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:565)
 at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:386)
 at com.google.gson.stream.JsonWriter.value(JsonWriter.java:480)
 at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:237)
 at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:222)
Answer: You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.
I don't have access to your beans OrgUser, Organization, Product, and Certification. So I assume that each of them comprises an id and a name.
For your List<Techinv> techList.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

List<Techinv> techList = new ArrayList<Techinv>();
for (int i = 1; i <= 3; i++) {
    Techinv tech = new Techinv(i, 1L, 2L, 3L, 4L, 5L, "cert",
            new Date(), new Date(), "notes", new OrgUser(i, "orguser"),
            new Organization(i, "organization"), new Product(i,
                    "product"), new Certification(i, "certification"));
    techList.add(tech);
}
Techinv[] techArr = techList.toArray(new Techinv[techList.size()]);

JsonArrayBuilder techArrBuilder = Json.createArrayBuilder();
for (Techinv tech : techArr) {
    JsonObjectBuilder jsonObject = Json.createObjectBuilder()
        .add("id", tech.getId())
        .add("muMask", tech.getMuMask())
        .add("muAssignedMask", tech.getMuAssignedMask())
        .add("muAskedAssignedMask", tech.getMuAskedAssignedMask())
        .add("muWillCertMask", tech.getMuWillCertMask())
        .add("muAskedWillCertMask", tech.getMuAskedWillCertMask())
        .add("certType", tech.getCertType())
        .add("applyDate", sdf.format(tech.getApplyDate()))
        .add("certDate", sdf.format(tech.getCertDate()))
        .add("notes", tech.getNotes())

        .add("OrgUser", Json.createObjectBuilder()
        .add("id", tech.getOrgUser().getId())
        .add("name", tech.getOrgUser().getName()))

        .add("Organization", Json.createObjectBuilder()
        .add("id", tech.getOrganization().getId())
        .add("name", tech.getOrganization().getName()))

        .add("Product", Json.createObjectBuilder()
        .add("id", tech.getProduct().getId())
        .add("name", tech.getProduct().getName()))

        .add("Certification", Json.createObjectBuilder()
        .add("id", tech.getCertification().getId())
        .add("name", tech.getCertification().getName()));
    techArrBuilder.add(jsonObject);
}
JsonArray jsonArray = techArrBuilder.build();

Map<String, Object> prop = new HashMap<String, Object>() {
    {
        put(JsonGenerator.PRETTY_PRINTING, true);
    }
};
JsonWriter jsonWriter = Json.createWriterFactory(prop).createWriter(System.out);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();

The output should be:
[
    {
        "id":1,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":1,
            "name":"orguser"
        },
        "Organization":{
            "id":1,
            "name":"organization"
        },
        "Product":{
            "id":1,
            "name":"product"
        },
        "Certification":{
            "id":1,
            "name":"certification"
        }
    },
    {
        "id":2,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":2,
            "name":"orguser"
        },
        "Organization":{
            "id":2,
            "name":"organization"
        },
        "Product":{
            "id":2,
            "name":"product"
        },
        "Certification":{
            "id":2,
            "name":"certification"
        }
    },
    {
        "id":3,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":3,
            "name":"orguser"
        },
        "Organization":{
            "id":3,
            "name":"organization"
        },
        "Product":{
            "id":3,
            "name":"product"
        },
        "Certification":{
            "id":3,
            "name":"certification"
        }
    }
]


The method 'document' isn't defined for the type 'CollectionReference'. Flutter/Firebase

Question:
The method 'document' isn't defined for the type 'CollectionReference'.
Try correcting the name to the name of an existing method, or defining a method named 'document'.

I am getting this error in my project. Can you help me?
My Code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crypto_app/models/users.dart';

class FireStoreService {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final DateTime time = DateTime.now();

  Future<void> createUser({id, mail, userName, photoUrl = ""}) async {
    await _firestore.collection("users").doc(id).set({
      "userName": userName,
      "mail": mail,
      "photoUrl": photoUrl,
      "about": "",
      "createTime": time
    });
  }

  Future<Users> bringUser(id) async {
    DocumentSnapshot doc = await _firestore.collection("users").doc(id).get();
    if (doc.exists) {
      Users users = Users.dokumandanUret(doc);
      return users;
    }
    return null;
  }

  void userUpdate({String userId, String userName, String photoUrl = ""}) {
    _firestore
        .collection("users")
        .document(userId)
        .updateData({"userName": userName, "photoUrl": photoUrl});
  }
}

Answer: CollectionReference in cloud_firestore for flutter/dart does not have a document(..) method. It is called doc(..) instead. https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/CollectionReference/doc.html
Comment: Probably also because it is not called `updateData` but `update` instead (https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentReference/update.html)
Comment: When I use it as a doc, I get an error in updateData.
Comment: I'm new to the flutter language, thank you very much.


SQL Server 2008 R2 connection string

Question: HI people.
I had SQL Server 2005 on Windows XP 32bit and just used this connection string
Server=.\SQLEXPRESS;database=GroupALD; Integrated Security=True"

Now I have Windows 7 64bit and SQL Server 2008 R2 I'm trying to connect database with same string but its shows this error

Cannot open database "GroupALD" requested by the login. The login failed.
  Login failed for user 'lester\les'.

Can somebody help me?
I'm using C# and Winforms
Comment: Sounds like this is not a connection string issue but rather a permission setting in the database itself. Otherwise, http://www.connectionstrings.com is a great resource for various connection string examples.
Comment: Change Server to Data Source; otherwise it is a permission issue
Comment: @Carnotauraus: that's **definitely** **NOT** the problem. I prefer `server=` and `database=` - seems much clearer (than `data source=` and `initial catalog=`) - and those settings work just fine every day in production...
Answer: Yes, try connectionstrings.com:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

Comment: i have express edition. when im using SSPI its shows such error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
Answer: The error message is pretty clear:

Cannot open database "GroupALD"
  requested by the login. The login
  failed.
Login failed for user 'lester\les'.

Your user doesn't have a valid login on your new database - it's not a connection-string related issue - you need to create a login for lester\les on your new server and create a user in the GroupALD database for that login.
See : how to create a SQL Server Login
Answer: Can you connect to your express edition using SQL Server Management Studio of R2 ?
One workaround i can suggest is to export the database from express to R2 if you can connect to R2 using your connection string .
Comment: YES i connecting with menagment studio without problems. but my app shows errors
Comment: @user525717: are you connecting with your user `lester\les` ?? Or with `sa` or your integrated Windows account??

SQL Server 2008 R2 connection string


Path null run on device with minifyEnabled = true

Question: When I try to run my app on phisical device I got the error path may not be null or empty string. path='null' in build phase of the project but the build run nice if i try to run the app on the emulator.
I made some experiment and I found out that this behavior is due to minifyEnabled = true but I have not found a way to understand which path is null and why.
Is there somebody who has already solved any problem like this one?
This is my build.gradle file
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

import com.android.build.OutputFile;

apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'io.fabric'
apply plugin: 'let'
apply plugin: "org.sonarqube"

Properties localProperties = new Properties()
try {
    localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
} catch (Exception e) {
    localProperties = null
}

def versionMajor = 0  // Max one digit
def versionMinor = 2  // Max one digit
def versionPatch = 6  // Max one digit
def versionBuild = 6  // Max two digits: bump for dogfood builds, public betas, etc.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        renderscriptTargetApi 17
        renderscriptSupportModeEnabled true
        versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
        multiDexEnabled true
        dataBinding {
            enabled = true
        }
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        testInstrumentationRunnerArguments disableAnalytics: 'true' // Analytics opt-out.
    }
    productFlavors {
        envProd {
            applicationId "xxx"
            buildConfigField("String", "API_KEY", "xxx")

            crashlytics {
                enableNdk true
                androidNdkOut 'build/intermediates/transforms/mergeJniLibs/envProd/release/folders/2000/1f/main/lib/'
                androidNdkLibsOut 'build/intermediates/transforms/stripDebugSymbol/envProd/release/folders/2000/1f/main/lib'
            }

        }
        envTest {
            applicationId "xxx"
            buildConfigField("String", "API_KEY", "xxx")

            crashlytics {
                enableNdk true
                androidNdkOut 'build/intermediates/transforms/mergeJniLibs/envTest/release/folders/2000/1f/main/lib/'
                androidNdkLibsOut 'build/intermediates/transforms/stripDebugSymbol/envTest/release/folders/2000/1f/main/lib'
            }

        }
    }
    signingConfigs {
        release {
            if (localProperties != null) {
                storeFile file(localProperties['store.file'])
                storePassword localProperties['store.password']
                keyAlias localProperties['key.alias']
                keyPassword localProperties['key.password']
            }
        }
    }
    buildTypes {
        all {
            buildConfigField "java.util.Date", "BUILD_DATE", "new java.util.Date(" + System.currentTimeMillis() + "L)"
        }
        debug {
            applicationIdSuffix ".debug"
            ext.enableCrashlytics = false // Disable fabric build ID generation for debug builds
            ndk {
                abiFilters = []
                abiFilters.addAll(['armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'])
            }
        }
        release {
            signingConfig signingConfigs.release
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-crashlytics.pro',
                    'proguard-rules.pro',
                    'proguard-support-v7-appcompat.pro',
                    'proguard-google-play-services.pro',
                    'proguard-eventbus.pro',
                    'proguard-let.pro',
                    'proguard-gson.pro',
                    'proguard-guava.pro',
                    'proguard-aws.pro',
                    'proguard-calligraphy.pro'
            ndk {
                abiFilters = []
                abiFilters.addAll(['armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'])
            }
        }
    }
    splits {
        abi {
            enable true
            reset()
            include 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
            universalApk false
        }
    }
    packagingOptions {
        pickFirst 'lib/armeabi-v7a/libopencv_imgproc.so'
        pickFirst 'lib/armeabi-v7a/libopencv_core.so'
        pickFirst 'lib/arm64-v8a/libopencv_imgproc.so'
        pickFirst 'lib/arm64-v8a/libopencv_core.so'
        pickFirst 'lib/x86/libopencv_imgproc.so'
        pickFirst 'lib/x86/libopencv_core.so'
        pickFirst 'lib/x86_64/libopencv_imgproc.so'
        pickFirst 'lib/x86_64/libopencv_core.so'
    }
    dataBinding {
        enabled = true
    }
    testOptions.unitTests.all {
        testLogging { // Always show the result of every unit test, even if it passes.
            events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
        }
    }
}

dependencies {
    compile project('xxx')
    compile project('xxx')
    compile project('xxx')
    envTestCompile project('xxx')
    envProdCompile project('xxx')
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.6@aar') {
        transitive = true;
    }
    // Testing
    androidTestCompile('com.android.support.test:runner:0.5') {
        exclude module: 'support-annotations'
    }
    // Set this dependency to use JUnit 4 rules
    androidTestCompile('com.android.support.test:rules:0.5') {
        exclude module: 'support-annotations'
    }
    // Set this dependency to build and run Espresso tests
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        exclude module: 'support-annotations'
    }
    // Set this dependency to build and run UI Automator tests
    androidTestCompile('com.android.support.test.uiautomator:uiautomator-v18:2.1.2') {
        exclude module: 'support-annotations'
    }
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.google.android.gms:play-services-vision:11.0.4'
    compile 'com.google.android.gms:play-services-location:11.0.4'
    compile 'com.google.android.gms:play-services-safetynet:11.0.4'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    compile 'jp.wasabeef:glide-transformations:2.0.2'
    compile 'com.google.guava:guava:19.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:8.3.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.github.paolorotolo:appintro:4.1.0'
    compile 'com.facebook.rebound:rebound:0.3.8'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.amazonaws:aws-android-sdk-core:2.6.11'
    compile 'com.amazonaws:aws-android-sdk-s3:2.6.11'
    testCompile 'junit:junit:4.12'
    testCompile 'org.hamcrest:hamcrest-core:1.3'
    androidTestCompile 'org.mockito:mockito-core:1.10.19'
    androidTestCompile 'com.crittercism.dexmaker:dexmaker:1.4'
    androidTestCompile 'com.crittercism.dexmaker:dexmaker-dx:1.4'
    androidTestCompile 'com.crittercism.dexmaker:dexmaker-mockito:1.4'
}

// map for the version code, max 2 digits
project.ext.abiCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

android.applicationVariants.all { variant ->
    // assign different version code for each output
    variant.outputs.each { output ->
        output.versionCodeOverride =
                (variant.mergedFlavor.getMinSdkVersion().getApiLevel() * 10000000
                        + project.ext.abiCodes.get(output.getFilter(OutputFile.ABI)) * 100000
                        + variant.mergedFlavor.versionCode)
    }
}

This is the full stacktrace of the error:
java.lang.IllegalArgumentException: path may not be null or empty string. path='null'
    at org.gradle.api.internal.file.BaseDirFileResolver.doResolve(BaseDirFileResolver.java:72)
    at org.gradle.api.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:79)
    at org.gradle.api.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:61)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionConverter.convertInto(DefaultFileCollectionResolveContext.java:173)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:134)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCollections(DefaultFileCollectionResolveContext.java:92)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionConverter.convertInto(DefaultFileCollectionResolveContext.java:157)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(DefaultFileCollectionResolveContext.java:109)
    at org.gradle.api.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCollections(DefaultFileCollectionResolveContext.java:92)
    at org.gradle.api.internal.file.CompositeFileCollection.getSourceCollections(CompositeFileCollection.java:172)
    at org.gradle.api.internal.file.CompositeFileCollection.visitRootElements(CompositeFileCollection.java:184)
    at org.gradle.api.internal.changedetection.state.AbstractFileCollectionSnapshotter.snapshot(AbstractFileCollectionSnapshotter.java:78)
    at org.gradle.api.internal.changedetection.rules.AbstractNamedFileSnapshotTaskStateChanges.buildSnapshots(AbstractNamedFileSnapshotTaskStateChanges.java:87)
    at org.gradle.api.internal.changedetection.rules.AbstractNamedFileSnapshotTaskStateChanges.<init>(AbstractNamedFileSnapshotTaskStateChanges.java:54)
    at org.gradle.api.internal.changedetection.rules.InputFilesTaskStateChanges.<init>(InputFilesTaskStateChanges.java:28)
    at org.gradle.api.internal.changedetection.rules.TaskUpToDateState.<init>(TaskUpToDateState.java:55)
    at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifactStateImpl.getStates(DefaultTaskArtifactStateRepository.java:164)
    at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifactStateImpl.isUpToDate(DefaultTaskArtifactStateRepository.java:79)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)

Comment: `minifyEnabled true` does not have any path, so it cannot be the line that causes the error. Which line contains the path that is null?
Comment: When you launch on an emulator are you building the release or debug configuration?
Comment: Which line causes the error?
Comment: If I comment out the line "minifyEnabled true" the build completes successfully also when running on a smartphone
Comment: That doesn't answer my question.
Comment: @Code-Apprentice The error is caused by the line "minifyEnabled true".... I got this stacktrace: **java.lang.IllegalArgumentException: path may not be null or empty string. path='null'
at org.gradle.api.internal.file.BaseDirFileResolver.doResolve(BaseDirFileResolver.java:72)
at org.gradle.api.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:79)**
Comment: I don't know which path is null else I was not asking for help! The only thing that I know is that if I comment out the line with minifyEnabled the builds complete without any error
Comment: I understand that removing `minify true` causes the error to go away. However, this is not the true cause of the error. For more help, you should [edit] your question to show the entire stack trace.
Comment: I added the stacktrace
Comment: Check out https://stackoverflow.com/questions/45387761/android-proguard-issue-path-may-not-be-null-or-empty-string-path-null which seems to be about the same problem
Comment: Do you have a file named `local.properties`?
Comment: Yes, I have a local.properties file containing the path of the keystore and the passwords. I have already checked the question you reported but it seems to be something different as I have the problem only if i launch a run on a "real" device but it works fine on emulator and I found very strange this behaviour as the build configuration is the same for the 2 environment
Comment: I'm building release configuration in both environment
Answer: Try to remove this:
Properties localProperties = new Properties()
try {
    localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
} catch (Exception e) {
    localProperties = null
}

and this:
signingConfigs {
    release {
        if (localProperties != null) {
            storeFile file(localProperties['store.file'])
            storePassword localProperties['store.password']
            keyAlias localProperties['key.alias']
            keyPassword localProperties['key.password']
        }
    }
}

and try by signing the build manually
Comment: @TheOni have u tried this? I answered this because I could only find this code segment related to the path.
Comment: this part of code works fine, if I run it in the emulator the build complete without any error. If I remove minifyEnabled it works fine also if I run it on a phisical device


Database designing with ERD or DFD

Question: actually this is a really basic question as i am new to database designing. I am student too, i study chunks of information but not as a whole. Now my purpose is to study or learn whole process. thats why i started designing database on my own but i found that that ERD and DFD(Data Flow Model) are necessary to create database from scratch. I viewed a file having different case studies in it. But every thing i viewed was started from direct relational tables.
I was unable to find such case studies having ERD or DFD in it.
 So my basic question is that, are there case studies with ERD or DFD? Can someone point me to the useful link?
Thanks for your help in advance and down votes are also welcome.
Comment: Well I googled `database case study ERD` and found one on the first hit: http://www.enggjournals.com/ijcse/doc/IJCSE10-02-08-050.pdf
Comment: Generally, I create (or let my tool create) the ERD after I define the tables.  I define the DFD as a check (test) of the tables, to see if the tables support the application properly.
Comment: RbarryYoung, thanks. i have seen it earlier, when i tried to read that  i was lost in it.
Answer: ER modeling, as originally devised by Peter Chen, is not a very good model for database design.  What it really excels in is data analysis.  Analyzing your data requirements before you begin designing your database is a really good idea  (although, in the real world, you often have to reiterate because the analysis is never complete).  A good ER model will allow you to connect each value to be stored in the database with a particular subject matter entity or relationship, and with a particular attribute
Converting an ER model into a relational model is not hard. and you generally end up with a design that's at least third normal form without even trying hard.
Where it gets confusing is that a lot of professionals use ER diagrams to depict a relational model rather than an ER model.  Here are the main differences between ER and relational:
In an ER model you don't have foreign keys.  Relationships are identified in the model, but they are not implemented.
In an ER model, you don't have or need junction boxes that are used to implement many-to-many relationships in a relational model.
normalization is not relevant to the ER model.  normalization is a feature of a design, not a feature of data requirements.
In practice, as already said,  a lot of professionals don't really distinguish between ER modeling and relational modeling.  But in the classical three stage approach, you create a conceptual model using ER modeling, a logical model using relational modeling, and a physical model using SQL modeling that's DBMS specific.  The three models address different issues.

Database designing with ERD or DFD


restarting tomcat service monit

Question: I have a Tomcat service running that fail sometimes - I did not find the reason yet. In the Catalina log I see the following:
Feb 03, 2022 10:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-80"]
Feb 03, 2022 10:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-443"]
Feb 03, 2022 10:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
Feb 03, 2022 10:54:39 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina

which gives no information about root cause.
When I try to see the service status:
$sudo -E service tomcatd status
tomcatd dead but pid file exists

I want to write simple monit script that will monitor this behaviour and restart tomcatd in case it happens, but I did not find any example to such a situation. Any idea?
Comment: Could you attach the full log or at least 20-30 more lines before `Stopping service Catalina`?
Comment: why is it relevant?
Comment: To solve the root cause.
Answer: To fix this try below.
kill -9 pid
ps -eaf|grep pid
service service-name restart

Now for monit you have to write script to check the logs and pid and execute the desired action.
Some examples are below
Monitor a process using monit in ubuntu
monit: check process without pidfile
To know the root cause you have to either run in debug mode or if you already running check the logs what happen before process die or become non-functional.
Comment: monit can't do 'service service-name restart'?
Comment: please check https://stackoverflow.com/questions/20713187/monit-restart-service-how-do-i-know-when-its-done-restarting if that help.

restarting tomcat service monit


Can we construct a ring of order $15$ without identity not isomorphic to $\mathbb{15}$?

Question: I've proved any ring of order $15$ with identity is isomorphic to $\mathbb{Z}_{15}$ but what if the ring is of order $15$ with no identity element ? Can we construct a ring of order $15$ without identity not isomorphic to $\mathbb{15}$ ?
Comment: Hint: Let all products be $0$.
Comment: I just did (there is only one choice for the additive group).
Comment: Yes I thought that but how to construct explicitly ?
Answer: The "trivial ring" example (with all products zero) has already been given, but you can also make one with nontrivial multiplication by taking $\Bbb Z_5$ with normal multiplication and $\Bbb Z_3$ with zero multiplication and form the product ring to get an example with nonzero multiplication.
You can also switch up which one uses zero multiplication, of course.


Why does Drupal store each custom field in a separated table?

Question: I understand that, in order to add functionality to nodes and node types, extra fields must be created in the database.
Now, I don't see why a one-field-one-table schema is used instead of favouring the schema of just a single table for a content type, and then, in that additional table, all the extra fields. What are the adventages of that approach?
I have a site with 1,000+ tables and is being a mess to administer.
Answer: Because you can reuse the fields and attach them to more than one content type for example.
You actually get 2 tables for each field: one for storing the current version of the data (field_data_field_MACHINE_NAME), and the other one for storing the "historic" (if revisions are enabled) values (field_revision_field_MACHINE_NAME). Some content types can have enabled revisioning, meaning that shared fields need to be "flexible" enough to follow up with that, but at the same time store the values for content types with disabled revisioning.
If you had everything in one big table for content types (I think D5 did this), it would be a really big mess to manage, especially if you would share fields between entities (e.g. nodes and users).
Few suggestions:

See this answer by Clive for more information.
Inspect this on a clean install just to see how it works. Create 2 content types, add some fields (share some of them) and track what has been changed and how is the data stored in the database. You could probably dig some documentation page, but I think this is the best way to understand the schema.
Reuse the fields whenever you can in order to optimize the database more. Be aware that there might be some limitations (e.g. list options, file uploads, required or not, etc.) that will not let you customize fields for every instance, so you will have to create new ones.

I wrote this fairly quickly, but I hope I managed to explain it.
Comment: Thank you very much for such detailed answer. Now I see the reason of that schema. Also I am seeing that for Field Collection, for example, and specifically nested field collections, it is almost mandatory to have this schema instead of a multifield one.
Comment: Sure, glad it helped.
Comment: With CCK in 5 and 6, when a field was on a single content type, it was stored in the table for that type.  When it got added to another content type, it got split out into its own table.
Answer: Great answer from Aram! Which includes an explanation of how "custom fields" are technically implemented in a Drupal database.
If you wonder where the "schema" (as in the question) originates from, I suggest a higher level of abstraction, which I (still) call the "data model" of which the Drupal database is a technical implementation. And that automatically leads to "Database normalization", a concept introduced by E. Codd. The most important concepts I remember from the time I graduated are these:

1st Normal form (1NF).
2nd Normal form (2NF).
3rd Normal form (3NF).

I do remember there were even more (like 4NF, etc.).
But the "Rule" we always used to measure the quality of our data model was this:

"Everything depends on the key, nothing but the key, so help me ... Codd" ...

About the actual "creation" of such schemas (diagrams), eg to model many-to-many relationships: back in the 90s (the time of Windows 3.1 and OS/2) there was IBM's "AD Cycle". Part of the "hype" then was to use "CASE tools".
One of them was "Bachman", an "expert system" created/inspired by Mr. "Charles W. (Charlie) Bachman", who was heavily involved in the creation of IDMS (a DBMS used in mainframes ... still today!). That's also where the "Bachman diagrams" originate from (which are still in use today ...).
We used the Bachman tool to:

automagically validate our data model (the wait messages was something like "wait while the bow tie expert advisor is verifying your design" ...) and
automagically forward engineer such datamodel to DBMS implementations for IDMS or DB2 and
reverse engineer an existing database implementation (eg hierarchical IMS) to a data model.

It would be fun (interesting) to do some similar reverse engineering today with the Drupal database schema, to see how "Bachman" would evaluate its corresponding datamodel ... and discover possible violations of 1NF, 2NF or 3NF ... (if any).
Note: More interesting background info can be found in Add foreign keys to core, as suggested in @mpdonadio's comment below.
PS: I bet Dries, while he was graduating, must also have heard of Codd ... or "Charlie".
Comment: Very interesting, indeed. I have no formal training in Computers Science, so didn't know about 1st, 2nd and 3rd Normal forms. I had to grasp similar concepts by trial-and-error, reading, experience and frustration. A pity I cannot dedicate more time to learning those basic concepts in the desired order instead of jumping from code example to code example and tutorial.
Comment: Well, that's why there are sites like Drupal.SE, no? Too bad it's not allowed to ask for (eg) "tutorials", "how to get started", etc ...
Comment: I am not sure if Dries has anything to do with the field system.  I think yched did the original version of CCK, and still maintains much of the current field system in 7 and 8.  See also https://www.drupal.org/node/111011 Without true FK support, NF discussions get a bit muddied.


Photoshop action to make 1 random layer visible within each group

Question: I'm trying to use Photoshop actions to generate randomized images that are composed of a random sampling of layers.  I have 3 groups of layers which are ALL not visible by default.

Within each group I'd like to make 1 random layer visible (in total there will be 3 "on" layers)
Export the whole thing as a .png file.
Repeat n times

Example Groups/Layers:
[FRUITS]
* [Apples]
* [Oranges]
* [Pears]
* [Bananas]
* [Kiwis]

[VEGGIES]
* [Asparagus]
* [Cilantro]
* [Eggplant]

[MEATS]
* [Beef]
* [Pork]

All layers are hidden by default, but when I play an action, I might get the following result (visible layers):
Image1: [Apples] [Eggplant] [Pork]
Image2: [Pears] [Asparagus] [Pork]
Image3: [Kiwis] [Cilantro] [Beef]

Comment: I don't think this can be done with actions alone -- you'll probably need scripting. Can you please [edit your question](https://stackoverflow.com/posts/55839953/edit) to let us know what you've tried so far?
Answer: Here Is my script, but don't forget to do the following steps before running it:

Hide All Layers and Groups Except Background.
Save Your PSD.
Close and then reopen.

Now you are ready to rock.
Features

Make Unlimited Patterns you want from your groups.

Saved All Patterns As Indexed separate PNG in Separate Folder named PNG.

Watch GIF (below) to understand more:

function Visible() {
  var Grps = app.activeDocument.layerSets; // loops through all groups
  for(var i = 0; i < Grps.length; i++){
    var tmp = app.activeDocument.layerSets[i].layers.length;
    app.activeDocument.layerSets[i].visible=true;
    var groupChildArr = app.activeDocument.layerSets[i].layers;
    var randLays = Math.floor(Math.random() * tmp);
    groupChildArr[randLays].visible = true;
    Save();
  }
  Revert();
}

function Save() {
  var outFolder = app.activeDocument; // psd name
  var outPath = outFolder.path;
  var fName = "PNG";   // define folder name
  var f = new Folder(outPath + "/" + fName);
  if ( ! f.exists ) {
    f.create()
  }
  var saveFile = new File(outPath + "/" + fName +"/" + "Pattern_" +  num + ".png");
  pngSaveOptions = new PNGSaveOptions();
  pngSaveOptions.interlaced = false;
  app.activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}

// Original code - revert function does not work
// for some users
//function Revert(){
//  var idslct = charIDToTypeID( "slct" );
//  var desc300 = new ActionDescriptor();
//  var idnull = charIDToTypeID( "null" );
//  var ref163 = new ActionReference();
//  var idSnpS = charIDToTypeID( "SnpS" );
//  ref163.putName( idSnpS, "test.psd" );
//  desc300.putReference( idnull, ref163 );
//  executeAction( idslct, desc300, DialogModes.NO );
//}

function Revert(){
   var idRvrt = charIDToTypeID( "Rvrt" );
   executeAction( idRvrt, undefined, DialogModes.NO );
}

var count = prompt("How many patterns you want","");
for (var x=0 ; x<count;x++){
  var num = x+1;
  Visible();
}


Monitor Java Heap on a Centos Server via Telegraf/Grafana

Question: How to Monitor Java Heap usage on  centos server using Telegraf and Grafana? This monitoring is particularly for Logstash process running on the server. I tried to use JSTAT to get data, but it has lot of numbers which needs manipulation to obtain heapsize. Is there a straightforward way to let telegraf send out heap size info?
Answer: Have you looked at using the Prometheus JMX exporter? Prometheus integrates with both Telegraf and Grafana nicely.


Questionamento sobre forma de abertura de array em PHP

Question: Dando um lida sobre arrays em PHP, acabei encontrando algumas formas distintas de se abrir um array, mas que no fim possuem o mesmo destino, exemplo:
$arr = [
   'dado' => ''
];

Ou
$arr = array(
  'dado' => ''
);

Ou
$arr['dado'] = '';

E em outro contexto, adicionando keys:
$a = 1;
while($a <= 10){
   $arr[$a] = 'dado'.$a;
   $a++
}

Existe alguma diferença relevante nesses diferentes modos de se abrir um array ?
Qual seria o modo mais 'correto' de se abrir um array ?
Comment: As duas últimas não geram o resultado esperado. Quer mesmo mantê-las na pergunta? Acho que, considerando o foco da discussão, as mesmas poderiam ser removidas.
Comment: Eu não cheguei a testar pra ver se o retorno é o mesmo, acho que da pra remover sim.
Comment: Procure sobre linguagens dinâmicas. Que é o caso do PHP, ele vai dar o tipo da variável no momento da atribuição do valor para ela. Como você declarou o array em 3 formas, ele vai entender que a variável é do tipo array. Acontece o mesmo com o javascript que tem tipagem dinâmica.
Answer: Sim existe (quando usar, ambos geram o mesmo resultado um array.), a sintaxe compacta ([])  só está disponível a partir do 5.4 para versões anterios apenas array() funciona. Para manter maior compatibilidade do código caso seja uma biblioteca recomenda-se o uso da sintaxe tradicional array().


Fixed point of an integral equation

Question: I got stuck on the second part of the following question:

Let $R = \{f:[0,1]\to\mathbb{R}\mid f\text{ is bounded, integrable and } f(x)\geq 0\forall x\in[0,1]\}$ be a metric space with the metric $d(f,g) = \sup_{x\in[0,1]}|f(x)-g(x)|$. Define the function $\Phi_f:[0,1]\to \mathbb{R}$ by
  $$\Phi_f(x) = \int_0^x \frac{1}{1+f(s)}ds.$$
  Show that this defines a Lipschits continuous map
  $$\Phi: R\to R.$$
  Explain why $\Phi$ has a fixed point.

I managed to show that $\Phi$ is indeed Lipschitz continuous as follows (which I'm not sure is correct, so if I have any mistakes please let me know)
$$
\sup|\Phi_f(x)-\Phi_g(x)|=\sup|\int_0^x \frac{1}{1+f(s)}-\frac{1}{1+g(s)}ds|\\
\leq\int_0^x|\frac{g(s)-f(s)}{1+f(s)+g(s)+f(s)g(s)}ds|\\
\leq (x-0)\sup|f(x)-g(x)|\\
\leq \sup|f(x)-g(x)|
$$
But since he Lipschitz contstant is 1, I can't use the Banach Contraction Theorem to show that $\Phi$ has a fixed point (Note: we haven't proved the mean-value theorem nor did we define differentiation, so I can't use either in proving the result above)
Comment: What is $a$ here?
Comment: I think in the integral you should have $0$ where you wrote $a$.
Comment: It was supposed to be 0, fixed it now
Answer: First of all,observe that $R$ is a closed convex subset of the Banach space $B[0,1]$,which is the space of all bounded functions on $[0,1]$ with sup-norm.Now,consider the collection of all such maps $\phi_{f}$ where $f$ is in $R$.Name this collection $S$.Now,you can show that any such $\phi_{f}$ is a continuous map on $[0,1]$.Using the fact that $f\geq 0$ for all $f$ in $R$,this collection can be shown to be bounded and equicontinuous.Hence,by Arzela-Ascoli theorem,$S$ is pre-compact.Now,as you have shown,the map $f\rightarrow \phi_{f}$ is Lipschitz continuous,defined on a closed convex subset of a Banach space,and from what I have shown above,it's image is contained in a compact set.Hence,by Schauder fixed point theorem,it has a fixed point.I hope it's all right.

Fixed point of an integral equation


What is the "sensible default" for the Kest function of the spatstat package?

Question: I'm reading the documentation on the Kest function (page 731) from the spatstat package.
For the argument $r$, that is the "Vector of values for the argument $r$ at which $K(r)$ should be evaluated", it states that:

Users are advised not to specify this argument; there is a sensible default.

I'm interested in knowing how this argument is specified. I went to look at the source for this function but I'm not an expert on R (I write in Python) and I can't decipher how it is calculated.
I know that the piece of code that determines this is here:
  rmaxdefault <- rmax %orifnull% rmax.rule("K", W, lambda)
  if(is.infinite(rmaxdefault)) rmaxdefault <- diameter(W)
  breaks <- handle.r.b.args(r, breaks, W, rmaxdefault=rmaxdefault)
  r <- breaks$r
  rmax <- breaks$max

  (...)

  # recommended range of r values
  alim <- c(0, min(rmax, rmaxdefault))

Assuming rmax=NULL (the default) and a rectangular window, could you explain how the final vector alim is obtained?
Comment: It's not necessarily a problem that this is a duplicate of a question *on another site*. If you want to delete this, you can. Alternatively, you can answer it yourself & reference the SO thread.
Comment: Just realized that this has been asked before over at SO: https://stackoverflow.com/q/14330415/1391441
Answer: The answer is in spatstat's FAQ:

How are the r values determined in Kest(X) ?

The default r values for Kest are computed as follows:

The maximum r value is computed by the function 'rmax.rule', rmax \<- rmax.rule("K", W, lambda) where W is the window containing the data,
and lambda is the average density of points per unit area. Currently
this rule takes the minimum of

Ripley's rule of thumb: rmax = one quarter of the smallest side of the enclosing rectangle
large sample
rule: rmax = sqrt(1000/(pi \* lambda))

r values are equally spaced
from 0 to rmax with step value eps. If eps is not specified, then
eps = rmax/512 so that there are 513 values or 512 intervals.

You can always override the r values if you need to.

This means that, for a window of (length,width)=[0,1]x[0,1] (ie: A=1) and assuming that the number of points is N , the array of radii values is obtained as follows (in pseudo-code):
rho = N / A  # density
thumb = A / 4 # rule of thumb
large = sqrt(1000 / (pi * rho)) # rule of large numbers
rmax = min(thumb, large)

Hence for N<~5000 the array of radii will be an equal-spaced segmentation of the range [0, 0.25] in 512 intervals.

This was also asked over at StackOverflow.


Filter by DateTime Range MVC 5

Question: Good evening everyone,
I home, anyone can help my with Date time range filter on  view part.
Here is my model:
public class IndexVM
{
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public virtual ICollection<Order> Orders { get; set; }

}

I'm using view models for display, now here is my controller:
public ActionResult Index(DateTime? start, DateTime? end)
    {

        var orders = db.Orders
            .Where(x => x.OrderStatus == 3
            && x.ClosedAt > start
            && x.ClosedAt < end)
            .OrderByDescending(x => x.LastUpdateAt)
            .ToList();

        IndexVM model = new IndexVM();
        model.StartDate = start;
        model.EndDate = end;
        model.Orders = orders;
        return View(model);
    }

Now I have some problems with view.
Here is My QUESTION:
How to  pass start and end date to controller to get orders with defined properties?
Here is My View and what I'm doing wrong?
@using (Html.BeginForm())
{

                @Html.TextBoxFor(model => model.StartDate, "{0:MM/dd/yyyy}", new { @class = "date-picker form-control", @id = "start", @placeholder = "Start Date" })

                @Html.TextBoxFor(model => model.EndDate, "{0:MM/dd/yyyy}", new { @class = "date-picker form-control", @id = "end", @placeholder = "End Date" })

                <input type="submit" value="Save" class="btn btn-default" />

}

Answer: Controller
public ActionResult Index(DateTime? start, DateTime? end)
    {
  ViewBag.start = start;
            ViewBag.end = end;
        var orders = db.Orders
            .Where(x => x.OrderStatus == 3
            && x.ClosedAt > start
            && x.ClosedAt < end)
            .OrderByDescending(x => x.LastUpdateAt)
            .ToList();

        return View(orders);
    }

View
@using (Html.BeginForm())
{

               @Html.TextBox("start", null, new { @class = "form-control datepicker" })

               @Html.TextBox("end", null, new { @class = "form-control datepicker" })

                <input type="submit" value="Save" class="btn btn-default" />

}

Comment: That doesn't work for me. It just gives 2 text input boxes. Could you update with a full solution?

Filter by DateTime Range MVC 5


Is it meaningful to compute a confidence interval when the sampling method is not a simple random sampling?

Question: The lower and upper bounds of the 95% confidence interval of the mean of a random variable with normal distribution of known variance $\sigma$ are $\bar{x}-1.96\frac{\sigma}{\sqrt{n}}$ and $\bar{x}+1.96\frac{\sigma}{\sqrt{n}}$.
$n$ is the size of the sample and $\bar{x}$ is the mean value of the sample.
One assumption is that the sample of size is obtained through a simple random sampling but what does it happen when the sample is not obtained through a simple random sampling but for example through a systematic sampling?
So, the alternative to simple random sampling is the systematic sampling where (quoting from wikipedia) the sampling starts by selecting an element from the list at random and then every $k$-th element in the frame is selected, where $k$, the sampling interval (sometimes known as the skip) is $k=\frac{N}{n}$ where $n$ is the sample size, and $N$ is the population size.
Is it meaningful to compute a confidence interval in this case?
What are the errors in using the above formula when the sampling is not a simple random sampling?
Comment: Yes. On another note: what you trying to compute? Systematic sampling is usefull when you specify group weights - I don't see any in hint about this in your question. If you have groups - why do you want to compute an overall mean? Why not group means? Why not, if you assume normality an ANOVA ... and so on. The answer to you question depends on the information which you want to extract, not on the method per se.
Comment: It would help alot if you describe what your application is. As for CIs, from frequentist appraoch, they rely on the underlying distribution (normal in your example above). However, if you can assume that your sample is i.i.d (which is probably not, based on your question) and you compute a statistic (on a subset) that involves sums you can apply CLT. Otherwise, it may help to open another question describing your data and what approaches to use.
Comment: Maybe take a look at highest denstity intervals.
Comment: @Drey are you meaning https://en.wikipedia.org/wiki/Credible_interval ?
Comment: @Drey I have no "group weights", in my application a simple random sampling is not feasible while a systematic sampling is feasible.
Comment: Would you kindly enlighten why random sampling is not feasible? It may be offtopic but it would greatly increase the quality of the question -- it could be that because of your application a computation of the confidence interval (of the statistic in context) is not meaningful.
Comment: @Drey, basically also the systematic sampling I wrote about is not feasible in my application but, just to start, I would like to have an idea about the derivation of the CI in that case.
Answer: You're not specific as to which alternative to simple random sampling you have in mind. One could deliberately pick the $100$ largest observations in a simple random sample of $200$. Or the $100$ smallest. If one assumes a normally distributed population, then application of usual formula that you quote to the $100$ largest observations would hardly ever yield an interval that includes the population mean.
Or one could make the same of $200$ the $200$ largest in the whole population. That would be even worse: The validity of any conclusion you could draw would depend on the size of the population.
In any of these cases, you would not get a valid confidence interval from the usual formulas.
If you were to specify a particular alternative way of sampling then one might be able to work out a valid formula from a confidence interval when that kind of sampling is used. For example, suppose the observations are jointly normal and identically distributed and the correlation between any two of them is $1/2$. I expect one could work out a formula for use in that case. (Although just how such a distribution for the sample would arise I don't know.)
Comment: If you sample from a finite population of size $N$, then the standard formula does not apply, because of the finite population size (although if $N$ is really really large and $n<<N$, the formula is about right). You will find plenty of information on that, if you google for survey sampling, Alessandro. However, it certainly makes sense to do a CI derived in a sensible way.
Comment: The alternative to simple random sampling, as I wrote in the question, is the systematic sampling where (quoting from wikipedia) the sampling starts by selecting an element from the list at random and then every $k$-th element in the frame is selected, where $k$, the sampling interval (sometimes known as the skip) is $k=\frac {N}{n}$ where $n$ is the sample size, and $N$ is the population size.
Comment: I've edited the question.
Comment: @Björn : You don't need to write $n<<N;$ you can write $n\ll N. \qquad$


slimv segfaulting on OS X Lion

Question: I have been trying to get slimv (http://www.vim.org/scripts/script.php?script_id=2531) working for a while now, but I am really not sure what else I can do.
I am running vim 7.3 compiled with python support, using clisp (sbcl is showing the same issue though) on os x lion. I pulled the latest version of slimv off of vim.org.
When I load a lisp file, echo g:slimv_loaded returns 1, but I do not get a second window with the repl. When I hit any of the keybindings, a new terminal window opens, starts clisp, and returns the following
; Loading file /Users/pdk/.vim/slime/start-swank.lisp ...
;;  Loading file /Users/pdk/.vim/slime/swank-loader.lisp ...
WARNING: No architecture feature found in
     (POWERPC PPC X86 X86-64 X86_64 AMD64 I686 I586 I486 PC386 IAPX386
     SPARC64 SPARC
     HPPA64 HPPA ARM PENTIUM3 PENTIUM4 JAVA-1.4 JAVA-1.5 JAVA-1.6
     JAVA-1.7).
;;  Loaded file /Users/pdk/.vim/slime/swank-loader.lisp
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-backend.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-backend.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/xref.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/xref.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/metering.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/metering.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-clisp.fas ...
WARNING: DEFUN/DEFMACRO: redefining function BREAK in
         /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-clisp.fas,
         was defined in
         /private/tmp/homebrew-clisp-2.49-LWCF/clisp-2.49/src/condition.fas
WARNING: Replacing method #<STANDARD-METHOD (#<BUILT-IN-CLASS T>)> in
         #<STANDARD-GENERIC-FUNCTION EMACS-INSPECT>
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-clisp.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-gray.fas ...
WARNING: The generic function #<STANDARD-GENERIC-FUNCTION STREAM-WRITE-CHAR>
         is being modified, but has already been called.
WARNING: The generic function #<STANDARD-GENERIC-FUNCTION STREAM-LINE-COLUMN>
         is being modified, but has already been called.
WARNING: The generic function #<STANDARD-GENERIC-FUNCTION STREAM-FORCE-OUTPUT>
         is being modified, but has already been called.
WARNING: The generic function #<STANDARD-GENERIC-FUNCTION STREAM-LINE-COLUMN>
         is being modified, but has already been called.
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-gray.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-match.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-match.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-rpc.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank-rpc.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/swank.fas
WARNING: These Swank interfaces are unimplemented:
         (ACTIVATE-STEPPING ADD-FD-HANDLER ADD-SIGIO-HANDLER
         BACKGROUND-SAVE-IMAGE
         DISASSEMBLE-FRAME DUP EXEC-IMAGE FRAME-CALL INTERRUPT-THREAD
         MAKE-FD-STREAM
         RECEIVE-IF REMOVE-FD-HANDLERS REMOVE-SIGIO-HANDLERS SEND
         SLDB-BREAK-AT-START
         SLDB-BREAK-ON-RETURN SLDB-STEP-INTO SLDB-STEP-NEXT SLDB-STEP-OUT
         SOCKET-FD
         SPAWN TOGGLE-TRACE)
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-c-p-c.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-c-p-c.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-arglists.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-arglists.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-fuzzy.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-fuzzy.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-fancy-inspector.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-fancy-inspector.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-presentations.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-presentations.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-presentation-streams.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-presentation-streams.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-package-fu.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-package-fu.fas
;;  Loading file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-hyperdoc.fas ...
;;  Loaded file /Users/pdk/.slime/fasl/2011-03-13/clisp-2.49-unix-unknown/contrib/swank-hyperdoc.fas
;; Swank started at port: 4005.
CL-USER>
;; swank:close-connection:
READ: input stream #<IO UNBUFFERED SOCKET-STREAM CHARACTER 0.0.0.0:4005> has reached its end

;; swank:close-connection: NIL

simultaneously, the original terminal window closes vim, and shows this
tab 1 of window id 57924
Vim: Caught deadly signal SEGV

Vim: Finished.
[1]    83648 segmentation fault  vim foo.lisp

Any ideas what I can do?
Answer: I've just received the following information from the macvim developer:
It seems this is a 64 bit issue -- compiling MacVim 32 bit appears to fix it. Please compile a 32 bit
version.  Build instructions are here, in order to build 32 bit the "configure" line must include the flag "--with-macarchs=i386".
Comment: Awesome, tamas. I was finally able to get it working. I have been using vanilla vim, and am still not able to get it working there, but macvim is close enough.
Comment: Is there any progress on making this work with a 64bit compiled MacVim?  Compiling 32 bit brings about problems with language support for other languages.
Comment: Nothing I have heard of, but I have no connection with MacVim, so you should ask the MacVim maintainer.
Answer:
If you change log = True in line 32 of swank.py, then Slimv writes a logfile called swank.log containing the communication data between the swank client and the server. This may be used to check for any swank protocol problems. You can send the logfile to the author of Slimv (that's me:) for analysis.
You could try to run your own swank server taken from Slime manually, then let Slimv connect it. This can help if the swank server bundled with Slimv is not fully Lion-compatible.
You may want to try the most recent version taken from the Slimv repository.
Comment: Tamas you are the kibo of SO.

I enabled logging in swank.py, but I can't find the log file. Where is swank.log written to by default?
I tried the most recent version from the repo, but got the same result
Comment: Well, on Windows or Linux it is written in the "current" directory, i.e. the one Vim was started from. But you can also change the logfile name in swank.py by specifying a full path: `logfile = '\mypath\swank.log'`. Then you'll know where to find it. It is also possible that the logfile was simply not created because Vim crashed before writing any log message. In this case you should switch verbose mode on (e.g. set verbosefile=\path\slimv.log | set verbose=20) before trying to open the repl buffer.
Comment: seems like it wasn't creating the file before it crashed. here ya go - http://patrickkettner.com/slimv_crash.txt  Thanks so much
Comment: Seems like you also have fugitive.vim installed and Vim crashed while executing the BufWinLeave autocommand for fugitive. Slimv does some heavy buffer/window switching and this may be interfering with those autocommands, so I suggest to perform a test with fugitive disabled. There's also a new slimv090 branch in the repository that does less buffer switching, you may want to try that one as well.
Comment: It seems you tried to eval form (+ 2 2) twice, and the second one came before the first one finished. There may be a bug here that needs to be hunted down, but first please do this: try to open the repl buffer via ,c (connect server) in verbose mode and don't use ,d (eval defun) yet. Please contact me in email (you can find it in the doc), it seems that this problem needs a little more conversation.[I've deleted my previous comment, because it was a total mistake, sorry about that.]
Comment: I'm having a similar problem, except that Vim segfaults as soon as I try to connect. // I'm using Slimv from the Mercurial repo, changeset 841be852040b // Here's a screencast showing the problem: http://www.screenr.com/r3Rs // Here are the swank log and verbosefile log: https://gist.github.com/1256851
Comment: Another user reported macvim 7.3-59 segfaulting, but everything worked fine using version 7.3-57. Something must have changed in Vim from 7.3-57 to 7.3-59 in regard to python. If possible please check if the older Vim version works for you as well.
Comment: Hm, you're right, snapshot 61 works while 62 (the latest) segfaults.
Comment: Sorry Tamas, for some reason I missed your last post to me, I emailed you if you would still like to talk about it, otherwsie thanks for all the help =]

slimv segfaulting on OS X Lion


Points with Nonzero Spectral Measure are Countable

Question: This is from Conway's functional analysis textbook, questioin IX.2.10

Show that if $\mathscr{H}$ is separable Hilbert space, there are at most a countable number of points $\left\{z_n\right\}$ in $\sigma(N)$ such that $E\left(z_n\right) \neq 0$, where $E$ is the spectral measure corresponding to $N$.

I'm aware that the spectral measure of a relatively open subset of $\sigma(N)$ is nonzero. Also, that a separable Hilbert space has a countable orthonormal basis. But I'm anaware that how to use separability over here.
Any help is appreciated.
Answer: Let $A=\{z\in\sigma(N): E(\{z\}) \ne 0\}$, and $S$ be a countable dense subset of $\mathscr{H}$.
Let $\mathcal{P}(S)$ be the power-set of $S$ and define a mapping $\tau: A\to \mathcal{P}(S)$ as follows
$$\tau(z) = \{s\in S:\exists v\, \left(v\in \mathscr{H}\land E(\{z\})(v)=v\land \|v\|=1\land \|v-s\|<\frac{1}{2}\right)\}$$
Claims

For each $z\in A$, $\tau(z)\ne\emptyset$.
For $z,w\in A$ such that $z\ne w$, $\tau(z)\cap\tau(w)=\emptyset$.

Since $S$ is countable, $S$ can be well-ordered, so there is a function $f:A\to S$ such that $f(z)\in\tau(z)$ for all $z\in A$.  (For example, choose the least element in a fixed well-order of $S$.)  By the second claim, $f$ is injective, and since $S$ is countable it follows that $A$ is countable.$\Box$
Now to prove the claims.  Start with the second claim.  Suppose $s\in \tau(z)\cap\tau(w)$.  This means there exist $v_z, v_w\in \mathscr{H}$ such that $\|v_z\|=\|v_w\|=1$, and $\|v_z-s\|, \|v_w-s\| < \frac{1}{2}$ and $E(\{z\})(v_z) = v_z$ and $E(\{w\})(v_w) = v_w$.  By the triangle inequality $\|v_z-v_w\|<\frac{1}{2}+\frac{1}{2} = 1$.  Moreover, since $\{z\}\cap\{w\}=\emptyset$, by the properties of spectral projections $E(\{z\})E(\{w\}) = E(\{w\})E(\{z\}) = E(\{z\}\cap\{w\})=E(\emptyset) = 0$.  But then
$$\langle v_z, v_w\rangle = \langle E(\{z\})v_z, E(\{w\})v_w\rangle = \langle E(\{w\})^* E(\{z\})v_z, v_w\rangle = \langle E(\{w\}) E(\{z\})v_z, v_w\rangle = 0$$
So $v_z, v_w$ are two orthogonal unit vectors, and then $\|v_z-v_w\|=\sqrt{2}$, contradicting the bound $\|v_z-v_w\|<1$ derived earlier.  This establishes the second claim.
For the first claim, for $z\in A$, $E(\{z\})\ne 0$ by assumption, so there is some non-zero vector $v$, which may be normalized such that $E(\{z\})(v) = v$.  Since the set $S$ is assumed dense, there is some $s\in S$ such that $\|v-s\| < \frac{1}{2}$.  Hence $\tau(z)$ is non-empty.


Python tkinter create multiple variables

Question: I started to code with tkinter and class methods. I try to code a to-do-list where I can create multiple entries by pressing a button below the entry. And a button next to the entry should change the color of the entry if pressed. The problem now is, that when I create multiple entries, the buttons only change the latest entry. So my question is how do I specify the entry when created?
Sry for obvious mistakes, Im new to coding :p
import tkinter as tk
from tkinter.constants import ANCHOR, CENTER, X
from tkinter import messagebox

class App():

    def __init__(self):
        self.window = tk.Tk()
        self.window.title("To-Do-List")
        self.window.geometry("700x700")

        self.x_but, self.y_but = 0.05, 0.2
        self.x_ent, self.y_ent = 0.05, 0.2
        self.x_but2 = 0.3
        self.check_var = True

        self.start_frame()
        self.grid1()
        self.window.mainloop()

    def start_frame(self):
        self.label1 = tk.Label(text="To Do List", font=("", 30))
        self.label1.place(relx=0.5, rely=0.05, anchor=CENTER)

    def grid1(self):
        self.button1 = tk.Button(text="Create", command= self.create_field)
        self.button1.place(relx = self.x_but, rely= self.y_but)

    def create_field(self):
        self.y_but += 0.05
        self.button1.place(relx= self.x_but, rely= self.y_but)

        self.entry1 = tk.Entry()
        self.entry1.place(relx= self.x_ent, rely= self.y_ent)

        self.button_check = tk.Button(text="✅", height= 1,command=self.check)
        self.button_check.place(relx= self.x_but2, rely=self.y_ent)

        self.y_ent += 0.05

    def check(self):
        if self.check_var:
            self.entry1.configure(bg="Green")
            self.check_var = False

        else:
            self.entry1.configure(bg="White")
            self.check_var = True

app = App()

Answer: You are changing the bg of self.entry1 which keeps overwriting itself each time an entry is created, so when button is clicked, it is always the last entry. The easiest solution is to define a parameter for check and then pass the required entry as an argument to it.
So the method would be:
def check(self,ent):
    if self.check_var:
        ent.configure(bg="Green")
        self.check_var = False

    else:
        ent.configure(bg="White")
        self.check_var = True

...and your button would be:
self.button_check = tk.Button(text="✅", height= 1,command=lambda x=self.entry1: self.check(x))

Also I hope you have a good reason to use place because using grid can make your life much easier, in this case.
For more explanation, read: Tkinter assign button command in loop with lambda
Comment: Thanks, but now the variable I defined for the green background doesn't work as planned. So when I check the first entry and check the second, I need 2 clicks to turn it green
Comment: @antal Because each time you click a button the value of _global_ `self.check_var` gets changed. You have to think of a better approach, I think its best to ask a new question for that


Como usar os argumentos passados para um script python?

Question: Em scripts php, podemos, quando executamos pela linha de comandos, capturar os seus valores dos argumentos passados através da variável $argv e o seu número através da variável $argc.
Por exemplo (Script):
echo 'My name is ', $argv[1]

Exemplo chamada:
 my_name_is.php Wallace

A saída será:

My name is Wallace

E no Python? Existe alguma maneira de capturar os argumentos passados para um script, via linha de comando?
Answer: Conforme esta resposta do SOen, você pode importar a biblioteca sys, alguns exemplos:
import sys

print "\n".join(sys.argv)

Outro exemplo com sys
import sys

for value in sys.argv:
    print value

Geralmente, o primeiro argumento de argv sempre é o nome do script que está sendo executado.
Por exemplo:
 > args.py one two tree

Retornaria
['args.py', 'one', 'two', 'tree']

Se você quiser retornar do argumento 1 em diante (listas começam a contagem do 0 zero), pode usar o slice para cortar o primeiro elemento da lista de argumentos.
Assim:
print sys.argv[1:]

Retorno:
['one', 'two', 'tree']

Se ainda você quiser usar a variável argv sem a necessidade de invocá-la do módulo sys, você pode fazer assim:
from sys import argv

print argv[1:]

Sei que tem outras maneiras de fazer, assim como o Python tem diferentes bibliotecas para propósitos semelhante, com o tempo vou editar e adicionar mais, acredito que o exemplo ficaria assim:
import sys

print 'Meu nome é ', sys.argv[1]


AngularJS MVC how to load a page?

Question: I'm trying to construct a "click and read" AngularJS website. I have a header that works that takes the user between a directory, contact page and the home page. That works fine. My question is:
How do I code this so that from the Home page the user can click a button or link that will take him/her to page2 then from page 2 another click will take them to page 3 and so on? I would also like them to be able to move the other direction as well.
Here is my file/folder structure:
app/app.js
app/lib

content/css/styles.css

header.html
index.html

views/contactMe.html
views/directory.html
views/home.html
views/page1.html

app.js
angular.module('myApp', ['ngRoute'])

.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/home', {
            templateUrl: 'views/home.html'
        })
        .when('/directory', {
            templateUrl: 'views/directory.html',
            //since this page requires a controller
            controller: 'myController'
        })
        .when('/contactMe', {
            templateUrl: 'views/contactMe.html',
            //since this page requires a controller
            controller: 'myController'
        })
        .otherwise({
            redirectTo: '/home'
        });

}]);  //.config

angular.module('myApp')
   .controller('myController', function($scope) {
      $scope.message = ("Hello World");
}
});

header.html

My Sample App

Home

Directory

Contact Me

index.html
<!DOCTYPE html>

    <title>Sample app</title>
    <link href="content/css/styles.css" rel="stylesheet" type="text/css" />

Answer: You can add in each page button to go back: Go Back and also button to go to next page (if you do not have a lot of pages, you can do it manually) - Go to page1
Here is my example:

Header

Home

Directory

Contact Me

    Body

home.html:
Go to page1

Go Back

home

working plunker: http://next.plnkr.co/edit/1cBb8TzSX5mDJy4v
EDIT: http://next.plnkr.co/edit/Gm0TkOZCIxwxDerQ
Comment: I want to keep my existing header. Can I use your answer if I do not incorporate your header code? Thank you.
Comment: @JohnM. Of course you can keep your existing header, check out edit

AngularJS MVC how to load a page?


Reducing a matrix to Smith normal form

Question: I am trying to reduce the following matrix to Smith normal form
$$A= \begin{pmatrix}
1&0&0\\
1&2&0\\
1&0&3
\end{pmatrix}$$
Whatever row and column operations I try, I end up with the diagonal matrix
$$A= \begin{pmatrix}
1&0&0\\
0&2&0\\
0&0&3
\end{pmatrix}$$
However for Smith normal form I need diagonal entries $a_i$ such that $a_j|a_{j+1}$. But $2$ does  not divide $3$ here. How do I rectify this?
Answer: Newman says that Smith form can be accomplished with elementary row and column operations as long as the coefficient ring is Euclidean, as here. Since we are not going to change the determinant, this means diagonal $(1,1,6).$ Newman's assurance means that we can accomplish this for the two by two square with entries $(2,3).$
Take distinct positive integers $p,q$ such that $\gcd(p,q) = 1$ and
$$ px + qy = 1. $$ Then the sequence of resulting matrices is
$$
\left(
\begin{array}{rr}
p & 0 \\
0 & q
\end{array}
\right),
$$
$$
\left(
\begin{array}{rr}
p & 0 \\
px & q
\end{array}
\right),
$$
$$
\left(
\begin{array}{rr}
p & 0 \\
1 & q
\end{array}
\right),
$$
$$
\left(
\begin{array}{rr}
1 & (1-p)q \\
1 & q
\end{array}
\right) =
\left(
\begin{array}{rr}
1 & q-pq \\
1 & q
\end{array}
\right)
$$
$$
\left(
\begin{array}{rr}
1 & 0 \\
1 & pq
\end{array}
\right)
$$
$$
\left(
\begin{array}{rr}
1 & 0 \\
0 & pq
\end{array}
\right)
$$
Answer: Here's the way I determine the Smith normal form.

First find the gcd of all entries of the matrix - its easy to see this is 1. So $f_1(x) = d_1(A)/d_0(A) = 1/1 = 1$
Now you need to find the gcd of determinants of ALL $2 \times 2$ submatrices. There are 7 such submatrices. The determinant of the upper left matrix is 2. The determinant of the upper right matrix is 0. The determinant of the lower left matrix is -2. The determinant of the lower right matrix is 6.  Now consider submatrices obtained by removing the middle column. The first is obtained by removing the bottom row, and its determinant is 0. The second by removing the middle row, its determinant is 3. The last by removing the top row, its determinant is also 3. So here we see that the gcd is again 1. Now $f_2(x) = d_2(A)/d_1(A) = 1/1 = 1$.
Lastly, the only $3 \times 3$ submatrix is the matrix itself, and it has determinant 6. So  $f_3(x) = d_3(A)/d_2(A) = 6/1 = 6$.

So we have Smith normal form $\text{Dg}[1,1,6]$. I have elaborated step number 2, as it is a common error not to consider ALL the relevant minors. This step can be considerably shortened with a smarter heuristic type of search, in this case I would follow a "hunch" that most probably I can find determinants 2, 3 which are relatively prime. Its easy to find the submatrix with determinant 2, and then if I start by deleting the middle column I can quickly find the submatrix with determinant 3. Once I have these two I know the gcd is 1, so no further calculation is required.

Reducing a matrix to Smith normal form