text:
Q: Warnings When Attempting to Install Sysinternals With Powershell I am trying to install the sysinternals package with powershell, but is instead greeted with tons of warnings. It should be noted that I am following a set of instructions and don't know a lot about this subject yet. Here are the warnings when attempting to run the install-package command:
Install-Package sysinternals

WARNING: NuGet: System.InvalidOperationException: Unable to find version '1.3.5.1' of package 'chocolatey-core.extension'.
WARNING: NuGet:    at NuGet.PackageRepositoryHelper.ResolvePackage(IPackageRepository sourceRepository, IPackageRepository
localRepository, IPackageConstraintProvider constraintProvider, String packageId, SemanticVersion version, Boolean
allowPrereleaseVersions)
WARNING: NuGet:    at NuGet.PackageManager.InstallPackage(String packageId, SemanticVersion version, Boolean ignoreDependencies,
Boolean allowPrereleaseVersions)
WARNING: NuGet:    at NuGet.Commands.InstallCommand.InstallPackage(IFileSystem fileSystem, String packageId, SemanticVersion version)
WARNING: NuGet:    at NuGet.Program.Main(String[] args)
WARNING: NuGet: System.InvalidOperationException: Unable to find version '2019.12.19' of package 'sysinternals'.

As for what I've done before this, I've only installed the Chocolatey package provider and updated windows, but maybe I did something wrong? Here are the steps leading up to this:
Set-ExecutionPolicy RemoteSigned
Install-PackageProvider Chocolatey

Install-Module -Name PSWindowsUpdate
Get-WUInstall -Verbose
Get-WUInstall -Install

Any help is much appreciated.

A: Though you can use Chocolatey and NuGet, PowerShell's package manager is PowerShellGet (well, that uses NuGet by design). So, Choco is not really needed, yet, many still install and use it for the other sources.
If you use PowerShellGet directly, you'll see the same errors.
Find-Module -Name 'SysInternals' -AllVersions |
Format-Table -AutoSize
<#
# Results
PackageManagement\Find-Package : No match was found for the specified search criteria and module name 'SysInternals'. Try Get-PSRepository to see all available registered module
repositories.
At C:\Users\Daniel\Documents\WindowsPowerShell\Modules\PowerShellGet\2.2.3\PSModule.psm1:8873 char:9
+         PackageManagement\Find-Package @PSBoundParameters | Microsoft ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...ets.FindPackage:FindPackage) [Find-Package], Exception
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.FindPackage

#>

Find-Package -Name 'SysInternals' -AllVersions |
Format-Table -AutoSize
<#
# Results

Find-Package : No match was found for the specified search criteria and package name 'SysInternals'. Try Get-PackageSource to see all available registered package sources.
At line:1 char:1
+ Find-Package -Name 'SysInternals' -AllVersions |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...ets.FindPackage:FindPackage) [Find-Package], Exception
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.FindPackage
#>

Yet, if you do a wildcard search...
Find-Module -Name '*Internals*' |
Format-Table -AutoSize
<#
# Results

Version Name          Repository Description
------- ----          ---------- -----------
1.0.34  PoshInternals PSGallery  Collection of system internals tools for PowerShell.
4.3     DSInternals   PSGallery  The DSInternals PowerShell Module exposes several internal features of Active Directory and Azure Active Directory. These include FIDO2 and NGC key aud...
0.2.8   AADInternals  PSGallery  The AADInternals PowerShell Module utilises several internal features of Azure Active Directory, Office 365, and related admin tools. DISCLAIMER: Funct...
0.1     LCMInternals  PSGallery  Demo scripts explaining the internals of LCM
#>

Find-Package -Name '*Internals*' |
Format-Table -AutoSize
<#
# Results

Name                                    Version Source    Summary
----                                    ------- ------    -------
PoshInternals                           1.0.34  PSGallery Collection of system internals tools for PowerShell.
DSInternals                             4.3     PSGallery The DSInternals PowerShell Module exposes several internal features of Active Directory and Azure Active Directory. These incl...
AADInternals                            0.2.8   PSGallery The AADInternals PowerShell Module utilises several internal features of Azure Active Directory, Office 365, and related admin...
LCMInternals                            0.1     PSGallery Demo scripts explaining the internals of LCM
SilverlightToolkit-Internals-Unofficial 1.0.0   nuget.org The missing part of Microsoft Silverlight Toolkit. The internals DLL. 'System.Windows.Controls.Toolkit.Internals'
AppInternals.Agent.Cloud.Support        10.10.0 nuget.org Configure an Azure Cloud Service solution for AppInternals application performance monitoring.
InternalsVisibleTo.MSBuild              1.0.3   nuget.org Enables declaring 'InternalsVisibleTo' items in a .NET project file, rather than declaring them to an AssemblyInfo.cs file.
Akrual.DDD.Utils.Internals              1.0.8   nuget.org Useful Classes yo use everywhere
Meziantou.MSBuild.InternalsVisibleTo    1.0.1   nuget.org Allow to declare 'InternalsVisibleTo' in the csproj file, rather than declaring them to an AssemblyInfo.cs file.
microServiceBus.InternalService         1.0.0   nuget.org This package creates a stub from which you can create an Internal Service for microServiceBus.com
#>

So, as you can see, there is no such module/package called SysInternals to install.
What you do is just download the zip file from here and unpack and use it as normal.
Sysinternals Suite
https://learn.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite

A: I was having the same issue and found the answer here helpful. It seems like something about TLS 1.3 is causing the issue, and the second part of the answer—changing the .Net Framework default TLS version—allowed me to finish my sysinternals install via PowerShell. Then I just deleted the new reg key I had created. I guess I'll just have to wait and see if this is something that comes up again as I continue to learn more and work more with package management in PS.


text:
Q: Calculation of the mean curvature under a normal perturbation Let $X: M^n \to N^{n+1}$ be a Riemannian immersion. Write $g, A, \nu, H$ for the first fundamental form, second fundamental form, Gauss map and mean curvature of $X$ respectively. Consider the normal pertubation $X_u: M \to N$ define by $X_u := X + u\nu$, where $u$ is smooth. For small enough $u$, we have that $X_u$ is an immersion.
In the special case where the dimension of the hypersurface is $n=2$ and the ambient manifold is Euclidean $N = \mathbb{R}^{n+1}$, Nicolaos Kapouleas gives a calculation of the quadratic and higher order terms mean curvature of $X_u$ in 'Complete Constant Mean Curvature Surfaces in Euclidean Three-Space', Appendix C.
Is there a reference or calculation of the mean curvature of $X_u$ (or its linear/quadratic terms) in the more general cases of when the dimension $n$ is not equal to $2$ and/or when the ambient manifold $N$ is not Euclidean?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merging objects with different properties I'm trying to loop through a CSV containing a list of computers and related services.
the first ForEach loops through each 'row'. Then I split the contents of the Services 'column' and loop through the array using a foreach.
The result is:
Computer   winrm            webclient
--------   -----            ---------
localhost1 result goes here result goes here
localhost2
localhost3

I want the result to be like this:
Computer   winrm            webclient    soundservice     netlogon    www     someservice
--------   -----            ---------   ------------       -------     ----     -------
localhost1 running          stopped
localhost2                               running          running    running
localhost3                                                                      running

The problem seems to be that for the second ForEach, it creates a different object each time, and when it comes to adding the object to an objectarray, it only shorts the results from the first object. How can I 'merge' the different objects as it goes through each loop?
function Get-ServiceStatus {

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$False)]
        [string] $ServiceListPath                               # Specifies this accepts an array of strings
    )

    BEGIN {
        # $Csv = Import-Csv $ServiceListPath

$CSVListTemp = @"
Computer,services
localhost1,winrm;webclient
localhost2,soundservice;netlogon;www
localhost3,someservice
"@

        $Csv = $CSVListTemp | ConvertFrom-CSV
        $ObjArray = @()
    }

    PROCESS {

        ForEach ($Row in $Csv) {

            write-host $Row.Computer -ForegroundColor Green

            # $obj = @()
            $obj = new-object psobject
            $obj | add-member -name Computer -type noteproperty -value $Row.Computer

            $ServiceList = $Row.Services -split';'
            #write-host "SERVICELIST: $ServiceList"

                ForEach ($Service in $ServiceList) {
                    write-host "$($Service)" -ForegroundColor cyan
                    $obj | add-member -name $Service -type noteproperty -value "result goes here"

                }

            $ObjArray +=$obj

        } #End of first ForEach
        Return $objarray
    } # End of Process
}

Get-ServiceStatus

A: Iterate over the underlying properties of each object via the hidden psobject memberset. This way you can discover all possible property names, remove duplicates, and then pipe to Select-Object:
# fetch data
$statusObjects = Get-ServiceStatus

# discover property names
$uniqueNames = $statusObjects |ForEach-Object {
    $_.psobject.Properties.GetEnumerator() |ForEach-Object Name
} |Sort-Object -Unique

# select all possible properties from all objects
$statusObjects |Select $uniqueNames

A: If you want to rewrite your function to get that desired output this should get you started:
$csv = @"
Computer,services
localhost1,winrm;webclient
localhost2,soundservice;netlogon;www
localhost3,someservice
"@ | ConvertFrom-Csv

$definedColumns = $csv.Services.Split(';') | Select-Object -Unique

$obj = foreach($line in $csv)
{
    $tmp = [ordered]@{
        Computer = $line.Computer
    }
    $serv = $line.Services.Split(';')

    foreach($service in $definedColumns)
    {
        $tmp[$service] = (
            'Not Found', # => Change this to $null to get the exact output
            'Running'
        )[[int]($service -in $serv)]
    }

    [pscustomobject]$tmp
}

$obj | Format-Table -AutoSize

Computer   winrm     webclient soundservice netlogon  www       someservice
--------   -----     --------- ------------ --------  ---       -----------
localhost1 Running   Running   Not Found    Not Found Not Found Not Found
localhost2 Not Found Not Found Running      Running   Running   Not Found
localhost3 Not Found Not Found Not Found    Not Found Not Found Running


text:
Q: Handle IoC configuration with shared dependencies between projects I've a root project (root), some modules (A, B), and these modules have some external dependencies (Z). I'm using an IoC container.
I'm using C# here, but is a generic pattern question. Let say that my container is services, and I can initialize IoC configuration with use of extension methods. So in root project I'm writing:
services.AddModuleA();
services.AddModuleB();

