text:
Q: Cannot update any support library in Android I decided to update dependencies in our project. Currently, version of all com.android.support components is 27.0.2. When I try to update for example recyclerview to 27.1.1 I got two strange errors:

error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
error: android.arch.persistence.room.RoomProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.

Like I said, this happens for all support components like design, cardView etc. Furthermore when I build project with the help of console I can see that some exception is thrown
[UPDATE]
The following exception is not caused by upgrading support library version, just ignore this
Could not perform incremental compilation: Could not connect to Kotlin compile daemon
Could not connect to kotlin daemon. Using fallback strategy.
e: java.lang.ClassNotFoundException: com.sun.tools.javac.util.Context
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.jetbrains.kotlin.gradle.tasks.JarSearchingUtilKt.findToolsJar(jarSearchingUtil.kt:79)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:20)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:14)
        at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getToolsJar(GradleCompilerEnvironment.kt)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getCompilerFullClasspath(GradleCompilerEnvironment.kt:23)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileOutOfProcess(GradleKotlinCompilerRunner.kt:302)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:171)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:53)
        at org.jetbrains.kotlin.compilerRunner.KotlinCompilerRunner.runCompiler(KotlinCompilerRunner.kt:127)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompiler(GradleKotlinCompilerRunner.kt:108)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:382)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:251)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:215)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        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.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Unknown Source)

I paste my build gradle files (top and app).
Top level:
buildscript {
    ext.kotlin_version = '1.2.20'
    repositories {
        jcenter()
        google()
        maven { url 'https://maven.fabric.io/public' }
        maven { url "https://dl.bintray.com/kotlin/kotlin-dev/"}
    }
    dependencies {

        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'io.fabric.tools:gradle:1.25.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.6.0'
        classpath 'com.google.gms:google-services:4.0.1'
        classpath 'com.google.firebase:firebase-plugins:1.1.5' // Crash Reporting plugin

    }
}
allprojects {
    repositories {
        jcenter()
        google()
        maven { url "https://maven.google.com"} // Google's Maven repository}
        maven { url "https://jitpack.io" }
        maven { url "https://dl.bintray.com/kotlin/kotlin-dev"}
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And app module:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'
apply plugin: 'com.google.firebase.firebase-crash'

androidExtensions {
    experimental = true
}

def mVersionName = "1.0.2"

android {

    dexOptions {
        javaMaxHeapSize "6g"
    }

    compileSdkVersion 27
    buildToolsVersion '27.0.3'

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 81
        versionName mVersionName
        // set the name of the genereted apk including version name

        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }

        // TEST (integration)
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        testHandleProfiling true
        testFunctionalTest true
    }

    packagingOptions {
        exclude 'META-INF/rxjava.properties'
        exclude 'META-INF/LICENSE'
        exclude 'LICENSE.txt'
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    aaptOptions {
        // important to run code on kitkat
        additionalParameters "--no-version-vectors"
    }

    // directories like src/test/kotlin and src/androidTest/kotlin are not detected
    // as Android test locations by default (yet?),
    // we need to make Gradle and Android Studio aware of them.
    sourceSets {
        test.java.srcDirs += 'src/test/kotlin'
        androidTest.java.srcDirs += 'src/androidTest/kotlin'
    }

    // when true it won't throw an exception when referencing to Android eco system - to View/ activity etc.
    testOptions {
        unitTests.returnDefaultValues = true
    }

    // Always show the result of every unit test, even if it passes.
    testOptions.unitTests.all {
        testLogging {
            events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
        }
    }

    lintOptions {
        abortOnError false
    }
}

//Ensure Kotlin will not be used in production code.
afterEvaluate {
    android.sourceSets.all { sourceSet ->
        if (!sourceSet.name.startsWith('test') || !sourceSet.name.startsWith('androidTest')) {
            sourceSet.kotlin.setSrcDirs([])
        }
    }
}

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url "http://dl.bintray.com/glomadrian/maven" } //kod sms - edittext type
    mavenCentral()
}

kapt {
    generateStubs = true
}

dependencies {
    implementation 'com.android.support:support-v4:27.0.2'
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // Dependencies for local unit tests
    // Required for local unit tests (JUnit 4 framework)
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:2.10.0'
    // required if you want to use Mockito for unit tests
    testImplementation "com.nhaarman:mockito-kotlin-kt1.1:1.5.0"
    testImplementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testImplementation 'org.amshove.kluent:kluent:1.33'
    // a library with really cool assertion semantics

    // INTEGRATION TEST
    androidTestImplementation 'org.mockito:mockito-android:2.8.47'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation "com.android.support:support-annotations:27.1.1"
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs'
    })
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'design'
        exclude group: 'com.android.support', module: 'recyclerview-v7'
    }
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.3'

    // Multidex support
    implementation 'com.android.support:multidex:1.0.3'

    // Kotlin plugin for enabling Kotlin language
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.19.3"

    // Play Services
    String playServices = '11.8.0'
    String firebase = playServices
    implementation 'com.google.android.gms:play-services-location:15.0.1'

    implementation 'com.google.android.gms:play-services-places:15.0.1'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-crash:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.1.0' // Cloud Messaging

    // MAPS
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.maps.android:android-maps-utils:0.5'

    // Widgets / Views
    String supportLibrary = '27.0.2'
    implementation 'tk.zielony:carbon:0.15.0.1'
    implementation "com.android.support:appcompat-v7:$supportLibrary"
    implementation "com.android.support:design:${supportLibrary}"
    implementation "com.android.support:support-v4:${supportLibrary}"
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation "com.android.support:recyclerview-v7:${supportLibrary}"
    implementation "com.android.support:support-vector-drawable:${supportLibrary}"
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'

    // Android Architecture
    // LiveData and ViewModel
    String androidLifecycle = '1.0.0'
    String androidLifecycleExtension = '1.1.0'
    implementation "android.arch.lifecycle:common-java8:$androidLifecycleExtension"
    implementation "android.arch.lifecycle:extensions:$androidLifecycleExtension"
    annotationProcessor "android.arch.lifecycle:compiler:$androidLifecycle"
    kapt "android.arch.lifecycle:compiler:$androidLifecycle"
    implementation "android.arch.lifecycle:reactivestreams:$androidLifecycleExtension"

    // Room - DB ORM
    implementation "android.arch.persistence.room:runtime:$androidLifecycle"
    implementation "android.arch.persistence.room:rxjava2:${androidLifecycle}" // RxJava2 Support
    annotationProcessor "android.arch.persistence.room:compiler:$androidLifecycle"
    kapt "android.arch.persistence.room:compiler:$androidLifecycle"
    // Paging
    implementation "android.arch.paging:runtime:1.0.0-alpha4-1"

    // Retrofit
    implementation 'com.squareup.okhttp3:okhttp:3.9.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

    String jackson = '2.9.4'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:converter-jackson:2.3.0'
    implementation "com.fasterxml.jackson.core:jackson-core:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-annotations:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-databind:${jackson}"
//    implementation "com.fasterxml.jackson.module:jackson-module-kotlin:${jackson}"

    // RxJava
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.14'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'

    // View injection
    String butterKnife = '8.6.0'
    implementation "com.jakewharton:butterknife:${butterKnife}"
    annotationProcessor "com.jakewharton:butterknife-compiler:${butterKnife}"
    kapt "com.jakewharton:butterknife-compiler:${butterKnife}"

    // Injection
    String dagger = '2.16'
    implementation "com.google.dagger:dagger:${dagger}"
    implementation "com.google.dagger:dagger-android:${dagger}"
    implementation "com.google.dagger:dagger-android-support:${dagger}"
    annotationProcessor "com.google.dagger:dagger-compiler:${dagger}"
    annotationProcessor "com.google.dagger:dagger-android-processor:${dagger}"
    kapt "com.google.dagger:dagger-compiler:${dagger}"
    compileOnly 'org.glassfish:javax.annotation:10.0-b28'

    // EventBus
    implementation 'org.greenrobot:eventbus:3.1.1'

    // Bug / Crash / Memory Leaks libraries
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.0@aar') {
        transitive = true
    }

    String leakCanary = '1.5.1'
    debugImplementation "com.squareup.leakcanary:leakcanary-android:${leakCanary}"
    releaseImplementation "com.squareup.leakcanary:leakcanary-android-no-op:${leakCanary}"
    androidTestImplementation "com.squareup.leakcanary:leakcanary-android-no-op:${leakCanary}"

    // Stetho is a sophisticated debug bridge for Android applications.
    // When enabled, developers have access to Database Inspection, and many more
    implementation 'com.facebook.stetho:stetho:1.5.0'
    implementation 'com.jakewharton.timber:timber:4.6.0'
    implementation 'net.ypresto.timbertreeutils:timbertreeutils:1.0.0'

    // Support Libraries
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.github.vipulasri:timelineview:1.0.5'
    implementation 'com.googlecode.libphonenumber:libphonenumber:8.2.0'
    // letter spacing in description view (tablica rejestracyjna)
    implementation 'com.andrognito.kerningview:kerningview:1.0.0'
    // drawable with description inside
    implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    // view pager steps indicator (new damage)
    implementation 'com.github.rakshakhegde:stepper-indicator:2.0.0-alpha'
    // do display photo (zoom ect.)
    implementation 'com.github.chrisbanes:PhotoView:2.1.3'
    // Notification Badge
    implementation "me.leolin:ShortcutBadger:1.1.21@aar"
    // better library to handle Date()
    implementation 'net.danlew:android.joda:2.9.9.1'
    testImplementation 'joda-time:joda-time:2.9.9'

    // Picasso transformation from https://github.com/wasabeef/picasso-transformations
    implementation 'jp.wasabeef:picasso-transformations:2.2.1'
    implementation 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'

    // better spinner from https://github.com/Lesilva/BetterSpinner
    implementation 'com.weiwangcn.betterspinner:library-material:1.1.0'

}

