text:
Q: HRESULT E_FAIL error when doing batch geocoding in ArcObjects I am trying to write a batch geocoding application in ArcObjects/C# and keep getting the meaningless

"Error HRESULT E_FAIL has been returned from a call to a COM component"

error (error code -2147467259), and I can't figure out what's causing it.
Any tips on how to figure out what the error is? I am running ArcGIS 9.3.1 SP 2. Below is the code that I have. I get the error on the last line:

IRecordSet resultRecordSet =
  geocodeServer.GeocodeAddresses((IRecordSet)recordSetInit,
  addressProperties, null);

Here is the full code:

        IGeocodeServer geocodeServer = null;
        IGISServerConnection conn = null;
        conn = new GISServerConnection();
        conn.Connect("mandarin");
        IServerObjectManager som = conn.ServerObjectManager;

        IServerContext geocoderContext = som.CreateServerContext("StateCntyLoc", "GeocodeServer");
        geocodeServer = (IGeocodeServer)geocoderContext.ServerObject;
        IGeocodeServerObjects gom = (IGeocodeServerObjects)geocodeServer;

        IGeocodingProperties locProp = (IGeocodingProperties)gom.AddressLocator;
        locProp.SideOffset = 0;
        locProp.EndOffset = 0;

        IServerContext gdbContext = som.CreateServerContext("MF", "GeodataServer");
        IGeoDataServer geoDataServer = (IGeoDataServer)gdbContext.ServerObject;

        IGeoDataServerObjects gdsObjects = (IGeoDataServerObjects)geoDataServer;
        IWorkspace gdsWS = gdsObjects.DefaultWorkingWorkspace;
        IFeatureWorkspace featWS = (IFeatureWorkspace)gdsWS;

        ITable addressTable = featWS.OpenTable("FACT_CRASH_INPUT");
        IFields fields = geocodeServer.GetAddressFields();

        // The Address Field Mapping is key = Locator Field Names and value = RecordSet Field Names
        IPropertySet addressProperties = (IPropertySet)gdbContext.CreateObject("esriSystem.PropertySet");
        addressProperties.SetProperty(fields.get_Field(0).Name, "INTERSECTION");
        addressProperties.SetProperty(fields.get_Field(1).Name, "CNTY_CD");
        IRecordSetInit recordSetInit = (IRecordSetInit)gdbContext.CreateObject("esriGeodatabase.RecordSet");
        recordSetInit.SetSourceTable(addressTable, null);

        IRecordSet resultRecordSet = geocodeServer.GeocodeAddresses((IRecordSet)recordSetInit, addressProperties, null);

Now if I put the table in a file geodatabase on my local machine and do the batch geocoding against ArcGS Online, I get back a record set.
        IAoInitialize ao = new AoInitialize();
        ao.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);

        IGeocodeServer geocodeServer = null;
        IAGSServerConnection agsServerConnection = null;

        IPropertySet connectionProperties = new PropertySet();
        connectionProperties.SetProperty("Url", "http://tasks.arcgisonline.com/arcgis/services");

        IAGSServerConnectionFactory serverConnectionFactory = new AGSServerConnectionFactory();
        agsServerConnection = serverConnectionFactory.Open(connectionProperties, 0);

        IAGSEnumServerObjectName serverObjectNames = agsServerConnection.ServerObjectNames;
        serverObjectNames.Reset();

        IName name;
        IAGSServerObject serverObject = null;
        IAGSServerObjectName serverObjectName = serverObjectNames.Next();
        while (serverObjectName != null)
        {
            if (serverObjectName.Name == "Locators/TA_Address_NA" && serverObjectName.Type == "GeocodeServer")
            {
                name = serverObjectName as IName;
                serverObject = name.Open() as IAGSServerObject;
                if (serverObject as IGeocodeServer != null)
                {
                    geocodeServer = serverObject as IGeocodeServer;
                    break;
                }
            }
            serverObjectName = serverObjectNames.Next();
        }

        IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
        IWorkspace workspace = workspaceFactory.OpenFromFile(@"C:\Users\marni\Desktop\TestGC.gdb", 0);
        IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
        ITable addressTable = featureWorkspace.OpenTable("FACT_CRASH_INPUT");
        IFields fields = geocodeServer.GetAddressFields();

        // The Address Field Mapping is key = Locator Field Names and value = RecordSet Field Names
        IPropertySet addressProperties = new PropertySet();
        addressProperties.SetProperty(fields.get_Field(0).Name, "INTERSECTION");
        addressProperties.SetProperty(fields.get_Field(1).Name, "CITY_CD");
        addressProperties.SetProperty(fields.get_Field(2).Name, "CNTY_CD");
        addressProperties.SetProperty(fields.get_Field(3).Name, DBNull.Value);
        IRecordSetInit recordSetInit = (IRecordSetInit)new RecordSet();
        recordSetInit.SetSourceTable(addressTable, null);

        IRecordSet resultRecordSet = geocodeServer.GeocodeAddresses((IRecordSet)recordSetInit, addressProperties, null);


text:
Q: Weapon w = new Weapon(42); Isso está correto? Teve esta questão numa prova de programação
Considere a classe Abstrata Weapon. A linha de código abaixo apresenta algum erro? Justifique sua resposta.
Weapon w = new Weapon(42);

Essa é a minha resposta e o prof nao considerou nada
sim, não pode ter valor dentro de Weapon
o correto seria como está aqui em baixo /
Weapon w = new Weapon( );

A: Na verdade os dois modos estão incorretos pois uma classe abstrata não pode ser instanciada. Uma classe abstrata (no caso Weapon) é somente um modelo de classe que outras classes herdarão.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing model object in custom log and save it to the database using jdbc appender log4j2 I am using log4j2 jdbc appender for logging in my database. My log4j2 properties file currently is:
customLevel.DIAG =350

# JDBC appender
appender.db.type = Jdbc
appender.db.name = databaseAppender
appender.db.tableName = db_name.test
appender.db.cf.type = ConnectionFactory
appender.db.cf.class = com.myproject.ConnectionFactory
appender.db.cf.method = getConnection
appender.db.col2.type = Column
appender.db.col2.name = message
appender.db.col2.pattern = %m
appender.db.col3.type = Column
appender.db.col3.name = category
appender.db.col3.pattern = %M{1}
appender.db.col4.type = Column
appender.db.col4.name = timestamp
appender.db.col4.isEventTimestamp = true
appender.db.col5.type = Column
appender.db.col5.name = log_level
appender.db.col5.pattern = %-5p
appender.db.filter.threshold.type = ThresholdFilter
appender.db.filter.threshold.level = diag
appender.db.filter.threshold.onMatch = Accept
appender.db.filter.threshold.onMismatch = Deny

The information gets successfully stored in database when I log my events using:
LOG.log(Level.forName("DIAG", 350), "a diagnostic message");

But now I have to store multiple kinds of messages (like quantity, ordered to whom) for which I have to make a model.
public class LogModel {

String quantity, orderedTo, amount;

public LogModel(String quantity, String orderedTo, String amount) {
    this.quantity = quantity;
    this.orderedTo = orderedTo;
    this.amount = amount;
}

public String getQuantity() {
    return quantity;
}

public void setQuantity(String quantity) {
    this.quantity = quantity;
}

public String getOrderedTo() {
    return orderedTo;
}

public void setOrderedTo(String orderedTo) {
    this.orderedTo = orderedTo;
}

public String getAmount() {
    return amount;
}

public void setAmount(String amount) {
    this.amount = amount;
}
}