On module A I've this method:
public static void AddModuleA(this IServiceCollection services)
{
    // Init module internal services.
    //services.AddScoped<IA1Service, A1Service>();
    //...

    // Init module external dependencies.
    services.AddDependencyZ();
}

On module B I've a similar method:
public static void AddModuleB(this IServiceCollection services)
{
    // Init module internal services.
    //...

    // Init module external dependencies.
    services.AddDependencyZ();
}

Obviously Z dependency was already been added, so this tells me that I should not configure it inside a module extension method, and I should rather declare its configuration in root project:
services.AddModuleA();
services.AddModuleB();
services.AddDependencyZ();

But doesn't this break the Least Knowledge principle? Importing and configuring a module A (or B) will bring to a cascade explicit declaration of all dependency configurations.
And related question, is declaring the extension methods AddModuleA() and AddModuleB() a bad pattern at all? Could be a better idea to configure directly on root only services that I will use?
And in this case (a bit extreme), what about config of internal use only class?

A: Supposing that those extension methods are defined in your application's Composition Root, why don't you just remove the call to AddDependencyZ from within AddModuleA and AddModuleB?
public static void AddModuleA(this IServiceCollection services)
{
    // Init module internal services.
    //services.AddScoped<IA1Service, A1Service>();
    //...
}

public static void AddModuleB(this IServiceCollection services)
{
    // Init module internal services.
    //...
}

You would then, as you write, configure the container in the Composition Root (this is the Register phase in the RRR pattern):
services.AddModuleA();
services.AddModuleB();
services.AddDependencyZ();

Does this break the Least Knowledge principle? Yes, it does, but that's one of the many drawbacks of using a DI Container.
I recommend Pure DI instead of using a DI Container. That would make the problem disappear because all the code in the OP would be redundant.


text:
Q: How can I hyperlink to multiple hidden tabs from the same sheet? I've got a list of hyperlinks leading to multiple different hidden sheets in a workbook, using the following for each:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    Application.ScreenUpdating = False
    Worksheets("LL - JLL").Visible = xlSheetVisible
    Sheets("LL - JLL").Visible = True
    Sheets("LL - JLL").Select
    Application.ScreenUpdating = True
End Sub

From what I can tell this now applies to every hyperlink on the sheet. Eevery hyperlink now leads to the same sheet, LL - JLL, whereas I would need each hyperlink to lead to a different sheet. For example,
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    Application.ScreenUpdating = False
    Worksheets("LL - JLL").Visible = xlSheetVisible
    Sheets("LL - JLL").Visible = True
    Sheets("LL - JLL").Select
    Application.ScreenUpdating = True

    Application.ScreenUpdating = False
    Worksheets("LL - EMS").Visible = xlSheetVisible
    Sheets("LL - EMS").Visible = True
    Sheets("LL - EMS").Select
    Application.ScreenUpdating = True

    Application.ScreenUpdating = False
    Worksheets("LL- CCURE").Visible = xlSheetVisible
    Sheets("LL- CCURE").Visible = True
    Sheets("LL- CCURE").Select
    Application.ScreenUpdating = True
End Sub

The following code makes all hyperlinks on the sheet lead to the LL-CURE sheet, rather than their correspondent sheets.
Creating a new Sub for different hyperlinks leads to
Compile error:
Ambiguous name detected: Worksheet_FolowHyperlink

Any guidance would be greatly appreciated :)

A: Logic:

*

*Find the range which the hyperlink is pointing to

*Find the name of the sheet to which the above range refers to

*Pass the name to a common sub to unhide and activate the sheet

Code:
Is this what you are trying?
Option Explicit

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    Dim rng As Range

    '~~> Get the range the hyperlink is referrig to
    Set rng = Application.Evaluate(Target.SubAddress)

    '~~> Unhide and activate the sheet
    UnHideAndActivate rng.Parent.Name
End Sub

Private Sub UnHideAndActivate(shName As String)
    Dim scrnUpdating As Boolean
    Dim dsplyAlerts As Boolean

    On Error GoTo Whoa

    With Application
        '~~> Get user's current setting
        scrnUpdating = .ScreenUpdating
        dsplyAlerts = .DisplayAlerts

        '~~> Set it to necessary setting
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    '~~> Unhide and activate the sheet
    Worksheets(shName).Visible = xlSheetVisible
    Worksheets(shName).Activate
LetsContinue:
    With Application
        '~~> Reset original settings
        .ScreenUpdating = scrnUpdating
        .DisplayAlerts = dsplyAlerts
    End With

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub


text:
Q: Django ImageField core=False in newforms admin In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
TypeError: __init__() got an unexpected keyword argument 'core'

[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?

A: To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).

A: The core attribute isn't used anymore.
From Brian Rosner's Blog:

You can safely just remove any and all core arguments. They are no longer used. newforms-admin now provides a nice delete checkbox for exisiting instances in inlines.

A: This is simple. I started getting this problems a few revisions ago. Basically, just remove the "core=True" parameter in the ImageField in the models, and then follow the instructions here to convert to what the newforms admin uses.