kotlin {
    experimental {
        coroutines "enable"
    }
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'org.jetbrains.kotlin.android.extensions'

A: Instead of updating support library I started updating Kotlin. I set version from 1.2.20 to 1.2.51, then apply kotlin kapt plugin
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

and remove this block of code:
kapt { generateStubs = true }

Also I changed method name for dagger android processor
kapt "com.google.dagger:dagger-android-processor:${dagger}"

After these steps I still got some errors, but this time there were much more explicit and easy to solve. Issue fixed.


text:
Q: How to sum only 2nd column values using powershell? sharesize.ps1
echo " "
$date1 = Get-Date
Write-Host -foreground Yellow -background Black "Script Started at $date1"

$path = "\*"

get-childitem $path | where {$_.PSIsContainer} | foreach {

$size = (Get-ChildItem $_ -recurse | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum

$size = "{0:N2}" -f ($size / 1MB) + " MB"

$obj = new-object psobject
add-member -inp $obj noteproperty Path $_.fullName
add-member -inp $obj noteproperty "Size(MB)" $size
[array]$report += $obj
}

#display the table
$a = ""

$report | Sort 'Size' -Descending | ConvertTo-HTML -head $a -title "Process Information" -body "
Service Information
"| Out-File -Append c:\temp\folder.html

$date2 = Get-Date
echo " "
Write-Host -foreground Yellow -background Black "Script Ended at $date2"
echo " "

Above code is working great to me, help is much appreciated for the below help.
Here my requirement is to add sum of 2nd column volues and append the output to the last line of the above code output html(c:\temp\folder.html) as,

       Path                   | Size(MB)

 C:\NVIDIA\Displaydriver      |  400 MB
  *                           |  860 MB
  *                           |  100 MB
  *                           |   * MB
  *                           |   * MB

       Total                  |  1000 MB(sum of all numbers in 2nd column values)

and also i need to align the 2nd column values and Total row to CENTER.
Please Help

A: To sum the sizes do this:
$totalSize = ($report | Measure-Object 'Size(MB)' -Sum).Sum

A: $total = 0
$report | % {[float]$tmp = $_."Size(MB)".TrimEnd(" MB"); $total += $tmp}

Then you can just add the $total object to your custom $report object before you convertTo-html and bango. Thanks for the neat script.
Only thing that confused me a little was your () your size property of $report makes PS think its a method, thus the quotes. Is not the best convention, but it works.
More explicitly :
...
[array]$report += $obj
}

$total = 0
$report | % {[float]$tmp = $_."Size(MB)".TrimEnd(" MB"); $total += $tmp}
$obj = new-object psobject
add-member -inp $obj noteproperty Path "Total Size: "
add-member -inp $obj noteproperty "Size(MB)" $total
[array]$report += $obj
#display the table
...

Also, Remove | Sort Size -Descending for the total to appear on the bottom.

A: I had a similar need and here is my simple solution:
$stuff=get-stuff
$results=
    foreach ($item in $stuff) {
        $item | select column1,@{N="Column 2";E={$_.column2}},description,created,@{N="Size (GB)";E={"{0:N2}" -f $_.sizegb}}
    }

$results_sorted=@($results | sort created)
$results_sorted+=$item | select @{N="column1";E={"Totals"}},@{N="Column 2";E={$null}},@{N="Description";E={$null}},@{N="Created";E={$null}},@{N="Size (GB)";E={($results | Measure-Object "size (gb)" -Sum).Sum}}
$results_sorted | ft column1,"Column 2",Description,Created,"Size (GB)"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get C-style functions from source file? I need to read source file and find all c/c++ functions and get them for further proccessing. Tried it with PHP and regexp
$patt = '/([a-z ]*?)(\w+?)\s*(\(.*?\))\s*(\{.*\})/s';

But looks like its wrong way. What is the best way to do it?
Here's the example of function that i need to get:
int main(int argc, char **argv){
   int a=11112,baa=3,c;
   int a[] ={1,32,3,4,535,35,3,114};
   c=a+b;
}

As you can see 114}; that curve ruins regexp. So I think there's a better solution.

A: Introduction
There have been many hints in the comments that it cannot be done using regular expression matching and must be done by parsing using more powerful tools, but have not really explained why this is so, or even why parsing is different from regular expression matching. It might leave the reader with the impression that if one worked really hard that you might be able to do it or if you were really clever enough you could do it too. This is not true but needs a detailed explanation to really understand why.
It is an element of a good computer science education to understand problems like this, to such a degree that questions like yours are often set as examination questions to enable a student's understanding of the theory as applied to programming problems to be demonstrated. The weak student will try and write the regular expression and the strong student will demonstrate why it is impossible.
Such questions also show why just being a good and experienced programmer is not good enough. Irrespective of how many years of programming and computer experience someone has, without encountering the theory, this remains an insoluble problem. It is also my lament that some modern computer science degree courses, which focus on practical tasks, such as the creation of apps and modern platforms, often omit this critical element.
Background
So to the theory. We cite the work of Noam Chomsky and his Language Hierarchy. This outlines different levels of language specification mechanisms (Grammars) and distinguishes between their capabilities. The simplest form of grammar would be called Chomsky type-3, which represented a regular language, which we use as regular expressions.
A regular expression, irrespective of implementation or notation, has the ability to specify repeated sequences of symbols. Anything that is formed by patterns of repeating symbols can be matched by a regular expression.
We can match sequences of a, b and cs, such as(+):
(a|b|c)*              --- any number of a,b,c's in any order
a*b*c*                --- any number of a,b,c's in order
(abc|cba|bac|cab)*    --- any number of a,b,c's in equal number

However, one thing we cannot do is write a pattern for equal number of a,b,c's in a specific order, such as:
aabbcc, aaabbbccc

This also works for symbols like brackets:
[[bb]], {{{bbb}}}, ((((bbbb))))

What regular grammars cannot do is specify correct nesting. A more powerful mechanism is needed for that. The more powerful mechanism is known as Chomsky type-2 language, or context free grammars. (*) We normally experience these as the rules of grammar in some notation such as BNF or similar. We can handle nesting like this:
exp -> ( exp ) | id
id  -> a | b | c

This then gives us the equal numbers of open and close brackets we desire.
The Question
So, lets get back to the original question. How can we match C/C++ functions? If the language only allowed functions to look like this:
type name (type1 parameter1, type2 parameter2, ...) {
 ... body ...
 }

Your regular expression would do it, but as you noticed, there are structures inside a function that can contain pairs of {} that require something can handle nesting. Sometimes at this point some programmers think they can write code to count the number of open { and close } and avoid the need for grammars and parsers. However, it does not take many examples to show the flaws in this approach. Consider:
my function (an arg) { /* } */ arg = "{"; outch('{'); /* } */ }

Which shows not all symbols will be nested equally.
As a consequence, to identify functions in a language like C/C++, one has to almost fully parse (process) almost all the structures of the language using a set of rules for most of the language. To do this usually requires using a parser generator tools, such as suggested in the comments. Bison, yacc, antlr and so on, are examples of such tools.
Summary
In explaining why this is a question identifying a particularly special problem in computer science, I hope that over questioners and novice programmers would avoid the similar mistake and be lead to the correct knowledge that will enable their problem to be solved. Even better, it might lead some to update their knowledge of this important area of computer technology.

[+] I'm just typing this live, from my memory, and not from a text-book. If I err at the nature or detail of the example I apologise. My favourite book for examples and explanations of this material is: Cleaveland, J.C & Uzgalis, R.C. (1976) Grammars for Programming Languages. If you have one, you are a lucky person.
(*) For those who know the pedandic difference between a grammar and the language it generates, I apologise at by blurring of terminology.


text:
Q: The expected value of $1/(1+X)$ where $X$ has geometric distribution
Let $X$ be a random variable with a geometric distribution with parameter $p$.
Calculate $\Bbb E[1/(1+X)]$

I've looked at answers online but still do not understand how to solve this.
Specifically, I do not understand how to to get from $$\frac{p}{1-p} \sum_{x=0}^\infty (1/(1+x))((1-p)^x+1)$$  to  $-p\ln(p)  /(1-p)$.

A: Assuming that $X\in \{0, 1, \ldots\}$ is the geometric distribution counting failures before a first success.
Use the fact that $\mathsf E(g(X)) = \sum_x g(x)\;\mathsf P(X=x)$
$$\begin{align}
\mathsf P(X=x) & = p (1-p)^x \quad \mathbf 1_{x\in \{0, 1,2,\ldots\}}
\\[2ex]
\mathsf E\left(\frac 1{1+X}\right) & = \sum_{x=0}^\infty \; \frac 1{1+x} p(1-p)^x
\\[1ex] & = \frac{p}{1-p} \sum_{k=1}^\infty \frac{(1-p)^k}{k}
\end{align}$$
Then use the Taylor expansion: $$\ln (1+z) = \sum_{k=1}^\infty {(-1)}^{k-1}\frac{z^k}{k}$$