I have defined the column fields in my mysql database accordingly for the log. My question is how can I pass this model object to the jdbc appender so that it can map the data to my database column.
Another thing I tried (that didn't required making model) was using ThreadContext as:
ThreadContext.put("amount", amount);

And accordingly in log4j2 properties file:
appender.db.col3.type = Column
appender.db.col3.name = amount
appender.db.col3.pattern = %X{amount}

But is this the only option that I have? Like I have to clear the threadContext everytime right or else the value in threadcontext is working for another of my log.
I am actually rooting to work with model object if possible. Something like this:
LogModel logModel = new LogModel("100", "Mr. John", "12345");
LOG.log(Level.forName("DIAG", 350), logModel);

Your guidance will be much appreciated. Thanks.


text:
Q: Magento Plugin not working - Soap I'm trying to get an extension to work in Magento 1.7 but I get this system.log error:
ERR (3): Notice: Use of undefined constant SOAP_1_2 - assumed 'SOAP_1_2'  in /var/www/vhosts/
DEBUG (7): Error fetching parcelshops
2015-01-22T20:09:42+00:00
DEBUG (7): SOAP extension is not loaded.
2015-01-22T20:10:01+00:00
Is it because the soap is not enable on the server?
Best regards
Christian

A: It looks like the Soap extension isn't enabled on your server.
Create a "phpinfo.php" file in your Magento root folder, and add this:
<?php echo phpinfo(); ?>

You can check there if Soap is enabled or not.

A: Also, it is possible to check directly in the script if the specific extension (in this case - soap) was enabled:
$arrLoadedExtensions = array_map('strtolower', get_loaded_extensions());
$booLoaded = in_array('soap', $arrLoadedExtensions);


text:
Q: Is this limit of sums of product over the primes bounded by the square root function? Is it true that the square root always bounds this sum:
$$\sqrt{n} \ge \limsup_{n \rightarrow \infty} \,\Biggr\lvert \sum_{m=1}^{n} \prod_{k \in \mathbb{P}}^{\infty} \Biggl(1-2 \biggl(\frac{\sin(\pi\,m)}{k \sin(\pi\frac{m}{k})}\biggr)^2\Biggr)\cdot\Biggl(1-\biggl(\frac{\sin(\pi\, m)}{k^2 \sin(\pi\frac{m}{k^2})} \biggr)^2\Biggr) \Biggl \lvert$$
I would really appreciate an answer, as I might use this for a paper I am writing (In the case that this is true). And I do hope that you can help me with this. $$$$
(If this is (not) true, could you please explain why)

A: Let
$$\sigma(m,p)=\begin{cases}1&p\mid m\\0&p\nmid m\end{cases}$$
First note that
\begin{align}
\prod_{p \in \mathbb{P}}^{\infty} (1-2 \sigma(m,p))&=\prod_{p\mid m} (-1)\\
\prod_{p \in \mathbb{P}}^{\infty}(1-\sigma(m,p^2))&=|\mu(m)|
\end{align}
Consequently,
$$\prod_{p \in \mathbb{P}}^{\infty} (1-2 \sigma(m,p))(1-\sigma(m,p^2))=\mu(m)$$
the Möbius function.
Then
$$\sum_{m=1}^{n} \prod_{p \in \mathbb{P}}^{\infty}(1-2 \sigma(m,p))(1-\sigma(m,p^2))=\sum_{m=1}^{n}\mu(m)=M(n)$$
is the Mertens function.
So you are asking $|M(n)|\leq\sqrt n$ as $n\to+\infty$, which is not known today, that's the Mertens Conjecture.


text:
Q: Paypal IPN message queued using IPN Simulator, my listener (in sandbox) is working fine.
then I submit the order by the html form.
I noticed that all the IPN messages were "queued" (from the IPN history)
what make this happen? And How can I solve this?
I read some old threads that same case was caused by Paypal Server. Can anyone help to advise on this?  Thanks!

A: This shouldn't happen often, but it could be that the IPN server is simply backed up so the IPNs are waiting in the queue and will be sent as soon as the servers catch up.
Another thing that could cause it, though, is if you have lots of failures happening with your IPN script.  In such cases PayPal may place you on a slower queue because they don't want to waste server resources if you're failing a lot.  You should get notifications about that if this sort of thing is happening, though, and eventually they would just turn IPN off altogether until you get it fixed and re-enable it.


text:
Q: powershell -> SOAP request with additional Headers Hi i need a help with proper soap request. I tried few ways do it but no luck.
Need to generate such soap request:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Header><Action xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:env="http://www.w3.org/2003/05/soap-envelope" env:mustUnderstand="true"/><MessageID xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">uuid:..............</MessageID><ReplyTo xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing"><Address>http://www.w3.org/2004/08/addressing/anonymous</Address></ReplyTo><To xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:env="http://www.w3.org/2003/05/soap-envelope" env:mustUnderstand="true">host_url</To><wsse:Security xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" env:mustUnderstand="true"><wsse:UsernameToken><wsse:Username xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">$login</wsse:Username><wsse:Password xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" wsse:Type="http://docs.oas
is-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">$password</wsse:Password></wsse:UsernameToken></wsse:Security></soap:Header>
<soap:Body>
      ................
   </soap:Body>
</soap:Envelope>

i stucked on this getting iis internal error 500:
(...)
write-host "Sending SOAP Request To Server: $URL"
        $soapWebRequest = [System.Net.WebRequest]::Create($URL)
        $soapWebRequest.Headers.Add("SOAPAction","`"MethodName`"")
        $soapWebRequest.ContentType = "application/soap+xml;charset=`"utf-8`";action=`"host/MethodName`""

        $soapWebRequest.Method      = "POST"

        write-host "Initiating Send."
        $requestStream = $soapWebRequest.GetRequestStream()
        $SOAPRequest.Save($requestStream)
        $requestStream.Close()

        write-host "Send Complete, Waiting For Response."
        $resp = $soapWebRequest.GetResponse()
        $responseStream = $resp.GetResponseStream()
        $soapReader = [System.IO.StreamReader]($responseStream)
        $ReturnXml = [Xml] $soapReader.ReadToEnd()
        $responseStream.Close()
        write-host "Response Received."
        return $ReturnXml

}

$url = 'host.asmx'
$soap = [xml]@"
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:flow="host">
   <soap:Header/>
   <soap:Body>
      .....
   </soap:Body>
</soap:Envelope>
"@
$ret = Execute-SOAPRequest $soap $url; $ret | Export-Clixml  "test-$(Get-date -f yyyy-MM-dd-mm-ss).xml";

A: Your headers seem odd mixing up escaped quotes you actually don't need.
Try replacing
 $soapWebRequest.Headers.Add("SOAPAction","`"MethodName`"")

by
 $soapWebRequest.Headers.Add("SOAPAction","MethodName")

as well as
 $soapWebRequest.ContentType = "application/soap+xml;charset=`"utf-8`";action=`"host/MethodName`""

by
$soapWebRequest.ContentType = "application/soap+xml; charset=utf-8";


text:
Q: How to run a script on each folder in a drive? I am working on a data cleanup in a network drive. The drive has 1000+ folders, and those folders have several subfolders. The script that I got from G4G (seen below) prompts me to select a folder. I can click on one of my 1000+ folders, and the data is cleaned up properly (duplicates are deleted). However, I'd like to loop the command through the whole drive to avoid clicking on folders for hours. I cannot select the drive as my folder because duplicate file names between the first folders in the drive should not be considered duplicates.
Example:
Z:/Folder1 and Z:/Folder2 both have several files named text.txt, immediately inside of the folders and within the subdirectories of the folders. Folder1 and Folder2, among all text.txt files immediately inside and within its subdirectories, should each be left with one text.txt. If the current script is applied to Folder1 and Folder2 individually, then the desired result of one text.txt file existing in Folder1 and one existing in Folder2 is accomplished. If the script is applied to the Z: drive, then between Folder1 and Folder2, there would only be one text.txt, and one of the folders would be without a file named text.txt.
How can I apply this script to each first folder in the drive without having to manually click on each folder?
from tkinter.filedialog import askdirectory

# Importing required libraries.
from tkinter import Tk
import os
import hashlib
from pathlib import Path

# We don't want the GUI window of
# tkinter to be appearing on our screen
Tk().withdraw()

# Dialog box for selecting a folder.
file_path = askdirectory(title="Select a folder")

# Listing out all the files
# inside our root folder.
list_of_files = os.walk(file_path)

# In order to detect the duplicate
# files we are going to define an empty dictionary.
unique_files = dict()

for root, folders, files in list_of_files:

    # Running a for loop on all the files
    for file in files:

        # Finding complete file path
        file_path = Path(os.path.join(root, file))

        # Converting all the content of
        # our file into md5 hash.
        Hash_file = hashlib.md5(open(file_path, 'rb').read()).hexdigest()

        # If file hash has already #
        # been added we'll simply delete that file
        if Hash_file not in unique_files:
            unique_files[Hash_file] = file_path
        else:
            if file.endswith((".txt",".bmp")):
                os.remove(file_path)
                print(f"{file_path} has been deleted")

A: You can change the script as below.
Basically below script gets absolute path of all the directories in the current directory, and feeds them one by one for cleanup.
from tkinter.filedialog import askdirectory

# Importing required libraries.
from tkinter import Tk
import os
import hashlib
from pathlib import Path

# We don't want the GUI window of
# tkinter to be appearing on our screen
Tk().withdraw()

# Dialog box for selecting a folder.
file_paths = [os.path.abspath(i) for i in os.listdir() if os.path.isdir(i)]

for file_path in file_paths:
    # Listing out all the files
    # inside our root folder.
    list_of_files = os.walk(file_path)

    # In order to detect the duplicate
    # files we are going to define an empty dictionary.
    unique_files = dict()

    for root, folders, files in list_of_files:

        # Running a for loop on all the files
        for file in files:

            # Finding complete file path
            file_path = Path(os.path.join(root, file))

            # Converting all the content of
            # our file into md5 hash.
            Hash_file = hashlib.md5(open(file_path, 'rb').read()).hexdigest()

            # If file hash has already #
            # been added we'll simply delete that file
            if Hash_file not in unique_files:
                unique_files[Hash_file] = file_path
            else:
                if file.endswith((".txt",".bmp")):
                    os.remove(file_path)
                    print(f"{file_path} has been deleted")


text:
Q: How can I make PCManFM open plain text files with Leafpad by default in Lubuntu? When I'm using PCManFM, I sometimes do the following. I right-click in an empty place in ~/, and choose Make new... --> Empty File. I type some text in it, like 'blabalballabl', and then I save it, e.g., as test.
Now, I double-click this file. Leafpad won't open the file, but instead PCManFM will say that the file is executable. It then asks if I want to execute the file or not. I don't want this to happen, I just want Leafpad to open the file. Right-clicking the file, then changing the default application to open this type of files doesn't help.
Is there any way to force PCManFM to open files like these with Leafpad by default?
I'm using Lubuntu 11.10 32 bit.

PCManFM asks to execute the file

Changing the default program to open the file doesn't help.

mimeapps.list looks OK; text/plain should be opened by Leafpad.

A: Its perhaps worth checking that if you have a mimetype list that its defined correctly:

In the same folder - try removing/renaming any custom leafpad.desktop file just in-case it is due to an error in that definition.
Logout and login for changes to take effect.

A: This is a common problem when the file is executable. As far as I know, there is no fix other than removing its executable flag:

*

*chmod -x [yourfile], or

*Right-click > Properties > Permissions > Uncheck "Make the file executable".

However, this fix will probably not work if the file is on a filesystem that does not support POSIX-like file permissions (e.g. NTFS, vfat, network shares, etc...).

A: I have the solution!: Just add
,noexec

to the options of the ntfs line of /etc/fstab


text:
Q: angular 4 crud insert data to mysql db with php hi guys why my data save in db twice ? if i submit form the , form data will be saved but it creats another empety row in db too why ?
result is look like this :
name - username - email - number
 -   -    -    -
my user service
import {Injectable} from "@angular/core";
import {User} from "./user";
import {Http} from "@angular/http";
import "rxjs";
import { Observable } from "rxjs"

@Injectable()
export class UserService {

    constructor(private _http: Http) {
    }

    create(user) {
        return this._http.post('http://localhost/api/create.php', user).map(()=>"")
    }

user.component.ts
import {Component, OnInit} from "@angular/core";
import {User} from "./user";
import {UserService} from "./user.service";
import {isNumber} from "util";

@Component({
    selector: 'app-user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

    // users: Array<User> = [
    //     new User(1, 'fist', 'last', 'aa@aa.com'),
    //     new User(2, 'second', '2last', 'aa@aa.com'),
    //     new User(3, 'third', '3last', 'aa@aa.com')
    //
    // ];

    users: Array<User>;

    constructor(private _userService: UserService) {
    }

    ngOnInit() {

        this.getUsers();
        // this.destroy();
    }

    create(user) {
        //console.log(user);
        this._userService.create(user).subscribe(() => this.getUsers())
    }

    destroy(id) {
        this._userService.ndelete(id.id).subscribe(() => this.getUsers())
    }

    //  update(users: any) {
    //  const i = this.users.indexOf(users.original);
    // this.users[i] = users.edited;
    //}

    getUsers() {
        this._userService.getUsers()
            .subscribe(users => {
                this.users = users
            });

    }

}

and here is my child component that emmit data to parent
user-new.component.ts
import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {User} from "../user";

@Component({
  selector: 'app-user-new',
  templateUrl: './user-new.component.html',
  styleUrls: ['./user-new.component.css']
})
export class UserNewComponent implements OnInit {

  newUser = new User();
  @Output() createNewUserEvent = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  create(){
    this.createNewUserEvent.emit(this.newUser);
    //this.newUser = new User;
  }

}

and its form

user new component

<form (submit)= "create()">
    <input type="text" name="name" [(ngModel)]="newUser.name">
    <input type="text" name="username" [(ngModel)]="newUser.username">
    <input type="text" name="email" [(ngModel)]="newUser.email">
    <input type="text" name="phone" [(ngModel)]="newUser.phone">
    <input type="submit">
</form>

and here is php file that interact with mysql database
include ("db.class.php");

$conn = new Db();

$data = json_decode(file_get_contents("php://input"));

$sql = "insert into users set
        name= '$data->name',
        username= '$data->username',
        email= '$data->email',
        phone= '$data->phone'
";
$stmt = $conn->conn->prepare($sql);
$stmt->execute();

$conn->conn = null;
//end

A: I couldn't figure out the error, but you can use a if(!empty(value)) to prevent the entry of null values into database.
   if(!empty($data)){ $sql = "insert into users set
      name= '$data->name',
        username= '$data->username',
        email= '$data->email',
        phone= '$data->phone'";  }

This will prevent the insertion of empty database row.


text:
Q: lotus notes outline element not shown when the application is opened There is an outline which contains many view displayed. The oultine is contained by a frame from a main frameset.
The users are complaining the fact that when they open the Lotus Client ( IBM Notes 9 ) and then open a Notes application, this outline is not displayed, in fact they see all the views like in the Designer.
If they close and (re)open the application the issue is gone, but still the issue appears again and again.
Thanks for your time.

A: This is most probably because you do not use the default frame- names in your frameset. Name them NotesView (for the view) and NotesNavigator for the outline, then this will most probably fix your issue.


text:
Q: Simple WCF POST with Uri Template I thought this would be incredibly simple, but I must be missing something. I am trying to make a simple WCF POST request in conjunction with a UriTemplate. I have read numerous examples where people use a stream paramater as the last paramater, and this is supposed to pick up the POST body. I can only get this to work if the stream is the only paramater.
I've gone back to basics with a simple Hello World service.
Here is my code on the client
static string Test()
{
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1884/MyAPI/Service.svc/HelloWorld");
    req.Method = "POST";
    req.ContentType = "text/plain";
    Stream reqStream = req.GetRequestStream();
    byte[] fileToSend = System.Text.UTF8Encoding.UTF8.GetBytes("sometext");
    reqStream.Write(fileToSend, 0, fileToSend.Length);
    reqStream.Close();
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    var sr = new StreamReader(resp.GetResponseStream());
    return sr.ReadToEnd();
}

And this is the code on the service
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "HelloWorld")]
    Stream HelloWorld(Stream content);
}

public Stream HelloWorld(Stream content)
{
    var sr = new StreamReader(content);
    string text = sr.ReadToEnd();
    return new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Hello World! " + text));
}

This all works fine. Then I make this change:
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "HelloWorld/test/{test}")]
    Stream HelloWorld(string test, Stream content);
}