text:
Q: How to set main file in latextools with Sublime Text 3 editor The point is simple, how to set the "master file" that always will be compiled in Sublime Text 3 editor using standard Ctrl-b command (it could using sublime's projects).
Additional feature I'm looking for is setting compilation directory. Where it should be specified?

A: I'm the developer of LaTeXTools. To set the master file, you need to add the following line at the very top (i.e. as the first line) of any included files:
%!TEX root = yourmasterfile.tex
The README has further details.
Right now there is no support for setting a compilation directory other than the one where the master file resides. It's something a few users have requested, so I may get to it eventually, but it will require some pretty extensive changes (I think).
Update: If you're using a .sublime-project file, you can add the master file under the settings property. See the official README.
{
  "settings": {
      "TEXroot": "yourfilename.tex"
  }
}

In my case I had to provide the absolute path for the TEXroot file.

A: It seems the developer has archived the LaTextools. Following oweydd, I met the same condition using ST 4. The solution is to replace "latextools.tex_root" with "TEXroot". Anyway, much appreciate the developer's contribution.


text:
Q: best way to write data to a sqlite from multiple threads I am creating a monitoring application. I want to read queries from all the servers and store it in a sqlite file. Display it whenever it is required. I am using c++ to write this application - to fetch and store data from multiple servers to a single sqlite database. I am using separate threads to fetch data from multiple servers. If I fetch and write data to sqlite directly then it may lock sqlite file as 100s of threads will be writing at the same time.
What is the best way to write data to a sqlite from multiple threads?

A: I don't think there is a better way to do this with sqlite if you cannot control the number of simultaneous write actions.
SQLite is not designed for your use case. Consider switching to a Client/Server RDBMS. This is also what SQLite advises:
https://www.sqlite.org/whentouse.html

Situations Where A Client/Server RDBMS May Work Better
Client/Server Applications
If there are many client programs sending SQL to the same database over a network, then use a client/server database engine instead of
  SQLite. SQLite will work over a network filesystem, but because of the
  latency associated with most network filesystems, performance will not
  be great. Also, file locking logic is buggy in many network filesystem
  implementations (on both Unix and Windows). If file locking does not
  work correctly, two or more clients might try to modify the same part
  of the same database at the same time, resulting in corruption.
  Because this problem results from bugs in the underlying filesystem
  implementation, there is nothing SQLite can do to prevent it.
A good rule of thumb is to avoid using SQLite in situations where the same database will be accessed directly (without an intervening
  application server) and simultaneously from many computers over a
  network.
(...)
High Concurrency
SQLite supports an unlimited number of simultaneous readers, but it will only allow one writer at any instant in time. For many
  situations, this is not a problem. Writer queue up. Each application
  does its database work quickly and moves on, and no lock lasts for
  more than a few dozen milliseconds. But there are some applications
  that require more concurrency, and those applications may need to seek
  a different solution.

A: You could use messages queue like RabbitMQ or Redis to solve that kind of problem

*

*Send your data to the queue, which is good at async inserts

*Create a worker-thread, that will take new messages from the queue

*Use that worker to insert new messages to SQLite

With this architecture, only one worker-thread will write to a database, and there will be no locking problems, as it's ok for SQLite to work in "one writer multiple readers" mode

A: Use only one sqlite database connection for all threads, opened with flag SQLITE_OPEN_FULLMUTEX set.
Database will then serialize writes from all of the threads and there will be no locking.
But you need to tune your database and application design so write queries run fast enough, how much is required.


text:
Q: JBoss wildfly 10 NoClassDefFoundError at migrate from JBoss 4.2 I have a spring mvc application running into JBoss 4.2. I'm trying migrate this web app to JBoss wildfly 10 (wildfly-10.0.0.Final version).
When I try deploy my app show this error:
"{\"WFLYCTL0080: Failed services\" => {\"jboss.deployment.unit.\\\"myApp.war\\\".POST_MODULE\" => \"org.jboss.msc.service.StartException in service jboss.deployment.unit.\\\"myApp.war\\\".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment \\\"myApp.war\\\"
Caused by: java.lang.RuntimeException: WFLYSRV0177: Error getting reflective information for class org.ajaxtags.tags.AjaxDisplayTag with ClassLoader ModuleClassLoader for Module \\\"deployment.myApp.war:main\\\" from Service Module Loader
Caused by: java.lang.NoClassDefFoundError: au/id/jericho/lib/html/Segment
Caused by: java.lang.ClassNotFoundException: au.id.jericho.lib.html.Segment from [Module \\\"deployment.myApp.war:main\\\" from Service Module Loader]\"}}"

Looking for the web, I read that I need to load the jar "jericho-html-2.6.1.jar". To do it, I added in ${wildfly_home}/modules/system/layers/base/au/id/jericho/lib/html/main
 the jericho-html-2.6.1.jar and this module.xml
<?xml version="1.0" encoding="UTF-8"?>
    <module xmlns="urn:jboss:module:1.1" name="au.id.jericho.lib.html">
    <resources>
        <resource-root path="jericho-html-2.6.1.jar"/>
    </resources>
    <dependencies>
    </dependencies>
</module>

I added the extension in standalone.xml
<extension module="au.id.jericho.lib.html"/>

But I get same error.

A: Why do you add the extension in standalone.xml ??
You should add a WEB-INF/jboss-deployment-structure.xml file to your war with :
<jboss-deployment-structure>
    <deployment>
        <dependencies>
            <module name="au.id.jericho.lib.html" />
        </dependencies>
    </deployment>
</jboss-deployment-structure>


text:
Q: How to fix auth error on CouchDB replication I've setup local/remote CouchDB servers and I'd like to replicate between them.
Curling on each works fine so I know both databases are running ok:
curl -u admin:password https://remote.host.net/db_name - works
curl -u admin:password http://localhost:5984/db_name - works
However, when I try and setup replication it borks. This is the command used to setup the replication:
curl -u admin:password -X POST http://localhost:5984/_replicate -d '{"source":"https://admin:password@remote.host.net/db_name", "target":"http://admin:password@localhost:5984/db_name"}' -H "Content-Type: application/json"

Error message:
{"error":"replication_auth_error","reason":"{session_request_failed,\"https://remote.host.net/_session\",\n\"admin\",\n{conn_failed,{error,nxdomain}}}"}

Anyone have any ideas what's going wrong here?

A: I faced the same problem and adding "continuous": true to the request body, returns with a "ok":true.
From the docs, continuous should be used only when you want the replication to be triggered always the source changes, I don't know why the error when it is not included.
[edit]
Even with the success response, the data is not been copied. So we use this script to achieve the replication https://gist.github.com/Aybee5/fba07b06b94442a529ebae5465b77737

A: Yup.. I know its been almost a year since I posted the original question but I just ran into a similar issue and solved it by using the source_proxy/target_proxy kwargs in the replication request.
I can't remember if I was behind a proxy last time unfortunately.


text:
Q: Can I send an email with a hyperlink to a different domain (website) that doesn't match my email domain? Bear with me because I'm still learning about this. My description will probably be long. And please talk to me like a newbie:
My plan is to get multiple domains and through that, create multiple Google Workspace email accounts to send emails to different prospects in my emailing list.
On the emails that I send out from different email domain accounts, I was planning on just adding a link/hyperlink to my website for the recipients to click on & browse.
If I did that, would that ruin my reputation in the eyes of ISP? I fear that because my email domain doesn't match the website domain I'm hyperlinking will lower my reputation score. My fear is that I'll get blacklisted, get marked as spam, and many bad things, if I do it this way.
Thank you in advance for putting up with the long description. It's the best way for me to explain the situation.
I saw an article that says if my email domain and the domain being hyperlinked in the email message doesn't match, it's fine. It just depends on the hyperlinked domain's reputation and what I write on the hyperlink text (not misleading).
But I am just making sure by writing my question here.
And I think there is another way that might work, if this is not recommended:
Have the hyperlinked domain (website) to match with my email domain by connecting those multiple domains (that are used in my email accounts) to my primary domain (website).
Does that make sense?
Let me know if ANY OF THIS makes sense. Sorry again for my ignorance.


text:
Q: can the spark window function first_value be used? The window function first_value (equivalent first) seems to exist as the code snippet below demonstrates. The function is not listed in
https://spark.apache.org/docs/3.1.2/sql-ref-functions-builtin.html#window-functions
however it is listed in
https://spark.apache.org/docs/latest/api/sql/#first_value
in any case it seems to work as a window function
# first_value window function
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
from pyspark.sql.types import *
import pandas as pd
from time import perf_counter

# get a spark session
spark = SparkSession.builder.appName('learn').getOrCreate()

# create dataset
schema = StructType([
    StructField('c1', StringType(), nullable=True),
    StructField('c2', StringType(), nullable=True),
    StructField('value', DoubleType(), nullable=True),
])
import random
data = [(random.choice(list('ABC')), random.choice(list('abc')), random.random()) for _ in range(100)]
df = spark.createDataFrame(data, schema=schema).drop_duplicates()
df.createOrReplaceTempView('tmp_view')

# execute window function (using first() instead of first_value() gives the same result)
query ="""SELECT c1, first_value(value) OVER (PARTITION BY c1) as f FROM tmp_view"""
res = spark.sql(query)
res.drop_duplicates().show()

so the question is this a matter of omitting listing the first_value/first window function in the window function table in the documentation?
Looking at the dataframe API, it seems first_value does not exist, whilst first is not a window function but an aggregate function
import pyspark.sql.functions as f
f.first?
Signature: f.first(col, ignorenulls=False)
Docstring:
Aggregate function: returns the first value in a group.
The function by default returns the first values it sees. It will return the first non-null
value it sees when ignoreNulls is set to true. If all values are null, then null is returned.
.. versionadded:: 1.3.0

However, it can be executed as a window function using the dataframe API:
from pyspark.sql.window import Window
w = Window.partitionBy("c1")
res = df.withColumn('f', f.first('value').over(w))
res.select(['c1', 'f']).drop_duplicates()
res.show()

It can also be used as an aggregation function
data = [('a', 3),
        ('a', 30),
        ('b', 7),
        ('b', 70)
        ]
df = spark.createDataFrame(data, ['nam', 'value'])
res = df.groupby('nam').agg(f.first(f.col('value')))
res.show()

what is going on? Is it is so that the documentation is confusing or my understanding is somehow wrong?

A: check this official api and it's examples, you can define a windowing column from a dataframe column by xxx.over(w)


text:
Q: I want to generate Same URL for both android and ios apps on store There are app on my app store and play store, the android, and ios version
I want to generate a single link which redirects the user to app store if it opened in iPhone and redirect to play store if it open in android phone
is there a way do this, there is some company doing this.

A: You should specify, whether you want to achieve this on your website?
If yes, you could put up JQuery to detect the device type and based on type of device you can redirect the user to desired URL (play store or app store)
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script>
        $(document).ready(function (){
         if(navigator.userAgent.toLowerCase().indexOf("android") > -1){
             window.location.href = 'https://play.google.com/store/apps/developer?id=WhatsApp+Inc.&hl=en';
         }
         if(navigator.userAgent.toLowerCase().indexOf("iphone") > -1){
             window.location.href = 'https://itunes.apple.com/in/app/whatsapp-messenger/id310633997?mt=8';
         }
        });
</script>

For more help, Refer: https://forum.webflow.com/t/redirect-to-app-store-or-play-store-if-webflow-website-opened-from-an-iphone-or-an-android-device/21350/6

A: You just can do it with your server side. No service for this problem

A: You can upload (to public host) a small html page which on load will detect which device is being used and redirect accordingly.
Here is an example of how to do that with JavaScript

A: To Achieve the mentioned solution for your website, you have to take care of the following -

*

*On Desktop/Laptop browsers, You can't have one link to redirect on App Store and Play Store both. Because by Desktop OS Windows/Mac/Linux you won't be able to know about the User's Mobile Operating system.

*For Mobile Browsers, You can detect easily detect the device type of User based on your front-end technology(JQuery, Angular etc.). For getting the help for code you can provide the details about your front end and I am sure that community will help you on that as well.


text:
Q: Purpose of super keyword in objective c i asked meaning of "SUPER" keyword in view didload method
eg. [super viewdidload] kindly tell me correct meaning of this keyword.

A: The keyword super refers to the superclass of the caller.  In usage, it's a way to invoke the superclass's implementation of the current method.


text:
Q: I am trying to manage a small number of users control of a webpage So to start off, I have a raspberry pi, running a lighttp server on arch. I have a webpage that will have a max of 10 people connected at a time. Each user will be given the tag "Master," or "observer." The webpage will have controls that only the "Master," can use.
Just a heads up: I am just learning most of this so I may be making some mistakes about how to accomplish this.
My original idea is has follows. When a user connects to the database their IP address would be grabbed and inserted into a SQLite database, along with a user tag, and time of connection. From there I would be able to query the database for the users tag when they tried to execute various commands.
Whatever I use needs to be very lightweight and not store cookies on the users device.
Here is the JavaScript I currently have, it probably isn't the most efficient, but I plan on getting it working then making it look nice.
This code is supposed to connect the databases and insert the user.
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script type="application/javascript">
    var db = openDatabase('userCon.contbl.sqlite', '1.0', 'contbl', 1024);
    db.transaction(function(transaction) {
       var ip = myip;
       var conStatus = "master"
       var date = new Date();
       console.log('Inserting into the database ' + ip + ',' + conStatus +',' + date);
       transaction.executeSql('INSERT INTO contbl(ipAd, conType, lastActive) VALUES (?,?,?,?)',[ip,conStatus,date], function(transaction, results) {

       }, function (transaction, err){
             console.log(err.message+":Error"); // here an error
          });
    });
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip">  </script>

I am unable to connect to the SQLite database I created on the pi, which  after my research may be because SQLite is supposed to be run locally and not on a server.
Is there some sort of work around to point to the SQLite database on the pi, or is there a better resource to use for this type of task?
EDIT:
I guess my original post was not specific enough. The basic idea is I need to be able to pass a tiny bit of information from a webpage, back to the server hosting it. i.e. User connect to the server and sends its IP then the server tags that IP as an Observer of Controller. From there the server will treat each person viewing the webpage differently based on how the user was tagged.
My original plan was to use a really light weight database like SQLite, but as I found out, SQLite is local use only. I need to do this on a sever with lower then 10 connections.
My hope is someone has a suggestion, or an example to solve this problem.

A: The most common way for javascript running on a web page to talk to a server these days is some kind of RESTful web service.
You'll want to find a server-side programming language that runs on the Pi. Maybe node.js? It's like  javascript but on a server, see here: http://weworkweplay.com/play/raspberry-pi-nodejs/
You then write whatever methods you want in the server-side language, methods which talk to the database, then have your client-side javascript call those methods. Google "REST services node.js" and you'll find plenty of how-tos.

A: If the SQLite database is running on the server, and this code runs in the user's browser, it can't connect to the database. The only interaction between the browser and your server is HTTP, unless there's a gigantic security hole in your server.


text:
Q: why typeof function is coming object here? Why type of function is coming object in following javascript code?

  var y = 1;
    if (function f(){}) {
     y += typeof f;
   }
  console.log(y);

both will give same result
Output is coming as 1object
Shouldn't it be 1function?
Edit1: Please see below Image I'm getting 1object in chrome 60

A: Getting typeof f === 'object' from an isolated code as you've posted is not possible, since f is not defined in the scope you're using it. The function definition in the condition is not a function declaration, it is a function expression. The name f is visible in the body of the newly-created function only, it is not available outside of the said function. That makes typeof f to return undefined, any other reference to f would fire a reference error.
Hence the only possible way to get 1object is to define an object or array named f before writing the shown code in the posted screenshot, either in the console, or on the opened page behind the console.
This behavior of the named function expressions is defined in the standards. In very old IE you would get 1function, since old IEs created a global copy of the named functions expressions too.


text:
Q: How I can get the value of local variable 'head' in following code? function call(){

  var th;
  var head;
  $('#coToolTable').on('click', '.edit',function () {
    th = $('#coToolTable th').eq($(this).index());

    head=th.text();
    alert("head="+head);

  });

  var values1 = $('table tr td :checkbox:checked').map(function () {
    return $(this).closest('tr').find('td:first').text()

  }).get();

  alert("values="+values1+"head="+head);
  check(values1,head);
}

In this function, when I run it then the alert("head="+head); gives output of my table header but in next alert box alert("values="+values1+"head="+head); it gives head=undefined. Why?

A: You're assigning a value to head when you click on #coToolTable, not before that. Your second alert runs as soon as you execute call(), which is going to be before your click event handler runs and assigns a value to head. Therefore, when that second alert runs, you are seeing the value of head at the time it was declared: undefined.


text:
Q: GTM- Regular expression to match child pages but not the parent that share the same page path Looking for a regular expression for Google Tag Manager that will use the path in a URL but not return it.
For example: (\/fruit-and-veg\/).*$ will match all of the following:
https://www.the-example.co.uk/fruit-and-veg/
https://www.the-example.co.uk/fruit-and-veg/bunch-of-grapes/
https://www.the-example.co.uk/fruit-and-veg/red-pepper/
https://www.the-example.co.uk/fruit-and-veg/green-tomato/

I do not want to match on https://www.the-example.co.uk/fruit-and-veg/, but I do want to match on the others.
Or another way in GTM to achieve this.

A: .* match any text, empty string included, hence, you allow /fruit-and-veg/ at the end of string.
Require at least one more character:
\/fruit-and-veg\/.+

EXPLANATION
--------------------------------------------------------------------------------
  \/                       '/'
--------------------------------------------------------------------------------
  fruit-and-veg            'fruit-and-veg'
--------------------------------------------------------------------------------
  \/                       '/'
--------------------------------------------------------------------------------
  .+                       any character except \n (1 or more times
                           (matching the most amount possible))


text:
Q: AddressFilter mismatch at the EndpointDispatcher during dottrace remote debugger connection Trying to connect to remote agent via load balancer gives error:
The message with To 'net.tcp/address/RemoteAgent' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.
Most of the solutions talk about adding the below to service code:
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
Can something be done in the config to turn off AddressFilter matching?
Contents of RemoteAgent.exe.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <system.serviceModel>
    <services>
      <service name="JetBrainsAgentService" behaviorConfiguration="JetBrainsAgentServiceBehavior" />
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="JetBrainsAgentBinding_WSHttp" maxReceivedMessageSize="2147483647" openTimeout="00:01:00" receiveTimeout="infinite" sendTimeout="00:01:00" closeTimeout="00:01:00">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
          <security mode="None" />
        </binding>
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="JetBrainsAgentBinding_NetTcp" maxReceivedMessageSize="2147483647" openTimeout="00:01:00" receiveTimeout="infinite" sendTimeout="00:01:00" closeTimeout="00:01:00">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
          <security mode="None" />
        </binding>
      </netTcpBinding>
      <netNamedPipeBinding>
        <binding name="JetBrainsAgentBinding_NetNamedPipe" maxReceivedMessageSize="2147483647" openTimeout="00:01:00" receiveTimeout="infinite" sendTimeout="00:01:00" closeTimeout="00:01:00">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
          <security mode="None" />
        </binding>
      </netNamedPipeBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="JetBrainsAgentServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

A: You can try to use the workaround described here: http://androidyou.blogspot.com/2010/09/fix-wcf-addressfilter-mismatch-error.html
Also, you can use dotTrace console profiler instead of Remote Agent: https://www.jetbrains.com/help/profiler/Performance_Profiling__Profiling_Using_the_Command_Line.html


text:
Q: How to encode an audio file to bytes in UTF-8 in Android Studio? I am trying to send an audio file that was created with MediaRecorder to the Google Speech To Text API.
The audio file was created by the MediaRecorder with the following rules:
protected void setupMediaRecorder() {
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setAudioSamplingRate(16000);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
    mMediaRecorder.setOutputFile(mPathSave);
}

after the file is created, I'm doing the following:
private void isCorrectAnswer(MediaRecorder iRecorder, final Button iButton)  {
        String url = MYURL;
        File file = new File(mPathSave);
        InputStream inFile = null;
        try {
            inFile = new FileInputStream(mPathSave);
            byte[] bytes = fileToBytes();
            String stringBytes = new String(bytes, "UTF-8");
            writeToFile(stringBytes, PictureRecognitionLevel.this);
            try {
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("original_text", mQuestion.GetmAnswer());
                jsonBody.put("email", MYMAIL);
                jsonBody.put("audio_file", stringBytes);
                final RequestQueue queue = Volley.newRequestQueue(this);
                RequestFuture<JSONObject> future = RequestFuture.newFuture();
                final JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                iButton.setText(response.toString());
                            }
                        },  new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.print("ERROR!");
                    }
                });
                queue.add(jsonRequest);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private byte[] fileToBytes() {
    byte[] bytes = null;
    File audioFile = new File(mPathSave);
    try {
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){

            bytes = Files.readAllBytes(audioFile.toPath());

        } else {
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bytes;
}

What I get from this conversion is:
#!AMR-WB
 "�����-X���G���HB��@PITCH�@D ����a=)˂����p� c �� ��S(@@UQV�ep�*{�

(It's longer than that...)
I've read that the black diamond is a sign for either a problem with reading the data or a problem with the utf-8 encoding.
What can I do to get the file encoded in UTF-8? What am I doing wrong?


text:
Q: How can I avoid race condition when making cached Ajax calls Since many public APIs such as GitHub public API has a request limit, so it makes sense for us to implement some cache mechanism to avoid unnecessary request calls. However I discovered that this might incur race condition.
I coded up an example to demonstrate the situation
https://codesandbox.io/s/race-condition-9kynm?file=/src/index.js
Here I first implement a cachedFetch ,
const cachedFetch = (url, options) => {
  // Use the URL as the cache key to sessionStorage
  let cacheKey = url;
  let cached = sessionStorage.getItem(cacheKey);
  if (cached !== null) {
    console.log("reading from cache....");
    let response = new Response(new Blob([cached]));
    return Promise.resolve(response);
  }

  return fetch(url, options).then(async response => {
    if (response.status === 200) {
      let ct = response.headers.get("Content-Type");
      if (ct && (ct.includes("application/json") || ct.includes("text"))) {
        response
          .clone()
          .text()
          .then(content => {
            sessionStorage.setItem(cacheKey, content);
          });
      }
    }
    return response;
  });
};

It uses sessionStorage to cache the results.
And I am making the requests to Github API. The idea is simple, there is a Input and a p tag, and the Input has a event listener to listen for input changes and uses the input value to get the github user's name and the p will render the name on the page.
The race condition might occur in the following situation:

*

*User types jack in the input field, since this is the first time the user types jack so the result is not cached. The request will be made to fetch this jack user's Github profile

*Then the user types david in the input field, since this is also the first time the user types david so the result is not cached. The request will be made to fetch this david user's Github profile

*Finally the user types jack in the input field for the second time, since the result is already in the cache. The no request will be made and we can read the user profile from sessionStorage and render the result immediately.

Then you can image that, if the second request, i.e. request to fetch david's profile takes too long, user will see david end up being the final result rendered on the page even if his/her last search was for jack. This is because jack's result got overridden by the david's result which takes much longer to get back.
In my example, I used this function to simulate the user typing
async function userTyping() {
  sessionStorage.clear();
  inputEl.value = "jack";
  inputEl.dispatchEvent(new Event("input"));

  await sleep(100);
  inputEl.value = "david";
  inputEl.dispatchEvent(new Event("input"));

  await sleep(100);
  inputEl.value = "jack";
  inputEl.dispatchEvent(new Event("input"));
}

the sleep function is defined as
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

Right now what I can think of is using debounce to avoid the situation when the user is typing too fast. However it doesn't solve the problem in the fundamental level.
Also we can use some global variable to keep track of the latest input value, and use that to check if the result we are about to render is from the latest input value. Somehow I just don't think this is an elegant solution to this problem.
Any suggestions are appreciated.

A: You can save the current e.target.value in a variable inside the input handler. Then, once the cachedFetch response comes back, check if the same value is still in the input field. Only set the input field if the values match.
(If the values don't match, like if the input is a, then b, then a, and it takes the b request a longer time to finish, then b will be stored in the cache, but it won't be displayed to the user)
Also, make sure to only display the result to the user when an error does not occur:
inputEl.addEventListener("input", e => {
  const { value } = e.target;
  if (value === "") {
    return;
  }
  const url = endpoint + value;
  cachedFetch(url)
    .then(response => response.json())
    .then((result) => {
      if (e.target.value === value) {
        resultContainer.innerHTML = result.name;
      }
    })
    .catch(errorHandler);
});

A: You might be able to use the AbortController. It's experimental and not added to all browsers yet (missing in IE).
https://developer.mozilla.org/en-US/docs/Web/API/AbortController
Create an AbortController instance.
const controller = new AbortController();
const signal = controller.signal;

And connect it to your fetch.
return fetch(url, { ...options, signal }).then(async response => ...

And then cancel the request when you return something from the cache.
if (cached !== null) {
  controller.abort();
  ...
}


text:
Q: Creating Task for Different Users Outlook account I have read several posts and got a solution that use Microsoft.Office.Interop.Outlook to work to create a task in Outlook.  Here is the code that will create a task in outlook for my user.
    public void CreateOutlookTask()
    {
        Application outlookApp = new Application();
        TaskItem oTask = outlookApp.CreateItem(OlItemType.olTaskItem);
        Inspector oInspector = oTask.GetInspector;
        oTask.Subject = "This is my task subject";
        oTask.DueDate = Convert.ToDateTime("06/25/2011");
        oTask.StartDate = Convert.ToDateTime("06/20/2011");
        oTask.ReminderSet = true;
        oTask.ReminderTime = Convert.ToDateTime("06/28/2006 02:40:00 PM");
        oTask.Body = "This is the task body";
        oTask.Status =OlTaskStatus.olTaskInProgress;
        oTask.Save();
    }

I still have two issues with the above code.
1) It will only create tasks for the user that is running the application.  I hope to create tasks from a web app, so I need to be able to log into each users account because the web app will not have an outlook account.
2) Using Microsoft.Office.Interop.Outlook requires that outlook is installed.  I would really like a solution that doesn't require outlook to be installed on the machine, but haven't found one.
Any help on the above two issues would be greatly appreciated.

A: You can use exchange web services to create items such as this without the need of the interop libraries.
Get started with EWS client applications

A: If using OOM is still an option, you can use Application.Session.GetSharedDefaultFolder to retrieve the default Tasks folder of another Exchange user. You can then create a new task there using MAPIFolder.Items.Add.


text:
Q: Showing LiteDB database items in data grid view I'm using LiteDB. Customer definition is like below:
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string[] Phones { get; set; }
    public string[] Cars { get; set; }
}