text:
Q: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' (php 5.6+) A cronjob keeps raising this issue
Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'

the cronjob:
php /path/to/public/index.php /cron

My server:
PHP Version 5.6.23 (Apache Handler)
Ubuntu 14.04
The line provoking the error is FatFreeFramework's SQL php class:
function __construct($dsn,$user=NULL,$pw=NULL,array $options=NULL) {
    $fw=\Base::instance();
    $this->uuid=$fw->hash($this->dsn=$dsn);
    if (preg_match('/^.+?(?:dbname|database)=(.+?)(?=;|$)/is',$dsn,$parts))
        $this->dbname=$parts[1];
    if (!$options)
        $options=array();
    if (isset($parts[0]) && strstr($parts[0],':',TRUE)=='mysql')
        $options+=array(\PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.
            strtolower(str_replace('-','',$fw->get('ENCODING'))).';');
    $this->pdo=new \PDO($dsn,$user,$pw,$options);
    $this->engine=$this->pdo->getattribute(\PDO::ATTR_DRIVER_NAME);
}

After reading
Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in Undefined class constant (PHP 5.5.3)
I've tried adding the extensions in the php.ini, to no avail.
 extension=pdo.so
 extension=pdo_mysql.so

This SO post seems to indicate that the constant is not necessary but the thread was never closed. Advises welcome.


text:
Q: Python game logic: "coins" variable is not incrementing I am working on a game where the player is in search of treasure. Everything works perfectly, although my money system does not work. I need my code to work so that if the user lands on a treasure chest, they gain 10 extra coins. However, their number of coins is being set to 10 instead of adding 10.
import easygui
import time
from random import *
# Set up Initial Variables
Money = 0
grid = []
character = "X"
# player_loc will hold the x, y location of the player
player_loc = (0, 0)
# These are a mapping of direction
NORTH = "N"
SOUTH = "S"
EAST  = "E"
WEST  = "W"   #All variables used for Later on
Treasure = "T"
Goblin = "G"

def menu(): #function
   msg = "Would you like to...?" #Users choice to start game
   buttons = ["start", "quit"]
   while True:
      title = "Menu"
      selection = easygui.buttonbox(msg, title , buttons)
      if selection == "quit":
          exit()
      elif selection ==  "start": #If users input is to start the game the all of this appears("Welcome to the treasure hunt game!")
         easygui.msgbox("These are the rules! You have a choice of a grid ranging from a 3x3 choice to a 20x20 choice")
         easygui.msgbox("In these grids, bandits and treasure chests will spawn at random locations, hidden to you.")
         easygui.msgbox("You will have a choice of the amount of goblins and treasures you would like to spawn in, ranging from 1-2")
         easygui.msgbox("You will move around the map, in search of treasures which will give you 10 gold. Although landing on a goblin would deduct the amount of gold to 0.")
         easygui.msgbox("Furthurmore, just deciding on a position you would like to move to, would give you an extra 1 piece of gold.")
         easygui.msgbox("You can only find the same treasure chest two times before it's replaced by a bandit.")
         easygui.msgbox("To check the amount of gold you have and the amount of bandits and treasure chests in the grid. Simply type 'status'")
         easygui.msgbox("Don't forget! If you have collected all the treasure chests and you don't have 100 gold, you lose the game!")
         easygui.msgbox("Good luck, you will now be entered into the game")
         easygui.msgbox("Ok! let's jump into the game!")
         setupGrid()
         Chests_and_Goblins()

def setupGrid(): #New function for creating grid
    global grid #Adding/creating global variables
    global row
    global N
    N = easygui.integerbox("How big would you like the grid to be?")                #User input
    while int(N) > 20: #Changing N to an integer so computer understamds
        N = easygui.intergerbox("That number is too high, The grid has to be at a size of under 20x20")
    else:
        while int(N) < 3 : # Asking the user to input again as number is too high or low
        N = easygui.integerbox("That number is too low, the grid has to be a size of over 3x3. Please try again")
       for x in range(0, (int(N))):#For everything in range N
           row = [] #The N amount of rows are created
           for y in range(0, (int(N))): #For everything in range N
               if x == player_loc[0] and y == player_loc[1]: #If the positions is equal to th player location
                   row.append(character) # Add the character in
               else:
                   row.append('O') #Add the same amount of 0's as N
           grid.append(row)

def Chests_and_Goblins(): #Function used for adding the treasures and goblins in the grid
   global grid
   global row
   global Treasure
   B = easygui.enterbox(" How many chests would you like in the grid? The amount of chests you like is given by the amount of C's")
   F = easygui.enterbox(" How many Bandits would you like in the grid? The amount of bandits you like is given by the amount of B's")
   for each in B:
       grid[randint(0, int(N)-1)][randint(0, int(N)-1)] = Treasure
   for each in F:
      grid[randint(0, int(N)-1)][randint(0, int(N)-1)] = Goblin
   gridRunner()

def moveSouth(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0] + n][player_loc[1]] = character
    player_loc = (player_loc[0] + n, player_loc[1])
    money()

def moveNorth(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0] - n][player_loc[1]] = character
    player_loc = (player_loc[0] - n, player_loc[1])
    money()

def moveEast(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0]][player_loc[1] + n] = character
    player_loc = (player_loc[0], player_loc[1] + n)
    money()

def moveWest(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0]][player_loc[1] - n] = character
    player_loc = (player_loc[0], player_loc[1] - n)
    money()

def gridRunner():
    while True:
        for row in grid:
            print (row)

        switch = {NORTH : moveNorth,
                  SOUTH : moveSouth,
                  EAST  : moveEast,
                  WEST  : moveWest }
        print (" ")
        P = easygui.enterbox("What direction would you like to move in? North (N), South(S), East(E) or West(W)?")
        if P not in switch:
            easygui.msgbox("invalid move")
            continue
        distance = easygui.integerbox("How far would you like to move in this direction? (blocks are the units)")
        switch[P](distance)

   def money():
   global player_loc
   global character
   global Treasure
   if player_loc == Treasure:
      print("Well done, You have gained coins")
      money = 10
   else:
      print ("You got nothing")
      money = 0

menu()

A: In this part here:
  if player_loc == Treasure:
      print("Well done, You have gained coins")
      money = 10

You are setting the money to 10, not adding 10. All you need to do is:
money += 10

Also make sure def money(): isn't indented; it won't work as it currently is indented.

A: It looks like you have to indent the code under your money() function first:
   def money():
       global player_loc
       global character
       global Treasure
       if player_loc == Treasure:
          print("Well done, You have gained coins")
          money = 10
       else:
          print ("You got nothing")
          money = 0


text:
Q: EventBus Producer has been invalidated and can no longer produce events I am using RxBus which is an RxJava clone of Otto/EventBus to communicate between the different components of my android app. The app works fine on my Motorola Moto x 2013 running ICS, without crashes. But on a Nexus 5X, running Android M, it throws this exception:
Fatal Exception: java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:60)
   at android.os.Handler.handleCallback(Handler.java:808)
   at android.os.Handler.dispatchMessage(Handler.java:103)
   at android.os.Looper.loop(Looper.java:193)
   at android.app.ActivityThread.main(ActivityThread.java:5333)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
   at dalvik.system.NativeStart.main(NativeStart.java)
Caused by rx.exceptions.OnErrorNotImplementedException: [EventProducer public xyz.chanl.radio.events.Events$StageProgram xyz.chanl.radio.fragments.ProgramListFragment.stageProgram()] has been invalidated and can no longer produce events.
   at rx.Observable$27.onError(Observable.java:8139)
   at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:157)
   at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:120)
   at rx.internal.operators.OperatorSubscribeOn$1$1.onError(OperatorSubscribeOn.java:59)
   at rx.Observable.unsafeSubscribe(Observable.java:8321)
   at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
   at android.os.Handler.handleCallback(Handler.java:808)
   at android.os.Handler.dispatchMessage(Handler.java:103)
   at android.os.Looper.loop(Looper.java:193)
   at android.app.ActivityThread.main(ActivityThread.java:5333)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
   at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.IllegalStateException: [EventProducer public xyz.chanl.radio.events.Events$StageProgram xyz.chanl.radio.fragments.ProgramListFragment.stageProgram()] has been invalidated and can no longer produce events.
   at com.hwangjr.rxbus.entity.ProducerEvent.produceEvent(ProducerEvent.java:98)
   at com.hwangjr.rxbus.entity.ProducerEvent.access$000(ProducerEvent.java:17)
   at com.hwangjr.rxbus.entity.ProducerEvent$1.call(ProducerEvent.java:80)
   at com.hwangjr.rxbus.entity.ProducerEvent$1.call(ProducerEvent.java:76)
   at rx.Observable.unsafeSubscribe(Observable.java:8314)
   at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
   at android.os.Handler.handleCallback(Handler.java:808)
   at android.os.Handler.dispatchMessage(Handler.java:103)
   at android.os.Looper.loop(Looper.java:193)
   at android.app.ActivityThread.main(ActivityThread.java:5333)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
   at dalvik.system.NativeStart.main(NativeStart.java)