public Stream HelloWorld(string test, Stream content)
{
    var sr = new StreamReader(content);
    string text = sr.ReadToEnd();
    return new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Hello World! " + text + test));
}

And change the client code to hit HelloWorld/test/sometext
I get a 500 Internal Server Error. I've tried about 10 different variations including using a ?key=value type UriTemplate, returning strings instead of streams etc, and no luck.
Feels like I'm missing some tiny little thing that is going to make this work, as I have seen countless examples of exactly this all over the web. Theirs works, mine doesn't.
Any ideas?

A: I am not sure what went wrong, but after trying everything, I resolved this by creating a new project and copying all the code over. Never worked out what the differences were, maybe something got corrupted
Edit: in the end we discovered we had to specify WebServiceHostFactory in the Service.svc. This was there by default in the new project

A: When streaming, the Stream must be the only parameter: http://msdn.microsoft.com/en-us/library/ms789010.aspx
You may be able to use message headers: Add filename and length parameter to WCF stream when Transfermode = Stream

A: You can use new single file WCF model to configure and adjust endpoint behaviour. I combined your contract and service class into one file to show you how to do this.
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace StreamService
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MergedEndpoint
    {
        [WebGet(RequestFormat = WebMessageFormat.Xml, UriTemplate = "Data/{someid}",
          ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string GetData(string someid)
        {
            return string.Format("You entered: {0}", someid);
        }

          [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "HelloWorld",
          ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public Stream HelloWorld1(Stream content)
        {
            var sr = new StreamReader(content);
            string text = sr.ReadToEnd();
            return new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Hello World from single file! " + text));
        }
         [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "HelloWorld/test/{testparam}",
          ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
          public Stream HelloWorld2(string testparam, Stream content)
        {
            var sr = new StreamReader(content);
            string text = sr.ReadToEnd();
            return new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Hello World from single file! " + testparam+ text));
        }
    }
}

Input parameters need to be same name as method params. Their type is also string. You need to do the conversion if you want different input param.
You need to create WCf project and add Global.asax file with routing info for this file. You may need to add reference to System.ServiceModel.Activation to setup routing.
 Example:
protected void Application_Start(object sender, EventArgs e)
        {
 RegisterRoutes();
        }

        private void RegisterRoutes()
        {

            RouteTable.Routes.Add(new ServiceRoute("MergedEndpoint", new WebServiceHostFactory(), typeof(MergedEndpoint)));

    }

Your Client code has one change to content type.
 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:55166/MergedEndpoint/HelloWorld/test/234");
            req.Method = "POST";
            //req.ContentType = "text/plain";
            req.MediaType = "HTTP/1.1";
            req.ContentType = "application/json; charset=utf-8";
            Stream reqStream = req.GetRequestStream();
            byte[] fileToSend = System.Text.UTF8Encoding.UTF8.GetBytes("sometext");
            reqStream.Write(fileToSend, 0, fileToSend.Length);
            reqStream.Close();
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            var sr = new StreamReader(resp.GetResponseStream());
            string outp = sr.ReadToEnd();
            Console.WriteLine("Response:"+outp);

You can still read the raw content even if it is set to Json type.


text:
Q: Strange difference in bash behavior across systems I have two systems, an Ubuntu computer and an Android tablet.
I have built and configured bash for Android to be used in adb, so it's the same version as my Ubuntu bash, and they use mostly the same bashrc and configuration, and the same exact options set by shopt.
However, there is a slight difference in that the Android bash behaves as I expect when I I try to tab-complete something using a variable in it, but the Ubuntu bash doesn't.
 #Android
 ls $HOME/loc<tab> => ls $HOME/local #As expected

Basically, the variable is taken into account when completing. But then
#Ubuntu
ls $HOME/loc<tab> => ls \$HOME/loc #Undesired behavior.

The list of options is as follows, and is the same in both builds of bash.
autocd:checkwinsize:cmdhist:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:progcomp:promptvars:sourcepath

What can be making the Ubuntu version escape the $ instead of using it for completion as in the Android build? What can I do to make both work the same way? Any help will be greatly appreciated.

A: The bash package 4.2-0ubuntu3 exhibits this problem, as per this bug:
https://bugs.launchpad.net/ubuntu/+source/bash/+bug/778627/
Apparently this in an issue with bash itself, so right now, your option is to download and compile an upstream copy of bash to run on your machine.


text:
Q: Thinkpad T540p, 16.04 LTS, microphone doesn't work at all I've got a huge issue with my build in microphone of my Lenovo T540p notebook. I am new to Ubuntu and using the 16.04 LTS.
I already read many threads about this and tried to solve it with ALSA mixer and pavucontrol. Nothing worked. In pavucontrol it seems that my micro doesn't detect any sound.
Thanks in advance!


text:
Q: Invalid column name when updating column with CTE I want to populate a column 'surplus' with the difference between the amount  submitted by bidders and the winning bid.
ALTER TABLE bids
ADD surplus FLOAT NULL;
GO

WITH cteSurplus AS
(
    SELECT
        projectId,
        bidAmount, bidderRank,
        surp = (bidAmount-MIN(bidAmount) OVER(PARTITION BY projectId))
    FROM
        bids
    GROUP BY
        projectId, bidAmount, bidderRank
)
UPDATE cteSurplus
SET surplus = surp
FROM cteSurplus;
GO

When I run this query, I get an error:

Invalid column name 'shortage'

For reference, I previously had to populate my rank column, and this query ran without any errors:
ALTER TABLE bids
ADD bidderRank INT NULL;
GO

WITH cteRank AS
(
    SELECT
        *,
        r = RANK() OVER(PARTITION BY projectId ORDER BY winningResultBool DESC, bidAmount DESC)
    FROM bids
)
UPDATE cteRank
SET bidderRank = r
FROM cteRank ;
GO

Does the error come from the subtraction and/or the use of MIN in bidAmount-MIN(bidAmount)?


text:
Q: Multiple Parameter to pass to Command WPF I have the following hierarchy:
abstract class TicketBase
{
    public DateTime PublishedDate { get; set; }
}

class TicketTypeA:TicketBase
{
     public string PropertyA { get; set; }
}

class TicketTypeB:TicketBase
{
     public string PropertyB { get; set; }
}

In my VM I have a List<TicketBase> Tickets. When a user clicks a button on my app, they want to see a list of previous values of a certain property, e.g.:
<Button Tag="{x:Type Types:TicketTypeA}"
        Command="{Binding ListHistoryCommand}"
        CommandParameter="{Binding Tag, RelativeSource={RelativeSource Self}}" />

as you can see, I set my Tag property to TicketTypeA and pass that as parameter to my command:
private void ListHistory(object o)
{
   if (Tickets.Count == 0)
       return;
   Type ty = o as Type;
   ValueHistory = new ObservableCollection<TicketBase>(GetTicketsOfType(ty).Select(t => t)); // <- Need to return t.PropertyA here, but dynamically
}

IEnumerable<TicketBase> GetTicketsOfType(Type type)
{
    if (!typeof(TicketBase).IsAssignableFrom(type))
        throw new ArgumentException("Parameter 'type' is not a TicketBase");
    return Tickets.Where(p => p.GetType() == type);
}

(ValueHistory is another collection that I set as ItemsSource on my grid)
However I need to also pass in the property name too, so that I can display just that property in the grid like so:
Published Time     |  PropertyA
===================================================
09:00              | <value of PropertyA at 09:00>
08:55              | <value of PropertyA at 08:55>

So the question is basically what is the cleanest way to pass in the property name as another parameter into my command?

A: I got this working without resorting to Attached Properties by using the x:Name property in the Xaml and then passing this on to my CommandParameter as a MultiBinding along with the Tag. From Front to Back:
In my View:
 <Button Content="{Binding PropertyA}" x:Name="PropertyA" Tag="{x:Type Types:TicketTypeA}" Style="{StaticResource LinkButton}"/>

 <Button Content="{Binding PropertyB}" x:Name="PropertyB" Tag="{x:Type Types:TicketTypeB}" Style="{StaticResource LinkButton}"/>

In the style for each button:
 <Style x:Key="LinkButton" TargetType="Button">
        <Setter Property="Command" Value="{Binding DataContext.ListHistoryCommand, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />

        <Setter Property="CommandParameter">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource propertyConverter}">
                    <MultiBinding.Bindings>
                        <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
                        <Binding Path="Name" RelativeSource="{RelativeSource Mode=Self}"/>
                    </MultiBinding.Bindings>
                </MultiBinding>
            </Setter.Value>
        </Setter>

In my Converter:
public class PropertyConverter : IMultiValueConverter
{
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //Type t = values[0] as Type;
            //String propName = values[1] as string;

            Type t = values[0] as Type;
            if (t == null)
                return typeof(TicketBase);
            String s = values[1] as String;

            return new Tuple<Type,String>(t,s);
        }
}

In my View Model:
private void ListHistory(object o)
    {
        if (Tickets.Count == 0)
            return;
        var tuple = o as Tuple<Type,String>;

        // Now write some code to dynamically select the propertyName (tuple.Item2) from the type (tuple.Item1)

    }

I am now receiving the Type and PropertyName in my Command. Now, I just need to compile a lambda expression at runtime to dynamically Select the PropertyName from the Type.

A: See this question
Passing two command parameters using a WPF binding
Update
If you need to store both the Type and the Property Name on the Button you'll have to use an attached property like you said. To pass the two parameters to the Command, something like this should work
<Button Tag="{x:Type Types:TicketTypeA}"
        local:ParameterNameBehavior.ParameterName="{Binding Source='Parameter A'}"
        Command="{Binding ListHistoryCommand}">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource PassThroughConverter}">
            <Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
            <Binding Path="(local:ParameterNameBehavior.ParameterName)"
                     RelativeSource="{RelativeSource Self}"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