When I want to show my data in data grid view only first two columns are shown and data grid view doesn't show last two columns which are array.
and this is GetAll
private List<Customer> GetAll()
    {
        var issuesToReturn = new List<Customer>();
        try
        {
            using (var db = new LiteDatabase(Constants.ConnectionString))
            {
                var issues = db.GetCollection<Customer>("customers");
                foreach (Customer issueItem in issues.FindAll())
                {
                    issuesToReturn.Add(issueItem);
                }
            }
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.Message);
        }
        return issuesToReturn;
    }

A: You can try use another field just to format data in you grid (but not stored in datafile). Like this:
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string[] Phones { get; set; }
    public string[] Cars { get; set; }

    [BsonIgnore]
    public string DisplayPhones => string.Join(", ", Phones);

    [BsonIgnore]
    public string DisplayCars => string.Join(", ", Cars);
}

Then, change in you grid to map your column using this "Display" properties.

A: Use "Include" method to load relative data:
var issues = db.GetCollection("customers").Include(x => x.Phones).Include(x => x.Cars);
Also note that GridView in WPF can't show array in one cell by itself. You need to add columns manually: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview(v=vs.110).aspx


text:
Q: Brightness not working on ubuntu 17.10, broken upgrade from 17.04? There are multiple similar questions present, but none addressed my concern. I recently upgraded from 17.04 to 17.10.
Full story:

*

*I start the system:
Dell logo -> a dark maroon screen -> Display is completely off -> The login screen sound. If I could see anything now, I would type my password and login.

*I turn off the system.

*Power on again. Select recovery mode from the grub options and start. Ubuntu starts up and everything's good after the login, but now I cannot change the brightness of the screen. It's set to maximum.

Things I tried without any success:

*

*changing the contents of /etc/default/grub as mentioned here: Display brightness control not working in 17.10

*Using xbacklight

*Running ls /sys/class/backlight/ doesn't return me any module. Related bug report:  https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/1724933

*Cannot find the UI for changing the brightness anywhere

*Shortcut keys for brightness is not working

Does brightness not work in the recovery mode?
If it's so, can anyone please give any clues on why I am unable to login to Ubuntu 17.10 in the normal mode?
I also created a live USB  of 16.04 to reset everything. After selecting the USB while starting up the system, it takes me nowhere. Stucks at a black blank screen for hours.


text:
Q: windows server 2008 R2 Standard - Stop Anonymous Logon On Windows Server 2008 R2 Standard ED. We have tons of ANONYMOUS LOGON logged under Event Viewer
How to stop this ? How to disable ANONYMOUS LOGON ?
Copy of messagge:

An account was successfully logged on.

Subject:
    Security ID:        NULL SID
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0

Logon Type:         3

New Logon:
    Security ID:        ANONYMOUS LOGON
    Account Name:       ANONYMOUS LOGON
    Account Domain:     NT AUTHORITY
    Logon ID:       0x7863af9a
    Logon GUID:     {00000000-0000-0000-0000-000000000000}

Process Information:
    Process ID:     0x0
    Process Name:       -

Network Information:
    Workstation Name:   ZZC-01309261645
    Source Network Address: 111.xxx.xxx.134
    Source Port:        55xxx

Detailed Authentication Information:
    Logon Process:      NtLmSsp
    Authentication Package: NTLM
    Transited Services: -
    Package Name (NTLM only):   NTLM V1
    Key Length:     128

This event is generated when a logon session is created. It is generated on the computer that was accessed.

The subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.

The logon type field indicates the kind of logon that occurred. The most common types are 2 (interactive) and 3 (network).

The New Logon fields indicate the account for whom the new logon was created, i.e. the account that was logged on.

The network fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.

The authentication information fields provide detailed information about this specific logon request.
    - Logon GUID is a unique identifier that can be used to correlate this event with a KDC event.
    - Transited services indicate which intermediate services have participated in this logon request.
    - Package name indicates which sub-protocol was used among the NTLM protocols.
    - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.

A: You can use a registry key to restrict it
HKEY_LOCAL_MACHINE\SYSTEM\CurrentcontrolSet\Control\Lsa
Change DWORD "RestrictAnonymous" to value 2
This will set it to level 2 restriction.  Be careful, though, as it can break things, as seen here with problems associated with Windows 2000.
http://support.microsoft.com/default.aspx?scid=KB;en-us;296405
You may want to take some additional looks into your machine, and possibly your network, though.  You've got NTLM running which is a very old and very insecure protocol called NT Lan Manager.  You've also possibly got open ports where there shouldn't be, indicating that you may not be protected by a firewall.  Windows security has improved over the years, but its still dangerous to be running "naked" on the Internet, especially when you've got NTLM happening.  Get that thing behind a firewall, and perhaps look into having a security pro look into your configuration.


text:
Q: Зависание приложения из-за потери связи с сервером У меня есть функция, отправляющая запросы на сервер и принимающая его ответ:

function send(send_id,url,data,cb_func){
        var xhr_data= new XMLHttpRequest();
        xhr_data.open('post',url+'&global_code='+global_code, true);
        xhr_data.timeout = 1500;
        xhr_data.ontimeout = function(){
               console.log("Лимит ожидания был превышен!");
               setTimeout(send(send_id,url,data,cb_func), 200);
        }
        var params = "&param"+123;
        xhr_data.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr_data.setRequestHeader("Content-length", params.length);
        xhr_data.setRequestHeader("Connection", "close");
        xhr_data.onreadystatechange = function(){
             if(!(this.readyState==4 && this.status==200 )) return;
             cb_func && cb_func(JSON.parse(this.responseText));
            }
         xhr_data.send(params);
         };

Из-за того, что связь между сервером и клиентом непостоянна, возникает ситуация, когда программа ждет ответ на свой запрос, а он не приходит, так как связь потеряна. Это приводит к зависанию приложения. Я установила timeout, однако он не всегда срабатывает.
Как можно обработать такого рода ошибки?

A: У Вас проблема в том, что вы ожидаете только статус 200. Поэтому, если статус не 200, и запрос выполнен (допустим со статусом 500), Вы не увидите результата. Попробуйте изменить .onreadystatuschange следующим образом:
xhr_data.onreadystatechange = function(){
    if (this.readyState!==4) return;
    cb_func && cb_func(JSON.parse(this.responseText), this.status);
}

Тогда, вторым аргументом в cb_func получите статус завершения запроса.
Есть еще вариант другой, когда первым аргументом передаете ошибку, если она есть, а вторым - результат (подход часто используется в node.js). Тогда, в случае this.status===200, можно вызвать cb_func(null, JSON.parse(this.responseText)), а в случае неудачи, к примеру cb_func(new Error('Request error. Status: '+this.status)).
П.С. ну и нужно проверить, что cb_func всегда передается, что это всегда функция, и что в ответе всегда валидный JSON, потому что иначе, в первом случае - просто ничего не выполнится, а в остальных - выбросится исключение.

Upd: Попробуйте, все-таки, в cb_func передавать просто this.responseText, а внутри cb_func парсить. Т.к. в случае срабатывания таймаута - this.responseText будет равен пустой строке, а при попытке вызвать JSON.parse('') Вы получите эксепшн.


text:
Q: javascript error implementing 'error' and 'complete' handlers in fine-uploader jquery call I am a Java developer, and not a great JS programmer, so maybe I'm just missing something here. But I am getting an error I don't know how to interpret or fix trying to put some custom handling of the 'on complete' and 'on error' logic into the my fine-uploader call.
The actual file uploading part is working, however my custom calls to 'alert' are not.
Here is the script code:
            $j(document).ready(function () {
                $j('#uploadNonDICOM_uploader').fineUploader({
                    request: {
                        inputName: 'uploadNonDICOM',
                        endpoint: '/handleUpload?',
                        params: {
                             nav: 'Cases',
                             subnav: 'New Case',
                             action: 'uploadCaseFile',
                             id: function() {return document.getElementById('id').value},
                             timestamp: function() {return document.getElementById('timestamp').value}
                        }
                    }
                }).on('error', function (event, id, name, responseJSON) {
                     alert('file upload failed');
                }).on('complete', function (event, id, name, responseJSON) {
                     alert('file uploaded');
                });
            });