i have googled, but nobody seems to have had this issue before or i cant find an even remotely similar stacktrace.
How can i investigate this problem?
I register and unregister the bus in the onStart and onStop functions of the fragment.

A: So, I investigated and I realized this normally happens when you register multiple producers emitting the same event. So when the producer is registered with a particular event it invalidates the second one. I don't know if this design was intentional.


text:
Q: Arduinojson pass variables scope I am having trouble with the code below. I'm coding a ESP8266 wifi module so that it will register automatically to a MQTT server. To make it easy to configure I made a portal that you can access when you first connect the device. Here you can enter the API key and the IOT path name of your device. I want to load and store these configs from a json.config file. This works, expect I can't seem to pass the variables to the void setup scope. The code is stil filled with my last efforts.
Any pointers on how to fix this?
#include <ArduinoJson.h>
#include <ESP8266WebServer.h>
#include "FS.h"

ESP8266WebServer server ( 80 );

char* ssid;
char* password;
char* apikey;
char* iotpath;

void setup() {

    const char* values = loadConfig();
    Serial.println(values);

  // declare ssid and password
 //char* ssid = "xxxxxxx";
 //char* password = "xxxxxxxx";

  // start serial connection and SPIFFS
  Serial.begin (115200);
  SPIFFS.begin();

   Serial.println(ssid);
   Serial.println(password);
   Serial.println(apikey);
   Serial.println(iotpath);

  // WiFi connection sequence
  WiFi.begin ( ssid, password );
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 ); Serial.print ( "." );
  }

  // WiFi success print
  Serial.println ( "" );
  Serial.print ( "Connected to " ); Serial.println ( ssid );
  Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );

  // Check if SPIFSS is started
  if (!SPIFFS.begin())
  {
    Serial.println("SPIFFS Mount failed");
  } else {
    Serial.println("SPIFFS Mount succesfull");
  }

  // check if config file was loaded
  /*
   if (!loadConfig()) {
    Serial.println("Failed to load config");
  } else {
    Serial.println("Config loaded");
  }*/

  // Server root handling
  server.serveStatic("/img", SPIFFS, "/img");
  server.serveStatic("/", SPIFFS, "/index.html");
  server.serveStatic("/css", SPIFFS, "/css");

  server.begin();
  Serial.println ( "HTTP server started" );

}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
  delay(100);
  //Serial.println(".");
}

const char* loadConfig() {

  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    //return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    //return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  // We don't use String here because ArduinoJson library requires the input
  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  // use configFile.readString instead.
  configFile.readBytes(buf.get(), size);

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    //return false;
  }

  const char* ssid = json["ssid"];
  const char* password= json["password"];
  const char* apikey = json["apikey"];
  const char* iotpath = json["iotpath"];
  //String ssid_string = String(ssid);
  //return ssid;
}


text:
Q: Update app when server update android I created android app that connects with MySql in phpAdmin by Json code and the app works well with me. I want when the admin add a new row in the table that in server, the app knows that the new data added, meaning that I want the app updated with sever forever.
How to do this?
Thanks in advance.

A: Schedule a request to the server every once in a while or let have a REFRESH button in your app. For the request to the server use an AsyncTask and s
Inside onPostExecute update your UI.
Check the AyncTask docs here

A: Its better to use GCM (Google Cloud Messaging) for Android and Push Notifications when ever you update your Mysql data, so that your app can connect to your server and download refreshed data accordingly, Saves Battery and improves your app performance.
Tutorial Here: http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/


text:
Q: How to rollback only one branch from development when multiple branches have been merged on it My workflow:

*

*There is a master branch

*There is a dev branch

*New feature branches are created based off master as and when required. These feature branches are then merged with dev so we can test it on our development server. Feature branches never take pull of any other branch other than master so they are pure in that any of these can be individually merged with master at any time.

*If there is any conflict while merging any feature branch to dev, this is resolved on dev branch itself by switching to dev and then taking pull of that feature branch and resolving conflicts manually while on dev branch. So, no feature branch ever takes pull from dev branch to keep them pure.

*Feature branches are based off master because sometimes one or more of the multiple features may not be ready for that month's deployment while all others have been completed and approved. In such cases, we are supposed to roll back the dev branch last month's state and then merge in all the approved branches leaving off the incomplete branches.

Problem/question:
For this month's deployment, one of the 10 features is not ready and we need to pull this out from development so that all others can be tested once on development server without this incomplete branch and then can be merged with master.
First option I can think of is as mentioned above i.e. to rollback dev branch to an older state (say commit abcdef) where none of these feature branches was merged in it. Then I need to merge in all the approved branches only on dev. I can roll back to that old state using git checkout abcdef. But I think it goes to some hanging state after that. How will I be able to merge other branches in it like I would normally do on dev branch?
I also read somewhere about git revert command. Is it possible to resolve my issue using git revert?
Please note that the branch I need to pull out has to be merged in with dev again after this month's deployment.

A: As long as you specify the parent branch (i.e. the "clean" one), you can do this with git revert. Something like this:
git revert -m 1 <merge SHA>

What this will do is create a new commit that reverts the changes in the merge. If you then later want to undo this (for instance, if you want to re-merge the problem branch), just revert the reverted commit.


text:
Q: android progressbar on click of Home/Back button I have implemnted progressbar in my small game like below
    gameProgressBar =(ProgressBar)findViewById(R.id.GameProcess);

    thrd = new Thread(progressBarThread);
    thrd.start();

}