ParameterNameBehavior
public static class ParameterNameBehavior
{
    private static readonly DependencyProperty ParameterNameProperty =
        DependencyProperty.RegisterAttached("ParameterName",
                                            typeof(string),
                                            typeof(ParameterNameBehavior));
    public static void SetParameterName(DependencyObject element, string value)
    {
        element.SetValue(ParameterNameProperty, value);
    }
    public static string GetParameterName(DependencyObject element)
    {
        return (string)element.GetValue(ParameterNameProperty);
    }
}

PassThroughConverter
public class PassThroughConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.ToList();
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}


text:
Q: How to register type library file (.tlb) with InstallShield LE in Visual Studio 2012 C# I've been creating various plugins for an application that requires me to produce a .tlb file. In the past, it has simply been a case of configuring my project's build properties to 'Register for COM interop' thereby producing a .tlb file along with my output dll.  Previously, when using the Visual Studio 2010 installer projects template, this would always correctly register .tlb during installation on the target machine.
I've recently attempted to make the switch to Visual Studio 2012 and use the InstallShield LE project to produce my installer, but it doesn't seem to register the type library during the install, nor does the express addition seem to allow me to manually register via the cmd-line regasm route - or at least it's not that obvious to me.
In the InstallShield project options I had to manually add the .tlb application file (from the  build's \release folder) to the list of files to be included in the installer as it doesn't seem to get included along with the files produced by the project output or content options.  In the .tlb file's 'COM & .Net Settings' properties, I have it configured to Registration Type: 'Extract COM Information' and have enabled 'COM Interop'.
What am I missing?

A: Try this thread for a good technical description: Are *.tlb files ever used at runtime?
In most cases I believe the *.tlb file is not needed because it is already compiled into most binaries regardless of whether it is an exe file or a dll, but .NET Interop is a lot more complex and as the other thread explains the *.tlb file can be needed to deal with advanced communication issues between threads and processes - something that I incidentially had forgotten.
When implementing a setup I have never had the need to register a *.tlb file by itself, it has been enough to register the corresponding binary (exe/dll), but this all depends on the use cases for the product.
Be aware that the way Installshield is registering for COM Interop is not always the best option as far as I recall. I am not sure exactly what they are doing, but I would check and compare with a normal regasm.exe registration:
http://msdn.microsoft.com/en-us/library/tzat5yw6(v=vs.110).aspx . And read the linked thread (Are *.tlb files ever used at runtime?) carefully on the issues of proxies, stubs and marshalling in case you need these features supported.
Here are some further links with concise information on COM/DCOM:
Contents of a Type Library:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms221355(v=vs.85).aspx
COM, DCOM, and Type Libraries: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366757(v=vs.85).aspx
Files Generated for a COM Interface: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366830(v=vs.85).aspx


text:
Q: Coffeescript - call function by variable I want to manage part of my layout with coffeescript. I have a left/right panel and I want to be able to switch between them. I have created something like this:
window.switchPanel = (panel = 'left', action = 'toggle') ->

  open = (panel) ->
    ...

  close = (panel) ->
    ...

  toggle = (panel) ->
    ...

My question is, how do I structure this so that I can call open/close/toggle by the action variable and can I use something so that I don't have to pass in the panel to every child function? Perhaps @panel?

A: I think you just want to throw your functions into an object so that you can access them by name:
window.switchPanel = (panel = 'left', action = 'toggle') ->
  funcs =
    open: (panel) ->
      ...
    close: (panel) ->
      ...
    toggle: (panel) ->
      ...

Then you can simply funcs[action](panel) inside switchPanel. If you don't want pass panel into the functions then you don't have to, they'll have access to panel simply by being defined within switchPanel:
window.switchPanel = (panel = 'left', action = 'toggle') ->
  funcs =
    open: ->
      ...
    close: ->
      ...
    toggle: ->
      ...

Then you'd just funcs[action]() and they could do what they like with panel.
Demo: http://jsfiddle.net/ambiguous/UV42x/
Some reading on JavaScript closures would clarify what's going on in the second version.
You might want to include an if(action !of funcs) check to make sure you don't try to use a bad action. Or, as Aaron Dufour notes in the comments, you could funcs[action]?() if you only need to check that action is valid once.

A: Few things:
1) I think you're creating obvuscated architecture by selectively calling methods within the object based on an input to the object.  It begs the question "Why even create the methods?  Why not just use a big IF ELSE IF type structure?"  But others would disagree with me.
2) This is one of the confusing circumstances of CoffeeScript.  You're dealing with something that would normally be clear if wrapped in explicit braces.  I don't like javascript's crazy use of anonymous function wrappers everywhere, but I do believe in bracketed code.  I defer to point 1.  I think you're just making things more complicated by doing it this way.
3) Have you studied how coffeescript transforms the 'this' keyword?  I'm pretty certain CoffeeScript does some kind of smart transformation on 'this' that deviates from standard javascript, which will mean nobody can answer this question for you except Coffee users.  It won't be the same as javascript.  Its relevant because in order to access 'panel' in the methods without passing it explicitly, you would need to use 'this.panel' or some other dereferencing mechanism to access the panel member from within one of the methods.  I can't tell you how, but this information my help steer you in the right direction.  The issue at hand is clearly a question of how to reference object members.


text:
Q: Angular 2 Cant display Array from GET-Request I try to display an array which I fetch from mongodb (Chrome networktool shows that I get it (response with articles)). I dont get any error but the articles arent shown in the template.
Here is the template:

{{arts.headline}}

                    {{arts.updated_at}}

{{arts.textarea}}

                    MutedText.MutedText.MutedText.

The getArticles() method in the Component: the articles array is declared!
getArticles():Promise
{
        return this.articleService.getArticles()
                            .then(articles => this.articles = articles);
    }

And the service's getArticles() method:
 getArticles(): Promise
{

       return this.http.get(`${BASE_URI}${PATH_ARTICLES}`)
                    .toPromise()
                    .then((r: Response) => r.json().data as Article[])
                    .catch(this.handleError);

    }

Thanks in advance,
I cant find anything on the net..

A: I once asked a similar question to this: custom created method error: "is not a function" with an answer from Günter Zöchbauer:

"If you cast JSON to a TypeScript class, all is happening is that you indicat to the static analysis it can safely assume the value being of that class, that doesn't actually change the JSON value at all and also doesn't make it an instance of that class."

Your problem is here: .then((r: Response) => r.json().data as Article[]). You declared them as array of Article but they aren't. It'll work but in reality they are (correct me if I'm wrong. It's a new topic for me too) simple objects.
You can add objects to an array of Article but that doesn't mean the added objects turns into an Article