The file uploader is actually working, but I get an error when looking in firebug, and the "alert" calls are not being made.
The error I am getting is:
TypeError: $j(...).fineUploader(...).on is not a function
http://localhost:8080/SpectraRad?nav=Cases&subnav=New%20Case
Line 741
Where line 741 is:
                }).on('error', function (event, id, name, responseJSON) {

To me this indicates I am maybe making a syntactical error?? For the life of me I cant see it if I am.
Any help I can get figuring this out would be greatly appreciated.
Thanks,
Dustin

A: The on method was added to jQuery 1.7.  You are using 1.6.1, which does not include this function.  You can use bind in place of on.  However, I strongly suggest, instead, you use a more recent version of jQuery.
Also, the signature for your error handler is incorrect, but that is not the cause of your problem.  Please see the events page in the documentation for a description of all parameters passed to each event handler.


text:
Q: why the camera backward is equivalent to moving the whole world forward? Opengl superbible 4th Edition.page 164

To apply a camera transformation, we take the camera's actor transform and flip it so that
  moving the camera backward is equivalent to moving the whole world forward. Similarly,
  turning to the left is equivalent to rotating the whole world to the right.

I can't understand why?

A: Image yourself placed within a universe that also contains all other things. In order for your viewpoint to appear to move in a forwardly direction, you have two options...

*

*You move yourself forward.

*You move everything else in the universe in the opposite direction to 1.

Because you defining everything in OpenGL in terms of the viewer (you're ultimately rendering a 2D image of a particular viewpoint of the 3D world), it can often make more sense from both a mathematical and programatic sense to take the 2nd approach.

A: Mathematically there is only one correct answer. It is defined that after transforming to eye-space by multiplying a world-space position by the view-matrix, the resulting vector is interpreted relative to the origin (the position in space where the camera conceptually is located relative to the aforementioned point).
What SuperBible states is mathematically just a negation of translation in some direction, which is what you will automatically get when using functions that compute a view-matrix like gluLookAt() or glmLookAt() (although GLU is a lib layered on legacy GL stuff, mathematically the two are identical).
Have a look at the API ref for gluLookAt(). You'll see that the first step is setting up an ortho-normal base of the eye-space which first results in a 4x4 matrix basically only encoding the upper 3x3 rotation matrix. The second is multiplying the former matrix by a translation matrix. In terms of legacy functions, this can be expressed as
glMultMatrixf(M); // where M encodes the eye-space basis
glTranslated(-eyex, -eyey, -eyez);

You can see, the vector (eyex, eyey, eyez) which specifies where the camera is located in world-space is simply multiplied by -1. Now assume we don't rotate the camera at all, but assume it to be located at world-space position (5, 5, 5). The appropriate view-matrix View would be
[1 0 0 -5
 0 1 0 -5
 0 0 1 -5
 0 0 0  1]
Now take a world-space vertex position P = (0, 0, 0, 1) transformed by that matrix: P' = View * P. P' will then simply be P'=(-5, -5, -5, 1).
When thinking in world-space, the camera is at (5, 5, 5) and the vertex is at (0, 0, 0). When thinking in eye-space, the camera is at (0, 0, 0) and the vertex is at (-5, -5, -5).
So in conclusion: Conceptually, it's a matter of how you're looking at things. You can either think of it as transforming the camera relative to the world, or you think of it as transform the world relative to the camera.
Mathematically, and in terms of the OpenGL transformation pipeline, there is only one answer, and that is: the camera in eye-space (or view-space or camera-space) is always at the origin and world-space positions transformed to eye-space will always be relative to the coordinate system of the camera.
EDIT: Just to clarify, although the transformation pipeline and involved vector spaces are well defined, you can still use world-space positions of everything, even the camera, for instance in a fragment shader for lighting computation. The important thing here is to know never to mix entities from different spaces, e.g. don't compute stuff based on a world-space and and eye-space position and so on.
EDIT2: Nowadays, in a time that we all use shaders *cough and roll-eyes*, you're pretty flexible and theoretically you can pass any position you like to gl_Position in a vertex shader (or the geometry shader or tessellation stages). However, since the subsequent computations are fixed, i.e. clipping, perspective division and viewport transformation the resulting position will simply be clipped if its not inside [-gl_Position.w, gl_Position.w] in x, y and z.
There is a lot to this to really get it down. I suggest you read the entire article on the rendering pipeline in the official GL wiki.


text:
Q: Excel not calculating a hh:mm formula where part of formula is derived from anothe formula result Am attempting to convert 11 hrs and 27 minutes to minutes but receiving incorrect results.
I am working on an application that charges a fee for parking of aircraft. The charges are levied on a per 5 minute basis. I have an aircraft that is parking for 11hrs and 27 minutes. This value is derived from another formula. I am trying to break that down to minutes so I can divide the total minutes by 5 in order to arrive at a total billable 5 minute periods. That is not working unless I direct input the 11hrs and 27 minutes and unless I do that I am getting 25,124,682 as a results. Trying different formats produces different incorrect results.
Cell B3 and B5 have arrival and departure dates as follows:
B3 02 06 19 17:18 formatted as dd mm yy\ hh:mm
B5 03 06 19 18:09 formatted as dd mm yy\ hh:mm
Cell D3 has the total parking time OF 11:27 Mins derived from adding cells B3 and B5 together and formatted as hh:mm.
Cell G3 has a value of 5 minutes (being that for every 5 minutes a charge is raised) formatted as mm:ss. I have tried all different combinations of the format but it all boils down to the 11H27 minutes coming from a formula
I am expecting a result of 137.4 but receiving 25,124,682 unless I direct input the time value of 11hrs and 27 minutes.

A: There are more than 24 hours from 02 06 19 17:18 to 03 06 19 18:09.
You need to subtract those values, instead of "adding":
= B5-B3

The result will be given in (fractions of) days. Basic mathematics will get to your result.
See the screenshot below. The formulas are the ones used on line 2.


text:
Q: Including JRE with steam application I have a application that I would like to include the jre with, because I cannot rely on the user having java installed. The program runs on the command line, started up with a .bat file.
What is the most clean, safe, and legal way to include the jre?
The options I have looked at so far are:
Install scripts, launch4j bundling, and literally just including the java install files
I haven't been able to actually get any of these to work with my command line application.
I would prefer if someone could find a way to do this from eclipse but am open to other programs and methods. My product is only for windows and I am using windows, so other use cases may be discarded when posting your answer.

A: Have a look into this: http://launch4j.sourceforge.net
It bundles everything into an .exe


text:
Q: On C# I am getting the CS1061 Error stating ,Object does not have a definition for "Items" and no Extension Method for "Items" Here is my coding.  I have researched this through out the website.  Many people seem to have the same issue, but not related to mine.  I am writing a program to access pictures from my laptop, but this error is not letting me access the Picture Directory.  Any help is highly appreciated!!!
currentDir = fb.SelectedPath; // Get the selected folder by the user;
textBoxD.Text = currentDir;
var dirInfo = new DirectoryInfo(currentDir);
var files = dirInfo.GetFiles().Where(c=>c.Extension.Equals(".jpg") || c.Extension.Equals(".jpeg") || c.Extension.Equals(".bmp") || c.Extension.Equals(".png"));
foreach (var image in files)
{
    object listBoxImages = null;
    //Add Images/Files to the list box
    listBoxImages.Items.Add(image.Name);
}

A: You have two problems. The first, which is the immediate cause of the compilation error is  that listBoxImages is defined as an object. So all it has is methods and properties of object - which does not have Items property.
Secondly, You are assigning null to listBoxImages so even if it had the Items property you'd get a NullReferenceException
I'm assuming you want to initialize it as a ListBox instead. When you do so also make sure to define and initialize it outside of the foreach loop because otherwise it will only contain the last item

In addition you can refactor your linq a bit to use a HashSet of the valid extensions:
var validExtensions = new HashSet<string>(new[] { ".jpg", "jpeg", ".bmp", ".png" });
var files = dirInfo.GetFiles().Where(c => validExtensions.Contains(c.Extension));

HashSet Contains is performed in O(1) so changing from the multiple || statements to using this collection doesn't harm performance and is much more extensible and readable

A: listBoxImages is of type object . Typecast it to the type of collection and use the items property

A: Problem is you are trying to add items to listboxImage that has not been initialized.
currentDir = fb.SelectedPath; // Get the selected folder by the user;
textBoxD.Text = currentDir;
var dirInfo = new DirectoryInfo(currentDir);
var files = dirInfo.GetFiles().Where(c=>c.Extension.Equals(".jpg") || c.Extension.Equals(".jpeg") || c.Extension.Equals(".bmp") || c.Extension.Equals(".png"));

var listBoxImages = new ListBox(); //I think listBoxImages is of type ListBox control
foreach (var image in files)
{
    //Add Images/Files to the list box
    listBoxImages.Items.Add(image.Name);
}


text:
Q: Sort a list of members in ascending and descending order I'm creating a simple database containing students with the following information: first name, last name, personalnumber, study type (permanent or part time student).
If user hits "showasc" the program asks whether to show students in ascending order by their first name or last name.
Managed to sort the members by name, but the problem is that only the names gets sorted while the rest of the information about the student doesn't, it stays in the order it was created. Bare in mind that I'm still very new to programming.
This is the part of the code that sorts the names:
else if(strcmp(command, "showasc") == 0)
{
    char input[15];
    printf("Show in ascendant order by first name or last name?\n ");
    scanf("%s", input);

    struct Student copyOfListOfStudents[20];
    memcpy(&copyOfListOfStudents, &listOfStudents, sizeof(listOfStudents));

    int i, j;
    char s[100];
    for(i=0;i<20;i++)
    {
        for(j=i+1;j<20;j++)
        {
            if(copyOfListOfStudents[i].valid  &&  copyOfListOfStudents[j].valid)
            {
                if(strcmp(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName) > 0)
                {
                    strcpy(s,copyOfListOfStudents[i].firstName);
                    strcpy(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName);
                    strcpy(copyOfListOfStudents[j].firstName,s);
                }
            }
            else
                break;
        }
    }
    printStudents(copyOfListOfStudents);

So for example, if user adds the the following students:

*

*Lol Ipop, 7802034567, Full time

*Anna Banana, 9901024356, Part time

And then wants to show students sorted by first name, this is what happens:

*

*Anna Ipop, 7802034567, Full time

*Lol Banana, 9901024356, Part time

How do I fix this problem?
(I hope that the code I'm showing is sufficient!)

A: You have already identified the problem. In your sorting algorithm, the names get sorted, but the other values are not.
To fix the issue, you need to change this part to swap the whole student struct:
if(strcmp(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName) > 0)
{
    Student tmp;
    memcpy(tmp, copyOfListOfStudents[i], sizeof(Student));
    memcpy(copyOfListOfStudents[i], copyOfListOfStudents[j], sizeof(Student));
    memcpy(copyOfListOfStudents[j], tmp, sizeof(Student));
}

Code is untested...


text:
Q: SQL difference between primary key(x, y) and primary key(x), unique(y) In SQL what is the difference between this
create table marriage (
    person1 int not null references human on delete cascade,
    person2 int not null references human on delete cascade,
    primary key (person1, person2)
);

and this
create table marriage (
    person1 int not null references human on delete cascade,
    person2 int not null references human on delete cascade,
    primary key (person1),
    unique (person2)
);

And does the table with two primary keys prevent this?
marriage:

person1 | person2
   1         2
   2         1

A: The first index is a unique index on two columns: that means that the combination of both should be unique. The rows 1,2 and 2,1 are not violating the index since the index treats them as a set. 1,2 and 1,3 don't violate the index either.
The second sample contains two indexes and both need to be unique. That means that rows with 1,2 and 1,3 violate the index constraints.


text:
Q: How do I create subtasks in Celery I am trying to loop through many buildings in my db. In each building I generate a bill for each apt in that building. This all happens on a scheduled task in Celery on the 25th of each month.  The bill is sent out for the next month. I know I can use chords and groups and other subtasks I am just confused as to how to organize it into one giant working mechanism.  This is what I tried so far (which does not work). I am testing using crontab and a current time just so I can see it run. In production I'll set that date to the 25th of each month.
config.py:
CELERY_TIMEZONE = 'America/New_York'
CELERYBEAT_SCHEDULE = {
    "billing-schedule": {
        "task": "tasks.bill_all_buildings",
        "schedule": crontab(hour=8,minute=41)
    },
}

tasks.py:
@celery.task()
def bill_all_buildings():
    for building in Building.query.all():
        if building.billing_on:
            print 'billing %s' % building.name
            bill_apts_in_building.delay(building)

@celery.task()
def bill_apts_in_building(building):
    for apt in building.apts:
        print 'billing apt %s' % apt.last_name
        create_apt_bill.delay(apt)

@celery.task()
def create_apt_bill(apt):
    money_helpers.bill_next_month(apt)

In the what happens is that bill_all_buildings gets run and then it says:
[2014-01-31 07:28:00,036: DEBUG/MainProcess] Task accepted: tasks.bill_apts_in_building[da7b46f2-e559-4947-9442-bd31329d8d0d] pid:9156

Then nothing happens.


text:
Q: System.IO.Ports.SerialPort and Multithreading I have some SerialPort code that constantly needs to read data from a serial interface (for example COM1). But this seems to be very CPU intensive and if the user moves the window or a lot of data is being displayed to the window (such as the bytes that are received over the serial line) then communication gets messed up.
Considering the following code:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{

byte[] buffer = new byte[port.ReadBufferSize];

var count = 0;

try
{
    count = port.Read(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
    Console.Write(ex.ToString());
}

if (count == 0)
    return;

//Pass the data to the IDataCollector, if response != null an entire frame has been received

var response = collector.Collect(buffer.GetSubByteArray(0, count));

if (response != null)
{
    this.OnDataReceived(response);
}

The code needs to be collected as the stream of data is constant
and the data has to be analyzed for (frames/packets).
    port = new SerialPort();

    //Port configuration code here...

    this.collector = dataCollector;

    //Event handlers
    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    port.Open();

If there is no user interaction and nothing being added to the window,
this works fine but as soon as there is interaction communication really gets messed up.
Timeouts occur etc....
For example, this messes everything up:
Dispatcher.BeginInvoke(new Action(() =>
{
  var builder = new StringBuilder();
  foreach (var r in data)
  {
      builder.AppendFormat("0x{0:X} ", r);
  }

  builder.Append("\n\n");

  txtHexDump.AppendText(builder.ToString());

  txtHexDump.ScrollToEnd();

}),System.Windows.Threading.DispatcherPriority.ContextIdle);
});

But even simple calls to log4net cause problems.
Are there any best practices to optimize SerialPort communication
or can someone tell me what I'm doing wrong...
Update:
In case the above didn't make much sence. I made a very simple (and stupid) little example:
class Program
{
    static void Main(string[] args)
    {
        var server = new BackgroundWorker();
        server.DoWork += new DoWorkEventHandler(server_DoWork);
        server.RunWorkerAsync();

        var port = new SerialPort();
        port.PortName = "COM2";
        port.Open();
        string input = "";

        Console.WriteLine("Client on COM2: {0}", Thread.CurrentThread.ManagedThreadId);
        while (input != "/quit")
        {
            input = Console.ReadLine();
            if (input != "/quit")
            {
                var data = ASCIIEncoding.ASCII.GetBytes(input);
                port.Write(data, 0, data.Length);
            }
        }

        port.Close();
        port.Dispose();
    }

    static void server_DoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine("Listening on COM1: {0}", Thread.CurrentThread.ManagedThreadId);
        var port = new SerialPort();
        port.PortName = "COM1";
        port.Open();

        port.ReceivedBytesThreshold = 15;
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        var port = (SerialPort)sender;
        int count = 0;
        byte[] buffer = new byte[port.ReadBufferSize];
        count = ((SerialPort)sender).Read(buffer, 0, buffer.Length);

        string echo = ASCIIEncoding.ASCII.GetString(buffer,0,count);
        Console.WriteLine("-->{1} {0}", echo, Thread.CurrentThread.ManagedThreadId);
    }
}

The result might look like this:
Listening on COM1: 6
Client on COM2: 10
This is some sample data that I send
---> 6 This is some sample data that I send
So reading the data from the port happens on the main thread....
Might this be part of what's causing my problems?

A: Your last conclusion, that the event runs on the Main thread, may not be true for Windows App. Don't test this in a Console.
The proper way to tune this is:

*

*set a large enough buffer, although the minimum 4096 is usually Ok

*set the ReceivedBytesThreshold as high as tolerable (and do it before the Open())

*do as little as possible in the Received event, pass the
data to a Queue or MemoryStream if you need more time

A: You should rewrite port_DataReceived procedure to read data until port.BytesToRead is greater then zero, like this:
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
        var port = (SerialPort)sender;
        while (port.BytesToRead > 0)
        {
            int byte_count = port.BytesToRead;
            byte[] buffer = new byte[byte_count];

            int read_count = port.Read(buffer, 0, byte_count);

            // PROCESS DATA HERE

        }
}

Also I would recommend you to just insert data in queue list in procedure port_DataReceived, and perform data processing in separate thread.

A: I am surprised no one caught this. The SerialPort class utilizes its own thread when using the DataReceived event. This means that if the subscriber, for example, is accessing any Form elements, then it must be done so with either an Invoke, or BeginInvoke method(s). Otherwise, you end up with a cross thread operation. In older versions of .net, this would go along unnoticed with unpredictable behaviour (depending on the CPU cores in the PC) and in later versions, should raise an exception.

A: The classic solution is to have a FIFO buffer. Ensure that the size of the FIFO is large enough to handle any critical case where there is a lot of input and the processor block is being taken up.
You could even have a 2-buffer system:
--->|Reader|-->FIFO-->|Processor|--->FIFO2--->|Displayer|


text:
Q: Bash script transfer to Python - copy logs from server to another remote server I have done my easy script in bash - this script should transfer the file with the specific new name from server 1 to remote server 2.
Can someone help with this and transfer all script to Python.
 #!/bin/bash

path=/opt/log #Im in dir /opt/log
fdate=$(date +%Y%m%d -d "-1 day") # yesterday date
file=maillog-$fdate     # log from yesterday which will be transfer to remote server
cp $path/$file /tmp/$HOSTNAME-$file  # copy $file to /tmp with the specific name of $HOSTNAME + $File name
gzip /tmp/$HOSTNAME-$file      # ZIP the file

rserver=hansus@hansus.edu.net    # remote server
rpath=/opt/log/maillog # remote path

scp /tmp/$HOSTNAME-$file.gz $rserver:$rpath # copy the file to remote server to remote path

rm /tmp/$HOSTNAME-$file.gz # clean the /tmp dir
 #Done

A: There are several solutions to this.
One option is unison:
http://xmodulo.com/synchronize-files-between-two-servers.html
The rsync solution:
You will need to ssh into one of the servers first (this should be trivial). Once in you can run this.
rsync -rtlzv --ignore-errors -e ssh . username@hostname:/path/to/directory

from: http://darcynorman.net/2009/01/07/how-i-move-stuff-between-servers-with-rsync/
The scp solution:
I actually think this is the most elegant way because you do not have to ssh in first. Somethibng like this:
nohup scp alice@source:/the/answer/of/all bob@target.example.com:/var/tmp/42 &

from: https://unix.stackexchange.com/questions/65116/does-a-scp-transfer-close-when-i-close-the-shell


text:
Q: SwiftUI - Created a multiline textfield using axis: .vertical and onSubmit won't work now So basically I created a multiline textField, but pressing onSubmit won't work at all, I rather it submit when double pressing return or something similar.
if there is a way to avoid collapsing the keyboard when submitting instead of using multiline I would be grateful to be told how :)

A: This is the workaround that I've used:
struct SwiftUIView: View {

    @State var text: String = ""

    var body: some View {
        TextField("text", text: $text, axis: .vertical)
            .frame(width: 200, height: 200)
            .multilineTextAlignment(.leading)
            .textFieldStyle(.roundedBorder)
            .font(.title)
            .onChange(of: text) { newValue in
                guard let newValueLastChar = newValue.last else { return }
                if newValueLastChar == "\n" {
                    text.removeLast()
                    hideKeyboard()
                }
            }
    }
}

Being hideKeyboard a function defined in an extension of View:
extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}


text:
Q: Increasing number part of UIImageView variable in a for loop? I have a three UIImageView variables called myPicture1, myPicture2 and myPicture3. In a for loop I am trying to increase the number at the end of myPicture by 1 so that I can assign a random image to each of the three variables. Here is the code below :
for (i=0; i<3; i++) {

int g = arc4random() % 19;

NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];

UIImage *picture = [UIImage imageNamed:imagename];

 UIImageView imageView = [[UIImageView alloc] initWithImage : picture];

 self.myPicture1 = imageView; **This is where I want myPicture to increase to myPicture 2 and then 3 **

}