//Progress bar function
private Runnable progressBarThread = new Runnable(){

    public void run() {
        // TODO Auto-generated method stub
        while (GameProgressCount<60){  //60 = 1 minute
            try{
                myHandle.sendMessage(myHandle.obtainMessage());
                Thread.sleep(1000);

            }
            catch(Throwable t){
            }
        }
        thrd.stop();
    }

    Handler myHandle = new Handler(){

        @Override
        public void handleMessage(Message msg) {

                GameProgressCount++;
                gameProgressBar.setProgress(GameProgressCount);
        }
    };

My question is that when i click on back/home button of the device, app is getting minimized (or goes previous screen) but the Progress bar thread would be running in the background. is it possible to pause the thread and resume when i minimize/open the app screen.
Thanks

A: You can pause the Thread in the OnPause method of the Activity and you can resume the Thread on OnResume method of the Activity which is pretty stright forward. Now if you wanted to Keep the GameProgressCount intact and wanted to Resume back from where it has left then you can use SharedPreference to store the value, when you resume back use the same value to start with.


text:
Q: How can I name objects in R according to a for loop? I'd like to name objects in a loop depending on i. I've got datasets from 1996 to 2020, all called Natalidad i_p.csv where i is the year. Each of them have the variables ano and mes. I want to create a matrix for each year with those two variables and name each of them matrix_i (where i is the year). I've tried the next code with and without the assign function, but it isn't working.
for (i in 1996:2020) {
nacimientos <- read.csv(paste0("C:/Users/.../Natalidad ", i, "_p.csv"), header = TRUE, sep = ";")
assign(paste0("matrix", i), i) <- melt(table(nacimientos$ano, nacimientos$mes))
}

A: We can assign names to an object with names()[i]<-"name".
First, create an output object to be populated. Then populate it with your loop.
    output<-vector('list', length(1996:2020))
    for (i in as.character(1996:2020)) {
    nacimientos <- read.csv(paste0("C:/Users/.../Natalidad ", i, "_p.csv"), header = TRUE, sep = ";")
    output[i]<-melt(table(nacimientos$ano, nacimientos$mes))
    names(output)[i]<-paste0("matrix_", i)
    }

this will create a list of matrixes, in which every element is named "matrix_i"


text:
Q: maintain filetype when encrypting a file I have written an AES cipher in python to help me understand its implementation in software.
I am reading the file contents into a bytearray using:
with open(self.plaintext_file_path, 'rb') as f:
    self.plaintext_data = bytearray(f.read())

the plaintext_data then gets run through the cipher and outputs ciphertext_data.
It's then saved back to a file after the bytes have been encrypted using:
with open(fname, 'wb') as f:
    f.write(self.ciphertext_data)

the file extension (for example .jpg) is maintained in the filename that I am using to save the data though the resulting file will not open as an image. why?

A: If you'd like the image to be readable by an image program, you'll need to look up the specifications for JPEG or your image format of choice.
See this related question or google the JPEG file format & magic number specifications.
Once you have made the boilerplate data for the smallest possible JPEG file, then you can inject your encrypted data in the appropriate location in the file and write it back to the disk.
You may want to create a function to strip out the JPEG boilerplate from the original image file as well, so that you're only encrypting the actual image data and not encrypting the boilerplate bytes.


text:
Q: What does "would be in" mean in this sentence? I have been learning Python programming from a book and I came across a sentence which I can't understand!

When you enter this code in the IDLE, it will automatically
  indent, so be sure to press the backspace or delete key once you've
  typed each print statement, so that your if, elif, and else statements
  will start at the far-left margin. This is the same position
  the if statement would be in if the prompt (>>>) were absent.

I just don't get this part:

This is the same position the if statement would be in if the prompt (>>>) were absent.

What does "would be in" mean?

A: I text talks about a case like the following
if x:
   print("Hello")
else:
   print("Goodbye")

That's the correct way to format.
Wrong would be:
if x:
   print("Hello")
   else:
       print("Goodbye")

To prevent the wrong way from happening you have to hit the delete key after you wrote print("Hello") and pressed <Enter>.
What's with the prompt? If you are in IDLE the correct text will look like:
>>> if x:
        print("hello")
else:
        print("goodbye")

The sentence says that if would be at the same height as else if the >>> wouldn't be there. As far as python is concerned if and else are on the same level on indention.


text:
Q: I know views and controllers shouldn't share logic.. but how else can I do this? I have a controller called DesignersController, the index method lists them and the view method accepts the designer name as a parameter and retrieves it by name.
so /designers will list all the designers and /designers/view/designer-name will display that designer.
Now if a designer name has a space, it needs to be escaped in the URL. I have logic for escaping and unescaping the spaces:
private $space_escape_char = '-';

function escapeSpaces($str)
{
    return str_replace(" ",$this->space_escape_char,$str);
}

function unescapeSpaces($str)
{
    return str_replace($this->space_escape_char," ",$str);
}

Now the view method on the Controller needs access to this so when it's passed a name like "Foo-Bar" it can translate that into "Foo Bar".
The index.ctp view file also needs access to it, so when it lists all the designers it can give links to each one, and be able to escape each name:
<?php foreach ($designers as $designer): ?>

<div>
<?php
    echo $this->Html->link(
        $designer['Designer']['name'],
        array(
            'controller' => 'designers',
            'action' => 'view',
            escapeSpaces($designer['Designer']['name'])
        )
    );
?>
</div>

<?php endforeach; ?>

What is the best way to handle this without code duplication?

A: The usual way this is done is to put the primary ID of the entity in the URL and have the name/title (in your case designer name) in the URL for keywords/usability.
For example
/designers/view/13/designer-name/

The controller will only care about the 13, searching the database for the designer of ID 13. It wouldn't use designer-name at all.
This is the way it's done here on Stackoverflow.
It also prevents /designers/view/john-smith12/

A: If this is a common occurance, I would recommend storing a URL slug in the the users database entry.  Calculate it once, and re-use it from there. Why recalculate something that will be the same every time?

A: What you're doing here is converting the designers' names into slugs, but manually. What you can do instead is use a Behaviour (like this Sluggable Behavior) to store the slug of your designer's name automagically. Thereafter, you can refer to $designer['Designer']['slug'] wherever you want the URL-safe version of the name. This slug gets stored in the database as part of the model data, so you can even query against it.


text:
Q: Calling a Web Service from PHP How can i call a web service from php

A: Use the curl function:
http://php.net/manual/en/book.curl.php
Assuming you are using a GET request to connect to a RESTful API:
$url = "http://the-api-you-want/?the-args=your-args&another-arg=another-arg";
$ch = curl_init(); // start CURL
curl_setopt($ch, CURLOPT_URL, $url); // set your URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
$json = curl_exec($ch); // connect and get your JSON response
curl_close($ch);

You can then use PHP's json_decode on the response if that is what you want to do.
Another option would be using Drupal's drupal_http_request function http://api.drupal.org/api/function/drupal_http_request/6

A: I would reccommend you to be more specific in your Question. Wich Type of Web Service do you mean?
If you are using Rest Webservices, i can recommend Zend_Rest_Client, that comes with the Zend Framework. I think the Zend Framework also provides Stuff for SOAP Services.

A: Use curl or the Zend_Http_Client library from Zend Framework (You don't need the entire Zend Framework to use the library). If the service you are calling is sending a JSON response, then you'll have to parse it in PHP using json_decode.


text:
Q: $f_n(x) = [x_n + g (x)]^2$ is not uniformly convergent, for every $x\in X$. The statement is:
Let $(x_n)_{n\in\mathbb{N}}$ be a sequence of non-zero real numbers such that $x_n → 0$ when $n → + ∞$. Show
that if g: X → R is unlimited, then the sequence of functions $f_n$: X → R defined by
$$f_n(x) = [x_n + g (x)]^2$$
for every $x \in X$, it will not converge uniformly.
I am not sure that what I did is correct. Let's go:
As $f_n=x_n^2+2x_ng(x)+g(x)^2$, is that true that if one term of this sum is not uniformly convergent, then $f_n$ won't be? See:
$x_n$ is uniformly convergent due to the fact that $x_n  → 0$ when $n → + ∞$. And $g(x)$ is uniformly convergent due to the fact that for every $\varepsilon>0, \exists n_0\in\mathbb{N}$ such that
$$n>n_0\Rightarrow |g(x)^2-g(x)^2|=0<\varepsilon, \forall x\in X.$$
However, $x_ng(x)$ is not uniformly convergent (I will hide the procedure because it is a routine calculation, it just uses the fact that g is unlimited). So, $2x_ng(x)$ isn't uniformly convergent as well.
So, can I conclude that $f_n$ is not uniformly convergent based on the fact that one of the terms isn't uniformly convergent?

A: If $f_n$  were unif. conv, then $x_ng(x)=f_n(x)-x_n^2-g(x)^2$ would be unif conv, and you have checked it is not possible.

So, can I conclude that fn is not uniformly convergent based on the fact that one of the terms isn't uniformly convergent?

NO, BUT, you can conclude that it is not unif. conv, since one term is NOT unif conv and the other terms are.


text:
Q: JavaScript - Checkbox acting like Radio Buttons I am making a JavaScript and HTML project where customers can click a check box for the services they would like done and it will add up the cost for each service on the right hand side.
I am currently using check boxes for each item and need them to act like radio buttons. In the screenshot I included customers cannot have the CQuartz Finest package and the Ceramic Pro Gold Package on their car at the same time.
I can get the check boxes to "uncheck" after it realizes the other one is currently checked but it will not subtract it's self from the total.
If you could steer me in the right direction that would be awesome! I typically code in HTML5, CSS3, Java and C++. I have not done a whole lot in JavaScript yet.
I have the screenshot posted here: https://www.dropbox.com/s/xlkh4vp70sa39wb/what-we-recommend.jpg?dl=0
Here is the code that I am currently using below:
HTML

<input id ="ceramicProGoldBox" type="checkbox" name="vehicle" onclick="validateCeramicProGold()" class="paintCoatings">
Ceramic Pro Gold

$1695.00

• 4 layers of 9H Glass Shield on all painted exterior surfaces

• 1 layer of 9H Glass Shield on exterior plastics

• 1 layer of Ceramic Pro Wheel and Caliper Coating on wheels and calipers

• 1 layer of Rain on all windows and glass

• Includes 2 stages of Paint Correction

<input id ="cquartzFinestBox" type="checkbox" name="vehicle" onclick="validateCquartzFinest()" class="paintCoatings">
CQuartz Finest

$700.00

• 2 Layers of CQuartz Finest on all painted exterior surfaces

• 2 Layers of CQuartz Finest on exterior plastics

• 2 Layers of CQuartz Finest on Wheels & Calipers

• 2 Layers of Car Pro Fly By is applied to exterior glass surfaces

• Includes a Single Stage Paint Correction

JavaScript

A: Since you already make use of JQuery, you can make it yourself a lot easier. Use the data attributes to add the relevant group information to the checkboxes, and use one change event on all check boxes that match a certain selection (in this case, I took all check boxes that have the paintCoatings class).
When the change of the check box occurs, the event will uncheck all previously selected checkboxes for this group and will compare an internal state to update the totalprice (and potential options)
I added some comments to the code to make it clear what is happening

'use strict';
var totalPrice = 0;

function updatePrice(totalPrice) {
  $('#totalPrice').html('$' + totalPrice.toFixed(2));
}

function addOption(checkboxItem) {
  var s = $(checkboxItem).data('group');
  $('#options').append('
' + $(checkboxItem).data('option') + '
');
}

function removeOption(checkboxItem) {
  var s = $(checkboxItem).data('group');
  $('#' + s).remove();
}

function addPrice(checkboxItem) {
  totalPrice += parseInt($(checkboxItem).data('price'));
}

function removePrice(checkboxItem) {
  totalPrice -= parseInt($(checkboxItem).data('price'));
}

var lastChecked = {};
$('input.paintCoatings').on('change', function(eventSource) {
  // target points to the checkbox that got clicked
  var sender = eventSource.target;
  if (sender) {
    // we have the relevant group of data inside data-group
    var group = $(sender).data('group');
    // select all matching checkboxes of this group
    $("[data-group='" + group + "']").each(function(index, checkbox) {
      if (checkbox !== sender) {
        // and deselect them if they are not the same to this sender
        checkbox.checked = false;
      }
    });
    // if this group had a previously selected checkbox
    if (lastChecked[group]) {
      // remove the price from the total price
      removePrice(lastChecked[group]);
      // remove the option from the option list
      removeOption(lastChecked[group]);
      // remove last selected item
      delete lastChecked[group];
    }
    // if the freshly clicked checkbox is checked
    if (sender.checked) {
      // add the price
      addPrice(sender);
      // add the option
      addOption(sender);
      // save it as the currently active one for this group
      lastChecked[group] = sender;
    }
    // update the price
    updatePrice(totalPrice);
  }
});
.option {
  display: inline-block;
  float: left;
  margin: 4px;
  border: solid #a0a0a0 1px;
  width: 150px;
  padding: 5px;
}
.option h2 {
  font-size: 11px;
  font-weight: bold;
}

0

  <input id="ceramicProGoldBox" type="checkbox" data-group="paint" data-price="1695" data-option="Ceramic" name="vehicle" class="paintCoatings">

Ceramic Pro Gold

$1695.00

  <input id="cquartzFinestBox" type="checkbox" data-group="paint" data-price="700" data-option="Quartz" name="vehicle" class="paintCoatings">

CQuartz Finest

$700.00

  <input id="ceramicProGoldBox" type="checkbox" data-group="wheels" data-price="150" data-option="19 inch wheels" name="vehicle" class="paintCoatings">

19"

$150.00

  <input id="cquartzFinestBox" type="checkbox" data-group="wheels" data-price="100" data-option="18 inch wheels" name="vehicle" class="paintCoatings">

18"

$100.00


text:
Q: Why map doesn't work on new Array in js Why does the code bellow returns an array of undefined values and I don't see any logs?
var arr = new Array(10);
arr = arr.map(function () {
    console.log('kapa');
    return 1;
});
console.log(arr);

A: You can use Array.apply
Array.apply(null, {length: 10}).map(function(){return 1})

A: Both the ECMAScript specification and the slightly more readable MDN description of .map() spell it out fairly clearly.  The .map() callback is not called for empty values of the array (e.g. values that are undefined).
From the MDN description for .map():

map calls a provided callback function once for each element in an
  array, in order, and constructs a new array from the results. callback
  is invoked only for indexes of the array which have assigned values;
  it is not invoked for indexes that are undefined, those which have
  been deleted or which have never been assigned values.

So, since var arr = new Array(10); creates an array with ten empty slots in it, there are no values in the array that .map() will call its callback for.
If you actually put values in the initial array, then you will see the desired result:
var arr = [0,1,2,3,4,5,6,7,8,9];
arr = arr.map(function() {
    return 1;
});
console.log(arr);    // [1,1,1,1,1,1,1,1,1,1]

Working demo: http://jsfiddle.net/jfriend00/9c0hmL2j/

For some further documentation on .map(), you can see the ECMAScript specification for Array.prototype.map.  Steps 8b and 8c in that section of the spec describe how the callback to .map() will not be called if a given array property has no value.

A: The map() method creates a new array with the results of calling a provided function on every element in this array.
You don't have elements if you call new Array[10]
You must do something like
var temp = [];
for(var i=0;i<10;i++){
    temp[i]=i;
}

Or in your case
var temp = new Array();
for(var i=0;i<10;i++){
    temp.push(i);
}


text:
Q: Bad access on NULL termination of the string -(void)myStartMethod{
    NSString *str = @"testing";
    char *charStr = [str UTF8String];
    charStr[4] = '\0'; // bad access on this line.
    NSLog(@"%s",charStr);
}

I am trying to terminate the string on fourth char and print the output as "test".
What am I missed?
Since C programing can be as it is used with Objective-c(foundation framework), then why it is throwing bad access. This type of char array modification is totally valid in C (GCC).
How can i avoid it and reason behind it.
Thanks in advance.

A: The documentation states provides a pretty good hint:

UTF8String
Returns a null-terminated UTF8 representation of the receiver.
- (const char *)UTF8String

So, clearly you're in error for modifying this. In fact, you should have gotten a warning for converting const char * to plain char *.
Also, the name of the '\0' character is not NULL, that's used for pointers.

A: As apple headers [str UTF8String] returns a const char* which can't be modified.

A: As the other answers have mentioned, you cannot modify the UTF-8 string returned from an NSString instance.
Instead use this code:
-(void)myStartMethod{
    NSString *str = @"testing";
    NSString *part = [str substringWithRange:NSMakeRange(0, 4)];
    char *charStr = [part UTF8String];
    NSLog(@"%s",charStr);
}

or:
-(void)myStartMethod{
    NSString *str = @"testing";
    NSString *part = [str substringWithRange:NSMakeRange(0, 4)];
    NSLog(@"%@", part);
}


text:
Q: Iteratively apply a function to an array I want to create an array that contains g^0, g^1, g^2.... up to g^100 but all to mod50 (apologies if anyone knows how to format this so the powers are properly aligned I need a bit of help!)
In my case g = 23, so I would want an array that looks like:
[1,23,29,17...]

I've included all my (incorrect) code at the bottom for ease of understanding. I have created an empty array with 201 items. I then tried to create a loop which takes i=0 initially and then as we move through each element of the array puts the new value of i as the power of x. I don't know whether it's just the code I have made an error with or I need to approach this with a different logic, but regardless any help would be appreciated!
n = 101
array = [0] * n
g = 23
i = 0

for i in array:
    if i<100:
        x = g**i
        print(x%50)
        i = i + 1

array

This is the output I am getting from this code:
[1,1,1,1,1...]

This initial question has been answered below
I was wondering if the same logic can be applied when instead of g^i as the required outputs, it would be h(g^(-in)) with h = 20, n = 18 and g = 23 as before. I have tried this and am getting incorrect values in my array, code I tried:
h = 20
n = 18
g = 23
array2 = [h*(g**((-i)*n))%500 for i in range(100+1)]

A: IIUC, you can use a list comprehension:
g = 23
out = [g**i%50 for i in range(100+1)]

output:
[1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1]

Or maybe better, using numpy:
import numpy as np
a = 23**np.arange(100+1)%50

output:
array([ 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 43, 33, 49,
       17, 13, 29, 47, 15, 41, 15, 19, 13, 21,  9, 39,  9, 25, 25,  9,  1,
        1, 29,  1, 27, 25,  9, 17, 39, 13, 39, 47, 33, 11, 39, 43, 33, 21,
        5, 31, 29, 19,  9, 25, 43,  5, 21, 13, 33, 49, 43,  9, 29, 29, 49,
       33, 15, 21, 11,  3, 37,  7,  7, 41, 27, 31, 33, 37, 39, 45, 17, 45,
       29, 19, 43, 23, 13, 49, 17,  7, 43, 19, 33, 29, 35, 15, 35,  9])

why your code failed
You are not doing anything with your array, just using it as a generator of 0s. So the condition i < 100 is always True and x is always 1. Your i = i+1 is overwritten by 0 at each loop.


text:
Q: Need help with executing and deleting remote bash script via a local bash script I am trying to create a bash script that will scp a script to a remote server, ssh (using an ssh key that is already installed) to the remote server, execute the uploaded script, and then delete the remote script when it is finished.  I'm not clear how to run an ssh session inside a bash script.  Here are the commands I use to do it from the command line:
scp my_script.sh user@www.remotesite.com:/usr/home/user/
ssh user@www.remotesite.com
>sh my_script.sh
>rm myscript.sh
>exit

How do I script the ssh portion of my command list?  Thanks!

A: ssh will execute commands passed as arguments on the remote machine. The following should do what you want:
ssh user@www.remotesite.com 'sh my_script.sh; rm my_script.sh'

A: You could also skip the file copy and delete and do something like this.
cat my_script.sh | ssh user@host bash

A: You could also investigate the use of Fabric, a Python library for systems admin over SSH:
http://docs.fabfile.org/0.9.1/
It's super-simple to get started with but very powerful, especially across multiple servers.


text:
Q: Firebase Analytics screen view event not loging screen name every time I've setup a fonction to log screen envents from my android app.
FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(activity);

Bundle bundle = new Bundle();

if (screenName.length() > 36) {
   bundle.putString(FirebaseAnalytics.Param.SCREEN_NAME, screenName.substring(0, 36));
} else {
   bundle.putString(FirebaseAnalytics.Param.SCREEN_NAME, screenName);
}

bundle.putString(FirebaseAnalytics.Param.SCREEN_CLASS, activity.getClass().getSimpleName());
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, bundle);

However, depending on the class loging the event, the screen name is not event part of the event sent to Google.
Here's the event loged when working :
Logging event: origin=app,name=screen_view(_vs),params=Bundle[{ga_event_origin(_o)=app, engagement_time_msec(_et)=15735, ga_previous_class(_pc)=SlideMenu, ga_previous_id(_pi)=1601424672890182561, ga_screen_class(_sc)=SlideMenu, ga_screen_id(_si)=1601424672890182562, ga_screen(_sn)=Recommandations}]
And when not working :
Logging event: origin=auto,name=screen_view(_vs),params=Bundle[{ga_event_origin(_o)=auto, ga_previous_class(_pc)=SlideMenu, ga_previous_id(_pi)=1601424672890182562, ga_previous_screen(_pn)=Recommandations, ga_screen_class(_sc)=AffichageContent, ga_screen_id(_si)=1601424672890182563}]
As you can see in the 2d line, the ga_screen(_sn) field is missing.
From what I've seen, it seems that the only class not loging the screen name is AffichageContent but I don't know if it's from the class itself or because this activity is started by a previous one.
I've loged the bundle.getString(FirebaseAnalytics.Param.SCREEN_NAME) and it's value before loging the event is the right one.
Thank's !


text:
Q: How send data from js to flask i have issue to send data in flask from js. I try use ajax.

AJAX code
      $.ajax({
        type: "GET",
        contentType: "application/json;charset=utf-8",
        url: "/getmethod/data",
        traditional: "true",
        data: JSON.stringify({data}),
        dataType: "json"
        });

Python code
def get_javascript_data(data):

    content = request.get_data('data')
    jsonify(content)

If u got some tips or tricks please tell me.

A: new_item = $('#input').val() //value I want to send
$.ajax({
    url: '/set_value',
    type: 'POST',
    data: new_item,
    success: function(response){
        $('#main').text(response)
    }
})

in flask:
new_item = request.get_data()


text:
Q: Google maps API - Displaying routes/polylines, kmlLayer alternative I am developing a web application where i have database backend with geo located objects, and each one has it's geo data stored in a kml file. When displaying object on a google map, via google maps js api v3, i have a following scenario:
first i do a json call, and it returns array of objects. Each json    object is has it's geo location, either a gmap marker or    route/polyline. Every object has properties: id, name, description,    kml_url… etc. Kml_url is url of the kml file, that is used to plot an    object on a map, through the "new google.maps.KmlLayer(…)" call.    Every created kmlLayer is bound to its json object, so it can be    manipulated (show/hide, for example) through that object by js. Then,    every kmlLayer get it's mouse click event listener with    "google.maps.event.addListener(…)", and the response is dynamically    generated from the kml's json object attributes (it grabs the id    attribute and through another json call it displays object's    details).
The problem is, when more than let's say 10 kml layers are created, i hit the "NetworkError: 414 Request-URI Too Large". I found that i can get rid of the error by using kml network links, but AFAIK, in this case i loose the ability to manipulate every object through it's json object (with bounded kmlLayer that is created).
What would be the alternative for this sort of application, maybe not using kml-s at all ?
If i go for using overlays, and drawing all the routes and markers myself, i am afraid i will end up with scalability issues, because drawing 15 routes, every with 50 polyline nodes, and another 15 markers, would take considerable amount of time on a client.
Thank you,
Emil

A: I've had great success with GeoXML3 for handling large numbers of KML files, each with many elements (including placemarks, polylines, and polygons).  I recommend you get the polys branch, which as of this post has the most features.  There's a current big effort going on in the KMZ branch that will handle KMZ (zipped) files, but this is not quite ready for production, in my opinion.
For my own edificaiton, I created a Github project which uses the Google API v3, Geoxml3, and displays a sidebar and layer controls.  It also uses some more advanced features like the afterParse hook and an addition I use that triggers a parsed event on the Geoxml3 object.


text:
Q: Reading a parameter through command prompt (starts with "-") I am facing a problem while reading input from command prompt in shell script. My script's name is status.ksh, and I have to take parameter from command prompt. This script accepts 2 parameter. 1st is "-e" and second is "server_name".
When I am running the script like this,
status.ksh -e server_name
echo $@

is giving output "server_name" only, where as expected output should be "-e server_name"
and echo $1    is giving output as NULL, where as expected output should be "-e".
Please guide me, how to read get the 1st parameter, which is "-e" .
Thanks & Regards

A: The problem was caused by -e. This is a flag for echo.
   -e     enable interpretation of backslash escapes

Most of the unix commands allow -- to be used to separate flags and the rest of the arguments, but echo doesn't support this, so you need another command:
printf "%s\n" "$1"

If you need complex command line argument parsing, definitely go with getopts as Joe suggested.

A: Have you read this reference? http://www.lehman.cuny.edu/cgi-bin/man-cgi?getopts+1
You shouldn't use $1, $2, $@, etc to parse options. There are builtins that can handle this for you.
 Example 2 Processing Arguments for a Command with Options

 The following fragment of  a  shell  program  processes  the
 arguments  for a command that can take the options -a or -b.
 It also processes the option -o, which requires  an  option-
 argument:

   while getopts abo: c
   do
         case $c in
        a | b)   FLAG=$c;;
        o)       OARG=$OPTARG;;
        \?)      echo $USAGE
           exit 2;;
        esac
   done
   shift `expr $OPTIND - 1`