text:
Q: React how to jump to a target input area in a form? I had a very long form which around 20 different fields and I displayed those input area using map function. I want to valid the input data when I click the submit button and jump to the corresponding input required box.
const ReportFields = [
  {
      title: "Report Title*",
      field: "report_title",
      type: "text",
      required: true
  },
  {
      title: "Submitting Agency*",
      field: "submitting_agency",
      type: "text",
      required: true
  },
  {
      title: "Division*",
      field: "division",
      type: "select",
      required: true
  },
  {
      title: "Committee*",
      field: "committee",
      type: "select",
      required: true
  },
  {
      title: "Assigned Contact*",
      field: "assigned_contact",
      type: "select",
      required: true
  },
  {
      title: "Other Recipients",
      field: "other_recipients",
      type: "text",
      required: false
  }];

class App extends Component {

  state = {
    report: {
    report_title: "",
    submitting_agency: "",
    division: "",
    committee: "",
    assigned_contact: "",
    other_recipients: ""
    },
    errorMessage: "",
    refs: {}
  }

 componentDidMount() {
    this.registerRefs();
 }

 registerRefs = () => {
    const refs = ReportFields.reduce((acc, current) => {
      const ref = React.createRef();
      acc[current.field] = ref;
      return acc;
    }, {});

    this.setState({ refs });
 }

   onSubmit = (e) => {
      e.preventDefault();
      for (let i = 0; i < ReportFields.length; i++) {
      const curt = ReportFields[i];
      if (curt.required && this.state.report[curt.field] === "") {
        this.setState({errorMessage: `${curt.title} cannot be empty!`});
        this.state.refs[curt.field].current.focus();
        break;
      }
    }
  }

   render() {
     const display = ReportFields.map((field, idx) => {
     return (

{field.title}

         <input
            type={field.type}
            onChange={(e) => {
              this.setState({
                 report: {...this.state.report, [field.field]: e.target.value}
            })
        }}
        ref={this.state.refs[field.field]}
        ></input>

    );
})

    return (

        {display}
        <input type="button" value="submit" onClick={this.onSubmit}/>

    );
 }
}

 export default App;

I tried to use react refs but it doesn't work, any idea?
Also, I am actually using these content in react modal, will this be one of the reason why it doesn't work?

A: Ok here is a solution I know who can work but I don't say it's the best one. A working example here https://codesandbox.io/s/94v4r6w7kr. As you can see when you click submit you jump to password input.
How do that work ? First as you can see we need a way to save all the ref we gonna create. I save it in the state refs here. The way that work is a loop over each field and for each one I createRef and add this to an object. I use this object inside the state. When you want to use it after that, you then can call this.state.refs[thenameoftheinput].current.focus().
This is an example, and I let you make it work with your own data. But I hope that can give you an idea :)
const ReportFields = [
  {
    title: "Report Title*",
    field: "report_title",
    type: "text",
    required: true
  },
  {
    title: "Submitting Agency*",
    field: "submitting_agency",
    type: "text",
    required: true
  },
  {
    title: "Division*",
    field: "division",
    type: "select",
    required: true
  },
  {
    title: "Committee*",
    field: "committee",
    type: "select",
    required: true
  },
  {
    title: "Assigned Contact*",
    field: "assigned_contact",
    type: "select",
    required: true
  },
  {
    title: "Other Recipients",
    field: "other_recipients",
    type: "text",
    required: false
  }
];

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      refs: {}
    };
  }

  componentDidMount() {
    this.registerRefs();
  }

  registerRefs = () => {
    const refs = ReportFields.reduce((acc, current) => {
      const ref = React.createRef();
      acc[current.field] = ref;
      return acc;
    }, {});

    this.setState({ refs });
  };

  focusTextInput = () => {
    this.state.refs.division.current.focus();
  };

  render() {
    const inputs = ReportFields.map(el => {
      return <input placeholder={el.title} ref={this.state.refs[el.field]} />;
    });

    return (

        <form>
          {inputs}
          <input type="button" value="submit" onClick={this.focusTextInput} />
        </form>

    );
  }
}

A: Iterate through all fields and create a separate ref for each one of them. Use a unique identifier (as a suggestion - the name property) to access the ref later.
class App extends Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);

    // Fields
    this.ReportFields = [
      {
        type: "text",
        name: "firstname",
        title: "First Name"
      },
      {
        type: "text",
        name: "lastname",
        title: "Last Name"
      }
    ];

    this.inputRefs = this.ReportFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: React.createRef()
      }), {});
  }

  state = {
    a: {
      b: "",
      c: "",
      d: "",
      e: "",
      f: "",
      g: "",
      h: "",
      i: "",
      j: "",
      k: "",
      l: "",
      m: "",
      n: "",
      o: "",
      p: "",
      q: "",
      r: "",
      s: "",
      t: "",
      u: "",
      v: "",
      w: "",
      x: "",
      y: ""
    },
    errorMessage: ""
  };

  focusTextInput() {

    // Focus on the input you wish, in this case "firstname"
    console.log(this.inputRefs["firstname"].current.focus());
  }

  render() {
    const display = this.ReportFields.map((field, idx) => {
      return (

{field.title}

          <input
            type={field.type}
            onChange={e => {
              this.setState({
                report: { ...this.state.report, [field.field]: e.target.value }
              });
            }}
            ref={this.inputRefs[field.name]}
          />

      );
    });

    return (

        {display}
        <input type="button" value="submit" onClick={this.focusTextInput} />

    );
  }
}


text:
Q: Is there a way to avoid unnecessary recursion? I posted this question over at CodeReview, but I came to realize that it's not so much a Haskell question as it is an algorithm question.
The Haskell code can be found on my github repo but I think the code isn't as important as the general concept.
Basically the program figures out the optimal first set of moves in a game of Kalaha (the Swedish variation). Only the first "turn" is considered, so we assume that you get to start and that anything from the point of the opponent getting to move is not computed.
Kalaha board http://www.graf-web.at/mwm/kalaha.jpg
The board starts off with empty stores and a equal amount of marbles in each pot.
You start your turn by choosing a non-empty pot on your side, pick all of the marbles up from that pot and then move around the board by dropping one marble when passing a pot. If your last marble lands in the store, you get another turn. If you land in a non-empty, non-store pot, you pick up all of the contents of that pot and continue. Finally, if you land in an empty pot, the turn is passed to the opponent.
So far I've solved this by picking all possible paths and then sorting them according to the amount of marbles in the store by the end. A path would mean to start from one of your pots, do all the necessary pick-up-and-move-around and see if you either land in a store or in an empty pot. If you land in the store you get to continue, and now there are as many new branches as there are non-empty pots on your side.
The problem lies in the fact that if you start with five marbles in the pots, it's already quite a few paths. Jump up to six and ghci runs out of memory.
The reason I can't figure out how to make this less expensive is because I think that each path is necessary during computation. While I'll only need at most three paths (the best ones) out of the thousands (or millions) generated, the rest need to be run through to see if they're actually better than the previous ones.
If one is longer (generally better) then that's good but costly. If it's shorter than any previous path, then program still had to compute that path to find that out.
Is there any way around this, or is computing all the paths necessary by definition?

A: Just try them all out in order, recording your sequences of moves as sequences of numbers 1 through 6 (representing the pot that you pick the marbles from), each time replaying the whole sequence from the start. Keep and update just the three winners, plus the very last sequence of moves so you'd know what to try next. If there's no next legal moves, go back one notch.
It's going to be prohibitively slow perhaps, but will use very little memory. You don't store resulting positions, only numbers of pots picked from, and replay the sequence anew each time from the starting position, altering the very last move (instead of 2, next try 3, 4 etc.; if no more legal moves, backtrack one level). Or maybe store positions just for the very last sequence of moves tried, for easier backtracking.
It's a typical space for speed trade-of then.

A: You could try parallellizing using this parallel version of map:
parMap :: (a -> b) -> [a] -> Eval [b]
parMap f xs = map f xs `using` parList rseq

Then you will spark off a new thread for each choise in your branch.
if you use as parMap pathFunction kalahaPots as your recursion, it will spark a lot of threads, but it might be faster, you could chunk it but i'm not that good of a parallell haskeller.


text:
Q: can i use MongoReplicaSetClient even for one server? My question is dumb, so sorry.
Is it a good idea to use MongoReplicaSetClient instead of MongoClient even for one server, and then trying to expend it with time Horizontal Scale Strategy ?

A: Replica sets are not related to horizontal scaling strategy (that would be sharding).
Replica sets are used for high availability - replicating data to other servers.  You can have one server be configured as a replica set with only one member though, of course, that does not provide you any high availability since there is nothing to fail over to if that one node fails.


text:
Q: Long Exact Sequence for the Pair $(I\times Y, \partial I\times Y)$
To Prove. Let $Y$ be a topological space and $I$ be the closed unit interval. Then the long exact sequence (for cohomology) of the pair $(I\times Y, \partial I\times Y)$ breaks up into split short exact sequences
  $$0\rightarrow H^n(I\times Y; R)\rightarrow H^n(\partial I\times Y; R)\xrightarrow{\delta} H^{n+1}(I\times Y, \partial I\times Y; R)\rightarrow 0$$

I am able to show that the map $H^n(I\times Y; R)\rightarrow H^n(\partial I\times Y; R)$ is injective. This is because if $j_0:\{0\}\times Y\to \partial I\times Y$ and $i_0: \{0\}\times Y\to I\times Y$ denote the inclusion maps, then the composite $H^n(I\times Y; R)\rightarrow H^n(\partial I\times Y; R)\xrightarrow{j_0^*} H^n(\{0\}\times Y; R)$ is $i_0^*$, which is an isomorphism since $i_0$ is a homotopy equivalence.
So the long exact sequence breaks up into short exact sequences as above.
But I fail to see why the sequence splits. Can someone please help? Thank you.


text:
Q: How to calculate CPU Load Average in C# .NET I have been looking everywhere for a snippet of code that will calculate the load average.
Any Ideas, Snippets, or links are greatly appreciated!!
Thank you!
Jeffrey