Is this possible ?
Thanks all,
Martin

A: well, I think you're approaching this in a kinda awkward way.
probably the best way to do that is to have your UIImageViews stored in an NSArray.
So in your class declaration, instead of
@property (nonatomic, retain) UIImageView *myPicture1;
@property (nonatomic, retain) UIImageView *myPicture2;
@property (nonatomic, retain) UIImageView *myPicture3;

you would have
@property (nonatomic, retain) NSArray *myPictures;

And then you create them like this:
NSMutableArray *myTempArray = [NSMutableArray arrayWithCapacity:3];
for (i=0; i<3; i++)
{
    int g = arc4random() % 19;

    NSString *imagename = [NSString stringWithFormat:@"image%d.jpg",g];
    UIImage *picture = [UIImage imageNamed:imagename];

    UIImageView imageView = [[UIImageView alloc] initWithImage : picture];
    [myTempArray addObject: imageView];
    [imageView release];
}
self.myPictures = [NSArray arrayWithArray: myTempArray];


text:
Q: Error while running configure. Halting the installation I'm trying to update Ruby via RVM to 1.9.3-p327. After typing rvm install 1.9.3-p327, I get this:
    No binary rubies available for: downloads/ruby-1.9.3-p327.
Continuing with compilation. Please read 'rvm mount' to get more information on binary rubies.
Installing Ruby from source to: /usr/local/rvm/rubies/ruby-1.9.3-p327, this may take a while depending on your cpu(s)...
ruby-1.9.3-p327 - #downloading ruby-1.9.3-p327, this may take a while depending on your connection...
ruby-1.9.3-p327 - #extracted to /usr/local/rvm/src/ruby-1.9.3-p327 (already extracted)
ruby-1.9.3-p327 - #configuring
Error running 'env LDFLAGS=-L/opt/sm/pkg/active/lib CFLAGS=-I/opt/sm/pkg/active/include CPATH=/opt/sm/pkg/active/include ./configure --enable-shared --disable-install-doc --prefix=/usr/local/rvm/rubies/ruby-1.9.3-p327 --with-opt-dir=/usr/local/rvm/usr', please read /usr/local/rvm/log/ruby-1.9.3-p327/configure.log
There has been an error while running configure. Halting the installation.