More examples:
http://linux-training.be/files/books/html/fun/ch21s05.html
http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.cmds/doc/aixcmds2/getopts.htm
http://www.livefirelabs.com/unix_tip_trick_shell_script/may_2003/05262003.htm


text:
Q: Contact Groups in Google People API does not work as advertised & documented Folks, I'm not sure if you are aware about this but people.contactGroups.get endpoint does not work at all. Even in API Explorer...
Here is an example of me querying people.contactGroups.list for the list of groups:

Now, lets flip the tables and switch to people.contactGroups.get endpoint call using the resourceName from the response below:

eek... what's the heck... you need it in format contactGroups/xyz? already, take that:

oops, that didn't work either...
Fine, move on and switch to people.contactGroups.members.modify endpoint and try modify our contact group there:

heck, heck... okay, here is your contactGroups/xyz format you're craving about:

It turns out these endpoints are exhibiting behavior neither consistent with the documentation nor with the internal implementation.
However, that somehow works gracefully in Google Contacts... Are you folks consuming for that some sort of internal APIs?
Is there anything wrong with what I'm doing or is it a bug in the APIs?

*

*UPD: It turns out only people.contactGroups.batchGet endpoint works as advertised and documented. All other people.contactGroups.* endpoints are prone to the very same issue.

A: There was a bug with the configuration of the resource name. This has now been resolved, sorry about any inconvenience.