A: The Process class has some properties you can use for that (TotalProcessorTime, UserProcessorTime, ...).
Msdn: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx


text:
Q: Communication via service isn't working Angular 8 I am working on a project where parents and children need to  communicate via service. Following this article in the official documentation I am not able to make it work.
This is the service I created:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class CommonService {
    private _propertyChangeAnnouncedSource = new Subject<string>();
    propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable();

    public announcePropertyChange(data: string) {
        this._propertyChangeAnnouncedSource.next(data);
    }
}

In the parent component, I import all I need:
@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss'],
    providers: [CommonService]
})
export class ParentComponent implements OnInit {

    constructor(private _commonService: CommonService) {

    }

    tellChild(data): void {
        this._commonService.announcePropertyChange(data);
    }

}

This is the child's code:
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy {
    private subscription: Subscription;

    constructor(private _commonService: CommonService) {
        this.subscription = this._commonService.propertyChangeAnnounced$.subscribe(
            data => {
                console.log(data);
          });
    }
}

When I call the announcePropertyChange the child is not responding. Any suggestion?
Thanks!

A: There could be several problems:

*

*Check whether or not child and parent component have the same instance of the service. You could have provided CommonService several places thus parent and child might not share same instance of the class.

*How do you exactly execute tellChild() method? Maybe you execute the method when the parent component is initiated, thus new event is emitted by Observable, but child has not yet created and has not subscribed to Observable, it skips the event.
Possible solutions:

*

*If problem 2 is your case then I suggest you to update your CommonService to use BehaviorSubject instead of Subject. private _propertyChangeAnnouncedSource = new BehaviorSubject<string>(null); This way no matter what time someone subscribes to the Observable they will get the latest value and continue monitoring further changes. If you want to avoid initial null value due to BehaviorSubject, I suggest you to modify Observable like so: propertyChangeAnnounced$ = this._propertyChangeAnnouncedSource.asObservable()
.pipe(filter(x => x !== null));
This is it for now, lets hear from you about these 2 and I will update my response later if there is still the problem.

A: Seems like there is a typo in your child component constructor.
private subscription;
  constructor(private _commonService: CommonService) {
        this.subscription = this._commonService.propertyChangeAnnounced$.subscribe(
            data => {
                console.log(data,'from child');
          });
    }

This works for me. Also Please show how is the tellChild invoked in your code:
<button (click)="tellChild('TestData')">Tell child</button>

Check the working Demo Here:


text:
Q: What is the preferred way for playback of a web video in Xamarin Forms? I want to:

*

*play videos in my Xamarin Forms app (iOS + Android + UWP)

*follow best practices and use maintained code

*be able to secure my content (subscription based access)

*if possible, style the transport controls to have a the same look and feel as my app

I found multiple ways that are possible, but not sure what is to be advised given my scenario:

*

*Azure Media player

I found this talk that implied that it is best to use Azure Media Services to transcode your video to different qualities / formats so you can do Adaptive Bitrate Streaming, which means that depending on the quality of the connection and the device type, you will always have the "best possible" video on every type of device with the lowest bandwith usage. According to this talk this requires a "smart player" with the logic to do the switching between quality levels. In the talk the azure media player is mentioned as the go-to video player because it has support for Adaptive Bitrate Streaming (ABS) from azure media services.
It does not mention other players with ABS compatibility.
The transcoded video in the sample is played with Azure Media Player, which is hosted in a WebView. And since this talk was from 2018 and in a very recent release of Xamarin Forms (5.0) they have removed support for UIWebView and replaced it with WKWebView and I'm not sure if the WebView (and thus the video player) used in the sample is still supported / advised.

*Custom Renderer

The Xamarin Forms documentation has a section "implementing a video player" where they give you a sample video player in the form of a custom renderer. I like that they allow you to style the transport controls yourself.
It is not mentioned if this video player has the same "smart switching" like the azure media player.

*Use vimeo

With a paid subscription you can apperently secure the access your content. The styling of the player is limited, but maybe enough for my purposes. They do the content encoding / smart switching in the player for you. You pay a monthly fee, and have a limit on how many video minutes you can add each month, but no other bandwith / storage costs (as far as I can see).

*Quick and dirty (naive?)

I can upload an mp4 to azure blob storage and use the customer renderer sample to playback the video directly from the blob.
This however would mean that there is no dynamic switching of video quality on the client and they would always consume "full bandwidth".
I am new to video transcoding / streaming.
Am I missing something in my analysis?

A: I would definitely go with option 2 because:

*

*It's recommended by Xamarin and Microsoft.

*It's free!

*Taking adventage of the native implementation, you would be using the full potential of each platform and you can display videos from any source, local videos from the phone or the project or from YouTube, Vimeo, etc (as long as they are public videos).

*Easy to use.

*It's easy to customize because you handle the native code, that means you are in charge and not some WebView or someone else library.

I would discard the other options because:

*

*Option 1 might be a good option, but you're consuming Azure and eventually it will cost you or your client money and use a WebView to display a video it's not very friendly from the UX point of view.

*Options 3: I would definitely discard a paid solution if I have other options, specially if the other options are free.

*Option 4 as same as before, you would be consuming Azure time and process, that lead you to lose money, if you want to upload a public video always upload to YouTube or some similar service, but as you said, consume the video from a native video player is the best option.

And by last, check this official sample, is more updated than the docs.
P.D: it's, custom renderer, not customer renderer ;-)


text:
Q: Foal Ts and Nuxt js i'm using "foal ts" in the backend and i set my endpoints properly , so i can authenticate and get a token for my "Nuxt js " app in the frontend
i test it with postman and everything perfect
also my "nuxtJS" app authenticate correctly
but when i try to fetch /api/note like i did in postman , i got bad request ,

// in nuxt component mounted method :
this.$axios.get('/api/notes',{data:{email:'admin@gmail.com'}})
.then(res => {return res.data})
.catch(err => {return err.message})

what's wrong ???!!!!
some screenshots from the backend ===>>>

A: I can't send a body with a get request usually you would have to send them as query params.


text:
Q: How to flag id's by a condition? I want to create a column that flags an id it has a straight order process. i.e. id's which don't have order_status pending or info_required.
e.g. id a has pending, so is_straight will be false. b has no pending or info_required, so it should be true.

Here is the example data:
    WITH t1 AS (
SELECT 'a' AS id, 'created' AS status, '2021-11-02 15:04:07'::timestamp AS created_at UNION ALL
SELECT 'a' AS id, 'created' AS status, '2021-11-03 13:23:34'::timestamp AS created_at UNION ALL
SELECT 'a' AS id, 'pending' AS status, '2021-11-07 04:04:46'::timestamp AS created_at UNION ALL
SELECT 'a' AS id, 'successful' AS status, '2021-11-07 13:25:05'::timestamp AS created_at UNION ALL
SELECT 'b' AS id, 'created' AS status, '2021-11-11 16:19:07'::timestamp AS created_at UNION ALL
SELECT 'b' AS id, 'successful' AS status, '2021-11-13 17:57:55'::timestamp AS created_at UNION ALL
SELECT 'c' AS id, 'created' AS status, '2021-11-15 01:09:23'::timestamp AS created_at UNION ALL
SELECT 'c' AS id, 'info_required' AS status, '2021-11-17 11:06:00'::timestamp AS created_at UNION ALL
SELECT 'c' AS id, 'successful' AS status, '2021-11-21 23:35:46'::timestamp AS created_at
    )

A: Using windowed COUNT_IF:
SELECT *,
   COUNT_IF(order_status IN ('pending', 'info_required')) OVER(PARTITION BY id) = 0
            AS is_straight
FROM t1;

Output:


text:
Q: Is there a way to detect rfid chip on an iphone? i know iphone 4 does not have a NFC chip built in but i am wondering if i can still detect a rfid chip maybe using wifi signal or celluar signal?

A: You don't really get low-level enough access to the phone's radios to let you communicate directly with an RFID tag. Your best bet is to look into external hardware, possibly an Arduino or similar talking to your app via the headphone jack.

A: Only the iPhone 6 has the required NFC controller to communicate with NFC tags. At this time, it's unclear what SDK might be available to developers:
Reading NFC Tags with iPhone 6 / iOS 8
RFID or NFC chips cannot be detected by WiFi or cellular. This is not possible due to different technology they use. There are external NFC readers available for the iPhone.
Check e.g. here: http://www.icarte.ca/


text:
Q: Why do helium fuse in the Sun? Initially there are lots of hydrogen atoms and trace elements in the Sun. Despite insufficient energy for the hydrogen to fuse in the core, quantum tunneling saved the day and invoke proton-proton chain reaction to release partial of Sun total energy output. What about the byproduct helium which require almost as much as ten times the temperature required to overcome the coulomb barrier right? What is exactly happening in the core once the hydrogen runs out in approximately 5 billion years from now?

A: Here is what will happen.
For a so-called main sequence star, that helium just builds up in the star because the star's gravity holds it there. Once the hydrogen supply runs out, the weight of all that helium squeezes down on the core and if the squeeze is hard enough, the temperature down there will get high enough to activate helium fusion, and the star shifts to burning helium and stays hot. If the squeeze isn't enough, the fusion process stops and the star cools off and shrinks.


text:
Q: Asp.net UserControl - How to Data-Bind objects from a list? I am using asp.net 4.5 c#.
I have created a user control with the following member inside:
  [Bindable(true)]
    public Product item
    {
        get{
            return _product;
        }
        set
        {
            _product = value;
        }

    }

I then use my control, while DataBinding a "Product" into the member above:
  <script runat="server">
Product item=new Product();
            </script>
                    <uc:productBox runat="server" item="<%#item%>"/>

While this works, Trying to bind dynamic items from a list in the following way fails:
  foreach (Product item in ProductList()){%>
                    <uc:productBox runat="server" item="<%#item%>"/>
            <%}%>

I get the following error:

The name 'item' does not exist in the current context

Why can't I bind items from a list and how can I solve this in order to work?