Then, I check the config log in ruby 1.9.3-p327/configure.log in which I see this:
[2012-12-24 22:39:14] env LDFLAGS=-L/opt/sm/pkg/active/lib CFLAGS=-       I/opt/sm/pkg/active/include CPATH=/opt/sm/pkg/active/include ./configure --enable-shared --disable-install-doc --prefix=/usr/local/rvm/rubies/ruby-1.9.3-p327 --with-opt-dir=/usr/local/rvm/usr
checking build system type... x86_64-apple-darwin11.4.2
checking host system type... x86_64-apple-darwin11.4.2
checking target system type... x86_64-apple-darwin11.4.2
checking whether the C compiler works... no
configure: error: in `/usr/local/rvm/src/ruby-1.9.3-p327':
configure: error: C compiler cannot create executables
See `config.log' for more details

I've install the newest Xcode 4.5.2 as well as install CLT via Xcode..It seems like the C compiler doesnt work and I dont know how to fix it.any suggestions?

A: check out this RVM installation page: https://rvm.io/rvm/install/. This might help you out.


text:
Q: Easiest way to load variables from a text file I have a program where I want to load Variables from a text file to use them as default variables.
The text file should look like this:
Name=No Name

Age=8

Gender=male

etc.

Is there a simpler way and if not how do I do that in the place with the question marks?
My Code look like this:
int Age;
std::string Name;
bool male;

if(f.is_open())
{
    while (!f.eof())
    {

        getline(f, line);
        if (line.find("Name=") == std::string::npos)
        {
            Name=?????;
            continue;
        }
        else if (line.find("Gender=") == std::string::npos)
        {
            if(????? == "true"); then
               male=true;
            else
               male=false;

            continue;
        }
        else if (line.find("Age=") == std::string::npos)
        {
            Age=?????;
            continue;
        }
        //etc. ...
}
f.close();

A:
Is there a simpler way?

You could use a serialization library, like cereal or Boost, as @JesperJuhl suggested.
However, I would strongly suggest to take a step back, and review your approach. You are asking for an improvement, but you don't have a good solution at this point, because Why is iostream::eof inside a loop condition considered wrong?
As I had written here, I will use std::getline() as the loop condition instead of ios::eof(), in order to parse the file, line by line.

How do I do that in the place with the question marks?

Then, for every line, I will tokenize it, based on a delimiter (equal sign in your case), in order to extract two tokens, the name of the variable and its default value. Read more about it in Parse (split) a string in C++ using string delimiter (standard C++)
Afterwards, I would use an if-else approach (You could use a switch statement instead) to check the name of the variable, and assign its default value to the actual variables of the program.
Full code example:
#include <iostream>
#include <string>
#include <fstream>

int main(void) {
  std::string defaultName, gender;
  int age;

  std::ifstream infile("mytextfile.txt");
  std::string line, varName, defaultValue;
  std::string delimiter = "=";
  while (std::getline(infile, line)) {
    varName = line.substr(0, line.find(delimiter));
    defaultValue = line.substr(line.find(delimiter) + 1);
    if(varName == "Name") {
      defaultName = defaultValue;
      continue;
    } else if(varName == "Age") {
      age = std::stoi(defaultValue);
      continue;
    } else if(varName == "Gender") {
      gender = defaultValue;
      continue;
    } else {
      std::cout << "Unknown entry: " << line << std::endl;
    }
  }

  std::cout << defaultName << ", " << age << ", " << gender << std::endl;

  return 0;
}

Output:
No Name, 8, male

A: If you feel a need to write it yourself instead of using a ready library, you could use a std::unordered_map<> and add some streaming and extraction support around it. Here's an example with comments in the code:
#include <string>
#include <unordered_map>

class KeyValue { //        Key          Value
    std::unordered_map<std::string, std::string> m_kv{};

public:
    // at() is used to get a reference to a Value given the supplied Key. It uses
    // the function with the same name in the unordered_map.

    inline std::string& at(const std::string& Key) { return m_kv.at(Key); }
    inline const std::string& at(const std::string& Key) const { return m_kv.at(Key); }

    // The "as<T>" function below is used to extract values from the map.
    // The exact version of the function that will be used depends on the type
    // you want to extract from the string. Explicit specializations of the function
    // are declared outside the class.

    // A generic conversion function to anything that can be constructed from a std::string
    template<typename T>
    T as(const std::string& Key) const {
        return at(Key);
    }

    // A function to extract directly into a variable using the proper as<T>
    template<typename T>
    void extract_to(T& var, const std::string& Key) const {
        var = as<T>(Key);
    }

    // A friend function to read from an input stream (like an open file) and
    // populate the unordered_map.
    friend std::istream& operator>>(std::istream&, KeyValue&);
};

// Explicit specializations of KeyValue::as<T>()

// floats
template<>
float KeyValue::as(const std::string& Key) const {
    return std::stof(at(Key));
}

template<>
double KeyValue::as(const std::string& Key) const {
    return std::stod(at(Key));
}

template<>
long double KeyValue::as(const std::string& Key) const {
    return std::stold(at(Key));
}
// signed integers
template<>
int KeyValue::as(const std::string& Key) const {
    return std::stoi(at(Key));
}

template<>
long KeyValue::as(const std::string& Key) const {
    return std::stol(at(Key));
}

template<>
long long KeyValue::as(const std::string& Key) const {
    return std::stoll(at(Key));
}
// unsigned integers
template<>
unsigned KeyValue::as(const std::string& Key) const {
    return std::stoul(at(Key));
}

template<>
unsigned long KeyValue::as(const std::string& Key) const {
    return std::stoul(at(Key));
}

template<>
unsigned long long KeyValue::as(const std::string& Key) const {
    return std::stoull(at(Key));
}
// bool
template<>
bool KeyValue::as(const std::string& Key) const {
    const std::string& val = at(Key);
    if(val=="true" || val=="1") return true;
    else if(val=="false" || val=="0") return false;
    throw std::range_error("\"" + Key + "\" is neither true nor false");
}

// the friend function that extracts key value strings from a stream
std::istream& operator>>(std::istream& is, KeyValue& kv) {
    std::string line;

    // read one line at a time
    while(std::getline(is, line)) {
        auto pos = line.find('=');
        if(pos == std::string::npos || pos == 0) {
            // if '=' was not found (or found at pos 0), set the failbit on the stream
            is.setstate(std::ios::failbit);
        } else {
            // if '=' was found, put the Key and Value in the map by
            // using substr() to split the line where the '=' was found
            kv.m_kv.emplace(line.substr(0, pos), line.substr(pos + 1));
        }
    }
    return is;
}

With that in place, you can read a file and populate the variables that you've preferably put in a class / struct. Example:
#include <fstream>

struct Variables {
    std::string Name{};
    unsigned int Age{};
    std::string Gender{};
    double PI{};
    bool Hungry{};
    bool Sad{};

    Variables(const std::string& filename) {
        std::ifstream is(filename);
        if(is) {
            KeyValue tmp;
            is >> tmp; // stream the whole file into tmp

            // extract values
            tmp.extract_to(Name, "Name");
            tmp.extract_to(Age, "Age");
            tmp.extract_to(Gender, "Gender");
            tmp.extract_to(PI, "PI");
            tmp.extract_to(Hungry, "Hungry");
            tmp.extract_to(Sad, "Sad");
        } else throw std::runtime_error("Could not read \""+filename+"\".");
    }
};

Example data file (vars.dat):
Name=No name
Age=8
Gender=male
PI=3.14159
Hungry=true
Sad=false

...and a main example::
#include <iostream>

int main() {
    try {
        Variables var("vars.dat"); // open file and populate variables

        std::cout << std::boolalpha
            << "Name:   " << var.Name << "\n"
            << "Age:    " << var.Age << "\n"
            << "Gender: " << var.Gender << "\n"
            << "PI:     " << var.PI << "\n"
            << "Hungry: " << var.Hungry << "\n"
            << "Sad:    " << var.Sad << "\n";

    } catch(const std::exception& ex) {
        std::cerr << ex.what() << "\n";
    }
}

A: I tried to simplify the solution of @Ted Lyngmo:
... I think it is not the fastest way and not the best, but it is more simple and more short:
#include <sstream>

class loadVars
{
public:
    std::string file;
    loadVars() { }

    //Input ->
    loadVars(std::string Text) {
        this->setFile(Text);
    }

    loadVars(std::istream& is) {
        this->setFile(is);
    }

    friend void operator>>(std::istream& is, loadVars& lv) {
        lv.file = std::string((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
    }

    void setFile(std::string Text) {
        this->file = Text;
    }

    void setFile(std::istream& is) {
        this->file = std::string((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
    }
    //<-

    std::string extract_to_first(std::string to) {
        std::string line;
        std::stringstream s_string = std::stringstream(this->file);

        while (std::getline(s_string, line)) {
            if(line.find("=") != std::string::npos) {
                if(line.substr(0,line.find("=")) == to) {
                    return line.substr(line.find("=")+1);
                }
            }
        }
        return "-1";
    }

};

A: I would not reinvent this.  As suggested, libraries for serialization exist.  Consider Boost.PropertyTree as an example and Boost can be helpful to learn in general.