text:
Q: Crash when calling getter method in Swift I'm doing the Stanford iOS course on iTunes U and i'm getting strange behavior when calling a getter method
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var display: UILabel!
    var newNumber = true
    var operandStack = Array<Double>()
    var displayValue: Double{
        get{
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set{
            display.text = "\(newNumber)"
            newNumber = true
        }
    }

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        if(newNumber){
            display.text = digit
            newNumber = false
        }else{
            display.text = display.text! + digit
        }
    }

    @IBAction func enter() {
        if(!newNumber){
            newNumber = true
        }
        operandStack.append(displayValue)
        println("\(operandStack)")
    }

}

When the enter() method is called I get a crash with a breakpoint pointing towards the return statement in the displayValue get method. If I ignore the get method and call
operandStack.append(NSNumberFormatter().numberFromString(display.text!)!.doubleValue)

Everything works fine but I don't understand why the get method crashes, isn't it doing the exact same thing as the code above would?
This is the full backtrace
* thread #1: tid = 0x133463, 0x000e4738 Kalkylator`Kalkylator.ViewController.displayValue.getter : Swift.Double(self=0x7986d560) + 24 at ViewController.swift:17, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x000e4738 Kalkylator`Kalkylator.ViewController.displayValue.getter : Swift.Double(self=0x7986d560) + 24 at ViewController.swift:17
    frame #1: 0x000e57c2 Kalkylator`Kalkylator.ViewController.enter (self=0x7986d560)() -> () + 130 at ViewController.swift:39
    frame #2: 0x000e5992 Kalkylator`@objc Kalkylator.ViewController.enter (Kalkylator.ViewController)() -> () + 34 at ViewController.swift:0
    frame #3: 0x01d0c7cd libobjc.A.dylib`-[NSObject performSelector:withObject:withObject:] + 84
    frame #4: 0x00b1aa90 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 99
    frame #5: 0x00b1aa22 UIKit`-[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64
    frame #6: 0x00c5b18a UIKit`-[UIControl sendAction:to:forEvent:] + 69
    frame #7: 0x00c5b5a7 UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 598
    frame #8: 0x00c5a811 UIKit`-[UIControl touchesEnded:withEvent:] + 660
    frame #9: 0x00b72cfa UIKit`-[UIWindow _sendTouchesForEvent:] + 874
    frame #10: 0x00b737d6 UIKit`-[UIWindow sendEvent:] + 792
    frame #11: 0x00b316d1 UIKit`-[UIApplication sendEvent:] + 242
    frame #12: 0x00b41b08 UIKit`_UIApplicationHandleEventFromQueueEvent + 21484
    frame #13: 0x00b15337 UIKit`_UIApplicationHandleEventQueue + 2300
    frame #14: 0x0021706f CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    frame #15: 0x0020cb7d CoreFoundation`__CFRunLoopDoSources0 + 253
    frame #16: 0x0020c0d8 CoreFoundation`__CFRunLoopRun + 952
    frame #17: 0x0020ba5b CoreFoundation`CFRunLoopRunSpecific + 443
    frame #18: 0x0020b88b CoreFoundation`CFRunLoopRunInMode + 123
    frame #19: 0x03fa32c9 GraphicsServices`GSEventRunModal + 192
    frame #20: 0x03fa3106 GraphicsServices`GSEventRun + 104
    frame #21: 0x00b19106 UIKit`UIApplicationMain + 1526
    frame #22: 0x000eec64 Kalkylator`main + 180 at AppDelegate.swift:12
    frame #23: 0x02407ac9 libdyld.dylib`start + 1

A: var newNumber = true

That's a boolean.
display.text = "\(newNumber)"