A: Binding expressions can only access variables in the scope of the class or static members from anywhere visible, not the scope of any loop as the loop will be executed in the own scope in code behind, in real.
You should rather use a Placeholder and populate it in code behind, or (even better) use the Repeater control that takes your ProductList and builds your productBoxes.
So in the ItemTemplate of your Repeater you should put your ProductBox and use <%# (Product)Container.DataItem %> expression on your Item property like binding a simple list to a Repeater.
A small hint: Building foreach in the ASPX is not very well written. Never do that. Also the name convention insists to start with upper case letters on class / control / public member names.


text:
Q: Handle iOS Version for MessageUI.Framework I am using MessageUI.Framework in my app but the same could not be run on iOS 3.x. Is there any way in which we can check the OS version at compile time. I have tried few solutions(Soln_1  and  Soln_2) on web but they did not work.

A: I have got a solution for the same
#ifdef _USE_OS_4_OR_LATER
   //code for iOS 4.0+
#elseif
   //code for the iOS < 4.0
#endif

This worked for me hope it does for all other as well.


text:
Q: Is it possible to concurrently download a single file without range requests? With HTTP/1.1 Ranged Requests there is a non-zero chance of corruption. Various transparent proxies usually used by ISPs can mangle the requests and thereafter return junk.
Also, not all servers support ranged requests and content length headers.
Is there a KISS way to concurrently download a file using GO without using these tricks?

A:
Is there a KISS way to concurrently download a file using GO without using these tricks?

No, there isn't. But this is not related to Go, this is a plain fact of how HTTP works. If you do not want to use range headers you cannot download just "the first" and "the second" half of a request.
Not only is there no "KISS way", there is absolutely no way (except by using the appropriate tools like range request).

A: One possible method (depending on exactly how you interpret "concurrently") would be something like the code below. This will NOT allow you to set time-outs or a method through which you can monitor the progress of the download, but it will allow you to start a download, then read it at leisure later.
type download struct {
        err error
        r   io.ReadCloser
}

// Download a file in a goroutine, return a channel through which we can
// read a download struct. The struct will either contain an error or
// an io.ReadCloser through which we can read the file.
func download(url string) chan download {
        rv := make(chan download)
        go func() {
                resp, err := http.Get(url)
                if err != nil {
                         rv <- download{err: err}
                         return
                }
                switch {
                        resp.StatusCode == 200:
                                // This can be made better, but is probably good
                                // enough for an illustration
                                rv <- download{r: resp.Body}
                        default:
                                rv <- download{err: fmt.Errorf("HTTP GET gave status %s", resp.Status)
                }
        }()
        return rv
}


text:
Q: Are Authorized NT Users stored in a table in Microsoft SQL Server? I am using Microsoft SQL Server 2008.
While generating custom reports, I need to provide specific parameters based on the logged in user. That's why my app requires a table for users with their ids, so that I can join whatever else I want with them.
The problem starts when I inspect the results of querying Master..SysUsers. My NT user is not listed, however in the SysLogins table, my NT user account is listed there.

A: Microsoft said something here
They suggested that we rather use sys.database_principals, sys.sql_logins than SysUser, SysLogins.


text:
Q: can I use "str".equals(obj) with toString implementation? String s="test";
StringBuilder sb = new StringBuilder("test");

System.out.println(s); //prints test
System.out.println(sb); //prints test

s.equals(sb); -> false

can anyone explain why

A: s is a String, and sb is a StringBuffer.  They are not the same object, so by default, they cannot be equivalent.
It also doesn't help matters that StringBuffer doesn't override Object.equals, so a StringBuilder object will only ever be equivalent to its same instance.

A: This is because String object is different from StringBuilder object.
What you may want is :
s.equals(sb.toString())

Here's what String class's equals method looks like:
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) { // this condition is false for StringBuilder objects
           // some logic here
        }
    }
    return false;
}

Taken from openjdk.
As you can see the equals method would return false due to following condition :
if (anObject instanceof String)

A: And just to throw light on why printing both of them do the same thing, in the background: When you call System.out.println on a StringBuilder Object, it automatically calls the toString method on the object for you.
So, you give it your StringBuilder object like this: System.out.println(sb); but it effectively (and automatically) converts it to System.out.println(sb.toString());

A: s is a String, while sb is a StringBuilder, and thus they are not equal. If you want to check if their string representations (toString()) are equal, you'd have to do so directly:
System.out.println(s.equals(sb.toString());

A: I would like to add that StringBuilder does not overrides equals and hashcode methods. Hence the equals method uses default objet identity comparison. As such 2 StringBuilder instances such sb1 and sb2 are equals if and only if sb1==sb2 is true.
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = sb1;

if(sb1.equals(sb2){
  //they are equals
}

Hence, could not satisfies String equals method SYMMETRIC contract, when you perform sb.equals(s) test.


text:
Q: How to handle the countdown with setTimeout and Interval in Javascript I have worked in capturing the user in the application, after login.

*

*After login I capture the users session with JavaScript's interval
functions

*

*The Interval functions trigger every minute.

*

*when the users session exceeds 1 minute in the app, it should to show a warning message
with a count down for the remaining minutes

*when the countdown is working properly for the first couple of seconds
and then hit the interval function, the count down have a flickering
problem.

*Session Timeout 3:0 minutes, Here when click the button and after 1
minutes show the countdown will be visible and it reaches some
seconds, there have a flickering problem.
Code:
loading= function(){
   var lastDigestRun = Date.now();
      var idleCheck = setInterval(function () {
           alert('interval function invoked');
          var now = Date.now();
          var displaytime = now - lastDigestRun > 3 * 60 * 1000;
          if (now - lastDigestRun > 1 * 60 * 1000) {
           alert("warning alert");
              load();
          }
          if (now - lastDigestRun >3 * 60 * 1000) {
              alert("logout");
          }

  }, 60 * 1000);

load = function () {
  startTimer(2,0);
  function startTimer(m,s)
  {
  document.getElementById('timer').innerHTML= m+":"+s;
    s == 0 ? (m == 0 ? alert('done') : (m--, s=60, t())) : (s--, t());
    function t(){ setTimeout(function(){startTimer(m,s)},1000)};
  }

};

Please also look at this JSFiddle


text:
Q: Fancybox iframe not working when called via javascript function I tried calling iframe in a fancybox, but it is not working.
Here is what I wrote:
        var paramsFancy={
            'transitionOut': 'elastic',
            'transitionIn': 'elastic',
            'speedOut': 300,
            'speedIn': 500,
            'autoScale': true,
            'centerOnScroll': true,
            'autoDimensions': true,
            'href' : '/index.php'
        };
        $.fancybox.open(paramsFancy);

I read the people comments from Open fancybox from function but nothing works for me.
Can anyone please help?

A: If you are using fancybox v1.3.4 (my guess, because the API options in your code above) then you need to do this :
$.fancybox(paramsFancy);

... because $.fancybox.open() is not a valid method for v1.3.x and below. It was introduced for v2.x and above.
Additionally, if you want to open an iframe, then you need to add the type API option to your settings like :
var paramsFancy = {
    transitionOut: 'elastic',
    transitionIn: 'elastic',
    speedOut: 300,
    speedIn: 500,
    autoScale: true,
    centerOnScroll: true,
    autoDimensions: true,
    href : '/index.php',
    type: "iframe" // need this for external pages
};

$.fancybox(paramsFancy);

See JSFIDDLE using fancybox v1.3.4

On the other hand, if you are really using fancybox v2.x, then you need to update your API options like :
var paramsFancy = {
    closeEffect: 'elastic', // transitionOut
    openEffect: 'elastic', // transitionIn
    closeSpeed: 300, // speedOut
    openSpeed: 500, // speedIn
    fitToView: true, // autoScale
    autoCenter: true, // centerOnScroll
    autoSize: true, // autoDimensions
    href: '/index.php',
    type: "iframe" // you still need this
};

Notice I commented out the options for v1.3.4
Then you could either use
$.fancybox(paramsFancy);

or
$.fancybox.open(paramsFancy);

... since the first method is backwards compatible.
See JSFIDDLE using fancybox v2.1.5

A: This should work :
    var paramsFancy={
        'transitionOut': 'elastic',
        'transitionIn': 'elastic',
        'speedOut': 300,
        'speedIn': 500,
        'autoScale': true,
        'centerOnScroll': true,
        'autoDimensions': true,
        'href' : '#contentdiv',
        'type': 'iframe'
    };
    paramsFancy.href='/index.php';
    $.fancybox.open(paramsFancy);


text:
Q: Fetch selected items from Two Sided Multi Select Control I have a multi select control similar to the one in below page -
http://www.stevefenton.co.uk/cmsfiles/assets/File/twosidedmultiselect.html
It works cool. The only challenge I am facing is how to smartly get the selected items.I assume some linq queries will help me, but I am new to this -
Form example,
1) If we add a new item in our selection -
prevSelection = {item1,item2}
newSelection ={item1,item2,item3}

How to find out that only item3 is newly added in newSelection?
2) If we remove an item in our selection -
prevSelection = {item1,item2}
newSelection ={item1}

How to find out that item2 is deleted in newSelection?
3) More challenging, if we remove as well as add few item in our selection -
prevSelection = {item1,item2}
newSelection ={item3,item4}

How to find out that item1 and item2 is deleted from newSelection, and item3,item4 added in newSelection?
Thanks

A: 1)
var newItems = newSelection.Except(prevSelection);

2)
var deletedItems = prevSelection.Except(newSelection);

3)
var newItems = newSelection.Except(prevSelection);
var deletedItems = prevSelection.Except(newSelection);


text:
Q: Do idle Netezza sessions harm performance There are times when a Netezza appliance becomes busy with many active sessions processing requests. At these times, there are normally some number of idle sessions. Is it possible for these idle sessions to harm Netezza performance, for instance does an idle session consume a database connection that might cause another pending connection to wait or do idle sessions on Netezza have no impact?
I am considering implementing a process to terminate idle sessions that have a connection start time over some threshold, 60 minutes ago, etc. However, if these sessions have no impact then terminating these sessions might have a negative consequence with no upside.