You're setting the text of your label to the value of that boolean
NSNumberFormatter().numberFromString(display.text

You're creating a number from a boolean - not an NSNumber - here.
You probably mean "newValue".

A: here is the modified working code:
the line at which you are getting crash has been replaced.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    var newNumber = true
    var operandStack = Array<Double>()
    var displayValue: Double {
        get{
            return (display.text! as NSString).doubleValue // Changed Line
        }
        set{
            display.text = "\(newNumber)"
            newNumber = true
        }
    }

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        if(newNumber){
            display.text = digit
            newNumber = false
        }else{
            display.text = display.text! + digit
        }
    }

    @IBAction func enter() {
        if(!newNumber){
            newNumber = true
        }
        operandStack.append(displayValue)
        println("\(operandStack)")
    }

}

A: Turns out i just accidentaly placed a breakpoint without knowing what it was. Removing it of course solved the problem


text:
Q: Is it possible to create relational metabox values in a custom post? I have a custom post type ('Model') for a sports modelling agency, and it requires the model to enter sports they are competent at, and also rank their ability from 1 to 5. For example, given the information:
Model: Joe Soap.
Football: 4.
Archery: 2
I would store this in the custom_post_type 'model' with the fields:
Model Name: Joe Soap.
 Sports: Football, Archery (taxonomy).
 Rank: 4, 2.

How do I associate 4 with Football and 2 with Archery using a metabox, where different models may have different sports in their lists ?

A: Your question is focusing on the wrong thing. A metabox is just one way for a user to introduce some data. The more important question is how you should store that data in the database.
You could make 'sport' a custom post type and connect it to models using the Posts 2 Posts plugin. Then, for each connection, you can associate a 'rank' custom field:
https://github.com/scribu/wp-posts-to-posts/wiki/Connection-information
The plugin takes care of creating a metabox and of storing the values in an efficient manner.

A: add_meta_box() documentation in Codex has example of metabox creation and links to related tutorials.

A: This tutorial on adding custom meta boxes is also really good: http://webdesignfan.com/custom-write-panels-in-wordpress/
It's all very flexible; you should be able to reuse the code you create.


text:
Q: C Macro function argument in multiple lines When a macro function is defined as shown in the if block it throws me the error.
Where as the the macro function defined in the else block works fine.
Please tell me if there is a way where I could make the macro in the if block work as expected.
#if 1

#define FREE            \
        (               \
            ptr         \
        )               \
        {               \
            free(ptr);  \
            ptr = NULL; \
        }

#else

#define FREE(ptr)                   \
        {                           \
            free(ptr);              \
            ptr = NULL;             \
        }

#endif

int main(void)
{

    FREE(p);

    return (0);
}


text:
Q: Keep data from services in ionic2 I want to keep the data from services in ionic2. Now each time data is loading from the API's i dont want to call each time user go to the view.
public getUpcomingShoots(){

        var json = JSON.stringify({ });
        var headers = new Headers();
        headers.append("Accept", 'application/json');
        headers.append('Content-Type', 'application/json' );
        let options = new RequestOptions({ headers: headers });

        return this.http.post(url, json, options)
        .map(data => data.json());

  }

and my function is :
getUpcomingShoots (){
    this.showLoading();
    this.mainService.getUpcomingShoots().subscribe(success => {

      if(success.status == 1){
        this.loading.dismiss();
        console.log(success);

        if(success.data.length == 0 ){
          this.noUpcomingEvents = true;
        }else{
          this.noUpcomingEvents = false;
        }

        this.upcomingEvents = success.data;

      }else{
        this.loading.dismiss();
        console.log(success);

      }
    },
    error => {
      console.log( error);
    });
  }

A: It depends on what you want. Now the data is fetched every time the user is opening the view.
The best way of solving that would probably be to move the call into the ionViewDidLoad lifecycle event. From the docs:
ionViewDidLoad: Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewDidLoad event is good place to put your setup code for the page.
class MyPage {
  ionViewDidLoad() {
    // Add your API call here
  }
}

You can read more about it here: https://ionicframework.com/docs/v2/api/navigation/NavController/
You might still want to add some sort of caching to your service that will return the cached values for some time unless you explicitly force a refresh.


text:
Q: Itext and PngImage I have a java application which usesitext for generating reports.
I have to include a logo which is in a resolution of 150dpi.
The code I uwrote is the following:
final float logoWidth = 368;
final float logoHeigth = 182;
float x = PageSize.A4.getWidth() - (16 * millimeters) - logoWidth;
float y = PageSize.A4.getHeight() - logoHeigth;

final InputStream idLogo = getClass().getResourceAsStream("/logos/ID_Module_150dpi_layoutgroesse.png");

Image logoTop = PngImage.getImage(idLogo);
logoTop.setAbsolutePosition(x, y);

The problem is that the logo is added at the right position but the size is not correct. It is twice the height and twice the width. What am I doing wrong here?
Thanks in advance!

A: Have you tried scaleToFit()
Image logoTop = PngImage.getImage(idLogo);
logoTop.scaleToFit(x, y);

And then positioning it, personally I use scaleToFit() combined with tables in iText to position


text:
Q: FireBase getAuth and onAuthStateChanged is not in "firebase/auth" import I am trying to learn and use getAuth(), onAuthStateChanged() methods from "firebase/auth"
But in the folder of node_modules/firebase/auth doesnt include those methods.
It seems like changing dirs depending on versions of firebase.
My Dependencies:
"dependencies": {
    "antd": "^4.16.13",
    "firebase": "^9.0.2",
    "next": "11.1.2",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },

By the firebase doc it sais that i should use import { getAuth, onAuthStateChanged } from "firebase/auth";
I searched and found that "firebase/firebase-auth"; folder has included getAuth method but when i try to use import {getAuth} from "firebase/firebase-auth"; it gives me an error states firebase/firebase-auth file is not exported.
What did I miss?
How i can use getAuth and onAuthStateChanged methods with this dependencies?
thank you for advices
Firebase.js:
// import "firebase/auth"
import "firebase/compat/auth"
//import {getAuth} from "firebase/firebase-auth";
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

import { getAuth, onAuthStateChanged } from "firebase/auth";

// onAuthStateChanged(auth, user => {
//     // Check for user status
// });

const app = firebase.initializeApp({
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGIN_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID
})

export const auth = getAuth(app);

export default app

A: import React, { useState } from 'react'
import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged, GoogleAuthProvider, signInWithPopup, signOut } from "firebase/auth";
import './App.css';

// import { getAnalytics } from "firebase/analytics";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

const firebaseConfig = {
  apiKey:
  authDomain:
  databaseURL:
  projectId:
  storageBucket:
  messagingSenderId:
  appId:
};

initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
const firebaseApp = initializeApp(firebaseConfig);
const provider = new GoogleAuthProvider();
const auth = getAuth(firebaseApp);

export default function App() {
  const [user, setUser] = useState(null)
  onAuthStateChanged(auth, (user) => {
          if (user) {
            // User is signed in, see docs for a list of available properties
            // https://firebase.google.com/docs/reference/js/firebase.User
            setUser(user);
            // ...
          } else {
            // User is signed out
            // ...
            setUser(null)
            }
          }
        );

  return <>{user ?
  <>
Welcome
<button onClick={() => signOut(auth)}>Google Logout</button></>
  : <>
Enjoy

  <button onClick={() =>  signInWithPopup(auth, provider)
                  .then((result) => {
                    // The signed-in user info.
                    // eslint-disable-next-line
                    const user = result.user;
                    // ...
                  }).catch((error) => {
                    // Handle Errors here.
                    // eslint-disable-next-line
                    const errorCode = error.code;
                    // eslint-disable-next-line
                    const errorMessage = error.message;
                    // The email of the user's account used.
                    // eslint-disable-next-line
                    const email = error.email;
                    // The AuthCredential type that was used.
                    // eslint-disable-next-line
                    const credential = GoogleAuthProvider.credentialFromError(error);
                    // ...
                  })}>
                      Sign in with Google
                    </button>
  </>}</>
}


text:
Q: Power Query - get values from other column and remove responding values I am looking for a way retrieve the following in power query:

Look into column A for values = 0 get the responding number C and
remove all responding numbers from the column C
It would be great if someone could give an advise how to achive this.
Thanks!

A: Filter column A equal to zero using the drop down arrow atop column A
Merge the results back onto the original data set (requires a second table, or in example below, manual adjustment to code using home ... advance editor... )
Expand merged column C; will show data next to any row where A=0 for same C
Add custom column to remove any data in C where original C = merged C
=  if [C]=[C.1] then null else [C]

Remove extra columns
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Filtered Rows" = Table.SelectRows(Source, each ([A] = 0)),
#"Merged Queries" = Table.NestedJoin(Source,{"C"},#"Filtered Rows",{"C"},"Table2",JoinKind.LeftOuter),
#"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2", {"C"}, {"C.1"}),
#"Added Custom" = Table.AddColumn(#"Expanded Table2", "New.C", each if [C]=[C.1] then null else [C]),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"C", "C.1"})
in #"Removed Columns"

A: I solved this by

*

*creating a new query and and in this created an "exclude" list, by copying the content from advanced editor to the exclude list

*filtering the Null values

*merging as new query "left anti join"

*and all the Null values and responding numbers are gone.

@Horseyride Thanks again for the hint