A: About performance, I'd say "no"
There are however other good reasons for terminating idle connections from time to time. Examples:
 - Even non-active connections may hold a lock on some object that you want to modify (alter a table, recreate a view)
 - TEMP tables occopy space, at will be released for these connections
 - there are a (configureable) max amount of connections (I believe that 500 is the default) and you will want to keep your distance :)
We do that every night around 22 - even for "active" end-user connections - since at short "grace period" in our SLA is allowed on the platform for recreating views etc anyway, and servers hosting end user tools (SAS/BusinessObjects) are recycled at that time as well
It is possible for a query to run for a looong time, and now at least we know that 24 hous is an absolute max :)
I hope this helps you
Lars

A: Curious why you wouldn't just set the SESSIONTIMEOUT property to a non-zero value of minutes -- say 60 in your example -- on the Security Group for these users?  See example below:
ALTER GROUP GRP_EXAMPLE
WITH
ROWSETLIMIT 10000000
 SESSIONTIMEOUT 60
 QUERYTIMEOUT 240
 DEFPRIORITY NORMAL
 MAXPRIORITY HIGH
;
Once Group properties are set, then NPS will take care of this for you automatically after any session has been idle for 60 minutes (or whatever you determine to be a good cut-off).


text:
Q: Nunit - How to skip test setup to call for particular unit test case I have unittest case project where TestSetup is globally setup for all test files.
[SetUpFixture]
public class TestSetup
{
     [Setup]
     public TestSetupMethod(){}
}

How to skip test setup to call for particular nunit unit test case. all other unit test case need this but for couple of unit test case where it is not require.

A: From the documentation:

This is the attribute that marks a class that contains the one-time setup or teardown methods for all the test fixtures under a given namespace.

So simply add all unit tests that requires the one-time setup in the namespace of your setup class, all that don't require that setup in another.


text:
Q: Inner join with sub query in PostgreSQL In my query I need to join with a sub query on a derived column :
select w1.wk_id,
(floor(td1.military_hour/4)*4) as military_hour_group ,
w1.end_date as end_date
from work_instances w1
inner join time_table td1 on w1.end_time = td1.time_id
inner join
(
  select (floor(td2.military_hour/4)*4) as td2_military_hour_group,
 (floor(td3.military_hour/4)*4) as td3_military_hour_group, wk_id
  from task_instances t1
  inner join time_table td2 on t1.end_time = td1.time_id
  inner join time_table td3 on t1.start_time = td3.time_id
) tq1
on tq1.td2_military_hour_group = military_hour_group
and tq1.td3_military_hour_group = military_hour_group
and tq1.wk_id = w1.wf_id

It says Invalid operation: column "military_hour_group" does not exist in w1, td1, unnamed_join, tq1;
What am I doing wrong?
Please help.

A: Try below: military_hour_group is your calculated column and that's why it is showing that error
select w1.wk_id,
(floor(td1.military_hour/4)*4) as military_hour_group ,
w1.end_date as end_date
from work_instances w1
inner join time_table td1 on w1.end_time = td1.time_id
inner join
(
  select (floor(td2.military_hour/4)*4) as td2_military_hour_group,
 (floor(td3.military_hour/4)*4) as td3_military_hour_group, wk_id
  from task_instances t1
  inner join time_table td2 on t1.end_time = td1.time_id
  inner join time_table td3 on t1.start_time = td3.time_id
) tq1
on tq1.td2_military_hour_group = (floor(td1.military_hour/4)*4)
and tq1.td3_military_hour_group = (floor(td1.military_hour/4)*4)
and tq1.wk_id = w1.wf_id

A: Okay Use like below mention
select *
from (select w1.wk_id, (floor(td2.military_hour/4)*4) as military_hour_group , w1.end_date as end_date
    from work_instances w1 inner join time_table td1 on w1.end_time = td1.time_id) table1 inner join (select (floor(td2.military_hour/4)*4) as td2_military_hour_group, (floor(td3.military_hour/4)*4) as td3_military_hour_group, wk_id
    from task_instances t1 inner join time_table td2 on t1.end_time = td1.time_id inner join time_table td3 on t1.start_time = td3.time_id ) tabl2 on tabl2.td2_military_hour_group = table1.military_hour_group and tabl2.td3_military_hour_group = table1.military_hour_group and tabl2.wk_id = table1.wf_id


text:
Q: Programming with functions using C. The functions are not executed I'm learning C and doing the exercise of the function chapter. So i have written a small programm with 3 files and two small functions. Sincerly it does not work. I have no errors, the functions are simply not executed and i don't know why.
First of all this is my headerfile which only declares my functions.
//employee.h
int addEmployee(void);
int printEmployee(int i);

So the next file is for the definition of the functions.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>

int numE;
int i;

int addEmployee(void)
{
    printf("Please type in the number of your employees: ");
    scanf_s("%d", &numE);
    i = numE;
    return i;
}

int printEmployee(int i)
{
    printf("%d", i);
    getchar();
    getchar();
    return i;
}

And the last file is used to execute the functions.
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>

int main ()
{
    int addEmployee();
    int printEmployee();
    return 0;
}

A: Using
int main ()
{
    int addEmployee();
    int printEmployee();
    return 0;
}

you're basically declaring 2 new functions with 0 arguments.
You're not calling your "old" functions.
This should work, as others have pointed out:
int main ()
{
    int emp = addEmployee();
    printEmployee(emp);
    return 0;
}

Because you're calling addEmployee(), storing it's result to emp and then printing emp using printEmployee. Since printEmployee is declared with one parameter, you just put emp in and it will work.

A: When you call a function you do not put the return type in front of the call.  The call is simply the name of the function and any parameters you are calling it with.  So your main function should look like this:
int main() {
    addEmployee();
    printEmployee(1);

    return 0;
}

EDIT:  So in your employee.c file, you are trying to use addEmployee() to take a number of employees from the command line and store it in the variable i right?  And you want printEmployee() to tell you how many employees were entered?  Here's how you would do that.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>

int i;

int addEmployee(void)
{
    int numE;
    printf("Please type in the number of your employees: ");
    scanf_s("%d", &numE);
    i = numE;
}

int printEmployee()
{
    printf("%d", i);
    getchar();
    getchar();
}

Here's what I did.
First, I made numE a variable local to the addEmployee function that uses it.  Generally you should keep variable scope as small as possible.  That means keep them down to the lowest level they are used.  In this case, numE is only needed by addEmployee() so that's its scope.
Second, I removed the parameter from int printEmployee(int i).  It was overriding your i variable at the file level.  So you were storing the number read into numE in i but then when you entered printEmployee() you were creating a new, empty i that hid it.  When you called printEmployee(1) from main, you were passing the value 1 into i in printEmployee(int i).  By removing the parameter, you stop hiding employee.c's i.
Finally, I removed the returns.  A function doesn't have to return anything in C.  And if you are not going to use the return, then it's just an extra line of code to include it.
There's one more change you'll have to make to make this work, in your lab6.c file.  Remove the parameter from the call to printEmployee()
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>

int main ()
{
    addEmployee();
    printEmployee();
    return 0;
}

Should work the way you expect it now.

A: you want:
int main ()
{
    addEmployee();
    printEmployee(1);

    return 0;
}

A: Change this:
int main ()
{
    int addEmployee();
    int printEmployee();
    return 0;
}

To this:
int main ()
{
    addEmployee();
    printEmployee();
    return 0;
}

You're re-declaring the functions instead of calling them.
You'll also have to change your printEmployee function to not accept an integer argument; it seems like it should just be using the same global variable as addEmployee. This is a bad idea though; global variables are generally to be avoided. addEmployee should probably return the employee ID, which you could store and then pass into printEmployee.


text:
Q: javascript error while running application on CRM I am working on a application and when I execute this am getting error at
var b=parseInt(a)+parseInt(b);

that var a is not defined. how do I get the value of a and b. am a new learner. Thank You.
FieldToGet=300101; //int1
FieldToGet2=300102 //int2
FieldToSet=300103; //res

var TstFun = new function () {

this.T1=function(){
    iEventId_OnFocus=10;
    iEventId_OnBlur=9;
    iComboType=1;

    centra.crmapi.getEditView().registerEventListener(function(obj){
        var data=obj['data'];
        var val=data[1];

        centra.crmapi.getEditView().getFieldValue(function(obj){
            var field1data=obj['data']
            var a=field1data[1];
        },FieldToGet,iComboType);

           centra.crmapi.getEditView().getFieldValue(function(obj){
            var field1data2=obj['data']
            var b=field1data2[1];
        },FieldToGet2,iComboType);

         var c=parseInt(a)+parseInt(b);

        centra.crmapi.getEditView().setFieldValue(function(obj){

        },FieldToSet,b,iComboType);

    },FieldToSet,10,iComboType);

};
};

A: The variables a and b are both declared inside the callback functions provided to getFieldValue, and therefore are out of scope (i.e. invisible) to the enclosing scope (the callback to registerEventListener). You should hoist the declarations of a and b, and only assign to them inside the callbacks.
Also, the execution of the callbacks will be deferred, so the values assigned to a and b, even when the declarations are hoisted, will not be usable to you on subsequent lines. You need to nest the callbacks too, like so:
centra.crmapi.getEditView().registerEventListener(function(obj) {
    var data = obj['data'];
    var val = data[1];
    var a;
    var b;

    centra.crmapi.getEditView().getFieldValue(function(obj) {
        var field1Data = obj['data'];
        a = field1Data[1];

        centra.crmapi.getEditView().getFieldValue(function(obj) {
            var field1Data2 = obj['data']
            b = field1Data2[1];

            // This line should no longer error,
            // but `c` seems to be unused...
            var c = parseInt(a) + parseInt(b);

            centra.crmapi.getEditView().setFieldValue(function(obj) {
                // I'm not sure what should go here.
                // Maybe this is where you want to use the value of `c`?
            }, FieldToSet, b, iComboType);
        }, FieldToGet2, iComboType);
    }, FieldToGet, iComboType);
}, FieldToSet, 10, iComboType);

All that said, I have no idea what the code is supposed to do. Your question lacks context, the naming of variables is poor, and the code style is inconsistent. Hope this helps though :)