text:
Q: SQL Convert unicode encoded varbinary to string Ok, i have to export REG_BINARY values and store them in SQL and later i need to convert these values to a string..
What i have:
in c# i read the REG_BINARY to a Byte[] data type like:
RegistryKey rk = Registry.CurrentUser.OpenSubKey...
byte[] value = rk.GetValue("TheKey")
then i store it to a SQL VarBinary Field using:
        private void SqlStorePstFileInfo(List<PersonalFolderObject> listOfPstObjects, int? userComputerId)
    {
        using (var sqlConnection = new SqlConnection(GetConnectionString()))
        {
            sqlConnection.Open();
            foreach (PersonalFolderObject pfo in listOfPstObjects)
            {
                string s = "INSERT INTO [InvPstFile] (UserComputerId, Name, Path, Size, OldRegBinary) VALUES(@UserComputerId, @Name, @Path, @Size, @OldRegBinary)";
                using (SqlCommand sqlCmd = new SqlCommand(s, sqlConnection))
                {
                    SqlParameter pUserComputerId = sqlCmd.Parameters.Add("@UserComputerId", SqlDbType.Int);
                    pUserComputerId.Value = userComputerId;
                    SqlParameter pName = sqlCmd.Parameters.Add("@Name", SqlDbType.NVarChar);
                    pName.Value = pfo.Name;
                    SqlParameter pPath  = sqlCmd.Parameters.Add("@Path", SqlDbType.NVarChar);
                    pPath.Value = pfo.OldPath;
                    SqlParameter pSize = sqlCmd.Parameters.Add("@Size", SqlDbType.Int);
                    pSize.Value = pfo.Size;
                    SqlParameter pOldRegBinary = sqlCmd.Parameters.Add("@OldRegBinary", SqlDbType.VarBinary);
                    pOldRegBinary.Value = pfo.OldRegBinary;
                    sqlCmd.ExecuteNonQuery();
                }

                //string s = string.Format("INSERT INTO [InvPstFile] (UserComputerId, Name, Path, Size) " +
                //                         "VALUES ('{0}','{1}','{2}','{3}')",
                //                         userComputerId, pfo.Name, pfo.OldPath, pfo.Size);

                //Helpers.Logging.Log.Info(string.Format("SQL: {0}", s));
                //var sqlCmd = new SqlCommand(s, sqlConnection);
                //sqlCmd.ExecuteNonQuery();
            }
            sqlConnection.Close();
        }
    }

when i read the the stored value in SQL Management Studio using:
select oldregbinary from InvPstFile where PersonalFolderId = 73

i get:
0x0000000038A1BB1005E5101AA1BB08002B2A56C200006D737073742E646C6C00000000004E495441F9BFB80100AA0037D96E0000000043003A005C00550073006500720073005C00630068007200690073007400690061006E002E006D007500670067006C0069005C0044006F00630075006D0065006E00740073005C004F00750074006C006F006F006B002000460069006C00650073005C006F006E0065006D006F0072006500730061006D0070006C0065002E007000730074000000
When i try to cast it to a string using CAST(AboveString as VARCHAR(max)) i get no result (displayed). The reason is the unicode encoding. When i replace/remove all 00 i get:
0x38A1BB15E5101AA1BB082B2A56C26D737073742E646C6C4E495441F9BFB801AA37D96E433A5C55736572735C63687269737469616E2E6D7567676C695C446F63756D656E74735C4F75746C6F6F6B2046696C65735C6F6E656D6F726573616D706C652E707374
when i cast that value to VARCHAR(MAX) i get:
8¡»å¡»+*VÂmspst.dllNITAù¿¸ª7ÙnC:\Users\MYREMOVEPROFILENAME\Documents\Outlook Files\onemoresample.pst
so, any ideas how to convert/cast the unicode encoded value to a string?
(i know you can decode above string to find the replaced MYREMOVEPROFILENAME - it's not worth the effort ;))

A: You should use GetString() method on specific unicode Text.Encoding to convert it back to string. Cast the column to byte[] from reader and then convert that to string using GetString().
string value;
using (SqlCommand command = new SqlCommand("select * from InvPstFile", sqlConnection))
{
    SqlDataReader sdr = command.ExecuteReader();
    //Assuming we are just reading 1 row here
    sdr.Read();
    var bytes = (byte[])sdr["OldRegBinary"];

    // Based on the original unicode format one of the following should
    // give you the string value
    value = System.Text.Encoding.UTF8.GetString(bytes);
    value = System.Text.Encoding.Unicode.GetString(bytes);
    value = System.Text.Encoding.Default.GetString(bytes);
}


text:
Q: SQL Azure V12 BACPAC import error: "The internal target platform type SqlAzureV12DatabaseSchemaProvider does not support schema file version '3.5'." Today, Jan. 20, 2017, I created a BACPAC file from a SQL Azure V12 database, and when I went to import it to a local SQL Server 2014 instance using SQL Server Management Studio 2014, I got this error:

The internal target platform type SqlAzureV12DatabaseSchemaProvider
  does not support schema file version '3.5'. (File: [filepath])
  (Microsoft.Data.Tools.Schema.Sql)

Note that I found several similar questions to this here on StackOverflow, but none with the exact same error message or same solution.  I tried installing the Microsoft® SQL Server® Data-Tier Application Framework (17.0 RC 1), but that didn't help. (If there's a newer version, I couldn't find it.)

A: After downloading and installing SQL Server Management Studio 2016 (v16.5.1), I was able to use that to successfully import the BACPAC file.  Note that it's a 1GB download and takes 30 minutes or more to install.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Verb usage with always Consider the following two sentences:

*

*John always play football.

*John always plays football.
Which of the above two sentences are correct? The first sentence seems right to me since there are too many 's' in the second one. Is "always" acting as a modular verb here? Thanks for any help.


text:
Q: what might be causing "object reference not set to an instance.." on IIS with https but not while testing with normal http I've got a bill payment web application that I've got communicating with Authorize.net (AIM) and the application its self uses session variables to gather and store data for submission and then applies those same variables to store data entries in SQL.
Initially the application worked fine when I compiled and tested in Visual Studio but when I threw it on the production IIS server (7.0), I get exceptions every time..."Object reference not set to an instance of an object". Now I realize that the error I'm getting on IIS is session variable related but get this..when I don't force https or type it in the address bar, it works just fine.
Obviously I'll need SSL processing transactions but forcing https seems to be messing with my session variables. I'm using the URL rewrite function but to force https but I removed it and then manually went to https in the address bar but still the same problem.
Any ideas or way to fix the issue?
Testing both live an on a local IIS (Self-Signed Security Cert) I get the following...
    [NullReferenceException: Object reference not set to an instance of an object.]
   deco.mgobilling.com.controls.Confirmation.Page_Load(Object sender, EventArgs e) +47
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Control.LoadRecursive() +145
   System.Web.UI.Control.LoadRecursive() +145
   System.Web.UI.Control.LoadRecursive() +145
   System.Web.UI.Control.LoadRecursive() +145
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

The page_load even calls session variables that were assigned on a previous page but seem to be null or lost when the site is under https. This is not the case however when the site is set to the normal http protocol.

A: IIS > Session State > Cookie Settings > Use URI
The issue is defiantly related to Session variables so I tried using Cookieless session IDs and was able to solve the issue this way. I applied the above setting without changing my Web.Config file but Web.Config settings are an option of course.
More on Session State here...
ASP.NET Session State Overview
UPDATE
So after changing my IIS config to use cookieless (URI), i was able to fill out a form and go to another page to confirm what I had filled in. A new problem arose when I came back to the same form and input different data. When I input different data and press submit to confirm my entry, the data is just erased.
Back to the drawing board, I changed the "Cookie Settings" in IIS to "Use Device Profile" and tested again. So far it has work and with different sets of data and on different browsers. Hopefully this will finally take are of the issue.
FINAL UPDATE
Still yet we face the issue. It seems intermittent and happens in one web browser but not the next. After some painstaking troubleshooting, I figure that my sessions are being lost because I am communicating with another website as part of the process. The Sessions are kept between my web forms but as soon as the second web form initiates communication with another website, "plop", their gone.
This is a payment process and it communicates with Authorize.Net. This may be a security thing on certain browsers and I can understand. Query Strings aren't an option and I didn't have time to set IIS to save session stated else ware but I've just got a feeling that it has something to do with browser behavior.
My final solution was to use the Control.FindControl method and grab input values from a previous page (or web user control in my case.). When I grab input values and assign them to local variables within the second page, all is well and I can then use those variables to fulfill my Authorize.Net POST, SQL storage, Email and so on.
I hope this can help someone if the future. I spend hours on Google trying to figure this one out.


text:
Q: Is there a way to prevent web dynos from going to sleep? I'm developing an application that fetches data from an api every 10 seconds and stores it in my own database. When I run it locally it works fine but when hosted on heroku my dyno goes to sleep and stops my app from performing its sheduled task. So my question is, can I disable the dyno sleep function? or is there an even better solution to this problem?

A: Free dynos on Heroku go to sleep when they are not receiving web requests. You can keep them from going to sleep by upgrading to a paid dyno.


text:
Q: Manually Run Job on Play Framework 1.3 I have inherited a system of web apps written in Play Framework 1.3 with zero knowledge transfer, and have been working through some bugs.
We have a Job that is running, but there is a bug with it. The Job runs at certain times of day, but for testing and debugging purposes I want to manually run it locally.
When I run play run locally the Job doesn't seem to run though.
Any ideas/pointers?

A: Jobs can be triggered by now() method;
Promise promise = new YourJobClassHere().now();
await(promise);

if your job returns something (using doJobWithResult() method) you can use it like this (using List type for the example):
Promise<List> promise = new YourJobClassHere().now();
List list = await(promise);


text:
Q: Accessing the DOM from webview in atom Electron Is it possible to scrape html from the webview element in the atom electron desktop development toolkit, I am trying to access the DOM but i get nothing back, i have tried a document.links in the console at runtime but i get empty properties and objects in return?
 window.onresize = doLayout;
 var isLoading = false;

onload = function() {
var webview = document.querySelector('webview');
doLayout();

var t = webview.executeJavaScript("console.log(document.links);");

document.querySelector('#back').onclick = function() {
webview.goBack();
};

<object is="browserplugin" type="application/browser-plugin" id="browser-plugin-1" style="flex: 1 1 auto;"></object>

A: Your console.log is logging to the webview's console, not your parent renderer process' console. Run document.querySelector('webview').openDevTools() from your parent renderer (after you have a src on the webview, it's additional methods aren't available until then). This will open another dev tools window. From that console, you should see your log. Note that webviews and the renderer hosting the webview are two separate webContents instances and two separate renderer processes. You can communicate between them or the main process via IPC.
Not sure what your goals are, but if you want to do DOM manipulation in a webview, I'd recommend using a preload script. This script gets run before the webview's JS and gives you access to all node.js and renderer electron APIs as well as the DOM. executeJavaScript is going to be a long difficult road, whereas preload scripts were built for this kind of use case.
Here's an example demonstrating 1) opening the devtools of a webview, 2) running a preload script in the webview's context that access the DOM, 3) communicating between the parent renderer process and it's child webview process via IPC: https://github.com/ccnokes/electron-tutorials/tree/master/preload-scripts


text:
Q: The probability of an event is 1 in 1365. There is a 3% chance of the odds going up from 1/1365 to 1/512. What are the odds now? I don't really know the process of doing the math here (this is actually the chance of Shiny Pokemon, if anyone's curious). Once you've battled 500, a 3% chance of getting 1/512 odds is added on.
So 1/1365 is your chance of getting a Shiny, but each encounter with a Pokemon has a 3% chance of changing the odds to 1/512, which are much higher. I'm curious what my total odds are then, basically.
Normally (I know it doesn't really work this way), I would say that if my odds are 1/1365 and I go over 1365 then I'm "over odds." I'm curious what would be the expected "odds" when you factor in my "3% chance of 1/512."
Thanks.

A: Just starting with the headline question:
$$P_{total} = \frac{1}{1365}(1-0.03) + \frac{1}{512}(0.03) = 0.000769$$ or 1 in 1300.
This is the probability per catch.  Your long run probability would need to also account for whether the change to 1/512 odds is permanent.


text:
Q: http.get randomly says "getaddrinfo: Name or service not known" To generate offline reports, my Rails app needs to download charts from the Google Charts API.
PROBLEM: It works fine most of the time, but sometimes (randomly) it fails and says getaddrinfo: Name or service not known
When I get the error, I just relaunch the generation and usually it is successful.
Is it usual? Is there a best practice to protect against this?
Maybe a re-entrant algorithm, or a more high-level method?
Current code:
require 'net/http'
  charts.each_with_index do |path, index|
    Net::HTTP.start("chart.googleapis.com") do |http|
    resp = http.get(path)
    open("tmp/charts/chart" + index.to_s + ".png" ,"wb") do |file|
        file.write(resp.body)
    end
  end
end

A: ... it seems, you are overloading your DNS mechanism. Try this:
require 'net/http'
  Net::HTTP.start("chart.googleapis.com") do |http|
    charts.each_with_index do |path, index|
      resp = http.get(path)
      open("tmp/charts/chart" + index.to_s + ".png" ,"wb") do |file|
        file.write(resp.body)
      end
    end
  end
end


text:
Q: Change size of blank line in HTML I'd like to insert a blank line in my HTML code but I'd like to change the size of this blank line to see if it fits with the rest of the page.
Does someone know how to do this ?

A: You could use something like:

A: The nicest way would be to put a bottom margin on the element you want some spacing after. The other solutions posted are not semantic and your markup will end up to be a giant mess of spacer elements without content.
CSS is the right way for presentation.
For example if you have two paragraphs, and want some spacing after the first one:

Blabla

Blabla 2

This is just an illustration, your best bet would be using id / class and a separate stylesheet.
The only other semantic solution I can think of is a
 element, but it is a quite problematic one if you want to style it cross-browser (see details on the link).

A: How about using the line-height css property?
Like this:

A: You could insert a div and change the height with css?

CSS:
.spacer {
  height: 100px;
}

But a better solution would be to put a bottom margin on the element preceding the space you want.

    The stuff before the space

CSS
  .some_content {
    margin-bottom: 100px
  }

Would give you a 100px space below the content.


text:
Q: How to log data on all running processes to use in scheduler simulation? I need to create a process scheduling simulation to test various tweaks of linux's completely fair scheduler, and I need to run it using a log of all the processes running on a system, including how much time they spend using the CPU and in I/O.  My textbook said that the way to do this is to produce a "trace tape" and use this in the simulation, but I can't find any information on how to do this.  How can I log as much information as possible about running processes, including arrival time, resource usage, and time spent waiting for resources?  I'm currently running ubuntu on the machine that this will be used on, but will gladly install whatever flavor of linux would make this easiest.

A: Sounds like an interesting project!
Lots of information about each running process can be found in the virtual directory /proc/[pid].  A lot of the information you're after can be found in /proc/[pid]/stat.  Perhaps you could write a simple script to read and save the contents of /proc/*/stat?
For more info on /proc, see http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html


text:
Q: How to edit input fields using Angularjs? I have my code that when you click on the "Add User" button a popup window shows up on the screen, and then I can type data in the input fields. After clicking on the "Save" button the data gets displayed on the page (inside of a table). I also have an "Edit" button which allows me to edit those fields. My question is...How to enable the Edit button so that when I click on it I get the popup window back and do the editing from there? this means that when I click on the Edit button I should get the popup with the data I typed in previously. Please someone help me. Thank you so much.
Here's my code:
var App = angular.module('App', ['ui.bootstrap'])

App.controller('mainController', function ($scope, $modal, $log, $filter) {

    $scope.People = [];

    $scope.openPopupScreen = function () {

        var modalInstance = $modal.open({
            template: '

.

<form >' +
                ' NAME:<input style = "width:200px;"type="text" class="form-control ng-scope ng-pristine ng-valid" ng-model="person.name">
' +
                ' LASTNAME:<input style = "width:200px;" type="text" class="form-control ng-scope ng-pristine ng-valid" ng-model="person.Lastname">
' +
                ' AGE:<input style = "width:200px;" type="number"class="form-control ng-scope ng-pristine ng-valid" ng-model="person.age">
' +
                ' <button id = "myid" type="button" class="btn btn-success" ng-click="add()">Save</button>' +
                '  <button type="reset" class="btn ">Clear</button>' +
                ' </form>' +
                '
' +
                '
' +
                '  close' +
                '
',
            controller: ModalInstanceCtrl
        });
        modalInstance.result.then(function (newPerson) {
            $scope.People.push(newPerson);
        });
    };

    var ModalInstanceCtrl = function ($scope, $modalInstance) {
        $scope.person = {
            name: '',
            Lastname: '',
            age: ''
        };

        $scope.ok = function () {
            $modalInstance.close($scope.selected.item);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

        $scope.add = function () {
            $modalInstance.close($scope.person);
        };
    };

});

A: I have modified your fiddle. and it is working now as you said
http://codepen.io/anon/pen/XmGYaE?editors=001
$scope.editPerson = function(person){
console.log("pr", person);
var modalInstance = $modal.open({
  template: modalTemplate ,
  controller: ModalInstanceCtrl,
  resolve: {
    person: function () {
      return person;
    }
  }
});

A: I have modified your(@Zohaib Ijaz) codepen.I do not use editperson function, I am just passing the person value in openPopupScreen and sending the people value through resolve. So we can reuse openPopupScreen function for both cases. I think it is better to reuse a function.
$scope.openPopupScreen = function(people) {

 var modalInstance = $modal.open({
  template: modalTemplate ,
  controller: ModalInstanceCtrl,
  resolve: {
    person: function(){
      return people;
    }
  }
 });
};


text:
Q: XPath: Trying to filter based on multiple child nodes I have this XML:
<doc>
  <target>
    <name>V1</name>
    <value>3</value>
    <more>foo</more>
  </target>
  <target>
    <name>V3</name>
    <value>5</value>
    <more>bar</more>
  </target>
  <var>
    <name>V1</name>
    <value>3</value>
  </var>
  <var>
    <name>V2</name>
    <value>3</value>
  </var>
</doc>

I want an XPath query that returns all target nodes where there exists a var node with whose name and value nodes match those specified in the target.  In the example above, there should be no matches.
My attempts at a query look something like this:
//target[//var/name=name and //var/value=value]

This query returns the first target node because there exists a variable V1, and there exists a variable whose value is 3.  But this is not what I am after; I only want matches where the name and the value of the same variable match the target.
I'm using XPath 1.0, so techniques to accomplish this with that version would be most helpful.
Note: Question updated to revise sample XML.

A: XPath 1.0 is not relationally complete (see https://www.rjerz.com/c/infosys/support/Codd-Relational_Completeness_Article.pdf) which means that not all join queries can be expressed, and I think this is one that can't. The limitation arises because XPath 1.0 has no range variables.
In XPath 2.0 it's easy:
//target[some $v in //var satisfies name=$v/name and value=$v/value]

A: If doc has multiple var nodes but one target only you can try
//doc[var[name=preceding-sibling::target/name and value=preceding-sibling::target/value]]/target

A: Not sure you can do exactly what you want with xpath 1.0 but you can sort of fake it by using the text of the <var> nodes to compare to that of <target>. So
//target[normalize-space(.)=//var/normalize-space(.)]

should do it: it will show no match with your sample xml. If you change the <name> value in the last <var> to V1 it should show one match.


text:
Q: How to generate index pages for each group of source code (X number of folders) in doxygen? I want to generate documentation from the C SDK. Let's say three folders (utils, services, drivers) belong to the Libraries group and two folders(main, config) belong to the application group. The document also has an introduction and user guide as separate pages.
So basically Libraries group and application group pages are generated from source code and need to separate as they have in nordic like Libraries and Examples pages.


text:
Q: Cannot use PHP var in a SQL Query I'm trying to show each row where userCZ = $_SESSION['user'], but whenever I try with the var, it doesn't find nothing at all.
If I replace the var for a literal string, It works perfectly.
I've also tried to check if the var is not empty and it returns the proper value at the begin of the script.
I think I am missing something in the syntax but I've tried with '' and "" and still not working.
<?php
  session_start();
  $userCZ=$_SESSION['user'];

require_once __DIR__ . "/../../init.php";
require_once __DIR__ . "/../../functions/db.php";

if (isset($_GET['start']) && isset($_GET['end'])) {
$stmt = 'SELECT * FROM the_events WHERE userCZ = '$userCZ' AND start_date >=
:start and end_date <= :end';
$_events = QuickPdo::fetchAll($stmt, [
    'start' => $_GET['start'],
    'end' => $_GET['end'],
]);

$events = [];
foreach ($_events as $e) {
    $events[] = [
        'id' => $e['id'],
        'title' => $e['title'],
        'project' => $e['project'],
        'start' => dateMysqlTime2Iso8601($e['start_date']),
        'end' => dateMysqlTime2Iso8601($e['end_date']),
    ];
}
echo json_encode($events);
}

A: This can be addressed by binding all of the dynamic values:
$_events = QuickPdo::fetchAll(,
  'SELECT * FROM the_events WHERE userCZ = :userCZ AND start_date >= :start and end_date <= :end',
  [
    'userCZ' => $userCZ,
    'start' => $_GET['start'],
    'end' => $_GET['end'],
  ]
);

Avoid using string interpolation unless you have no other option, and when that occurs, take every possible precaution to ensure you're doing it safely.


text:
Q: cling 2.0.1 on Android - NoClassDefFoundError NetworkAddressFactoryImpl$1 I'm not the first one to have this problem, and Cling author isn't very user friendly to say the least. He just tells people to RTFM. And I swore an oath to never RTM. So... I have all dependencies in my gradle:
compile files('libs/jetty-client-8.1.17.v20150415.jar')
compile files('libs/jetty-continuation-8.1.17.v20150415.jar')
compile files('libs/jetty-http-8.1.17.v20150415.jar')
compile files('libs/jetty-io-8.1.17.v20150415.jar')
compile files('libs/jetty-security-8.1.17.v20150415.jar')
compile files('libs/jetty-server-8.1.17.v20150415.jar')
compile files('libs/jetty-servlet-8.1.17.v20150415.jar')
compile files('libs/jetty-util-8.1.17.v20150415.jar')
compile files('libs/servlet-api-3.0.jar')
compile files('libs/slf4j-jdk14-1.7.12.jar')
compile files('libs/cling-core-2.0.1.jar')
compile files('libs/cling-support-2.0.1.jar')

And yet what I get is:
java.lang.NoClassDefFoundError: org/fourthline/cling/transport/impl/NetworkAddressFactoryImpl$1
        at org.fourthline.cling.transport.impl.NetworkAddressFactoryImpl.getNetworkInterfaces(NetworkAddressFactoryImpl.java:145)
        at org.fourthline.cling.transport.RouterImpl.enable(RouterImpl.java:131)
        at org.fourthline.cling.android.AndroidRouter.enable(AndroidRouter.java:92)
        at org.fourthline.cling.UpnpServiceImpl.<init>(UpnpServiceImpl.java:87)
        at org.fourthline.cling.android.AndroidUpnpServiceImpl$1.<init>(AndroidUpnpServiceImpl.java:54)
        at org.fourthline.cling.android.AndroidUpnpServiceImpl.onCreate(AndroidUpnpServiceImpl.java:54)
        at pl.qus.xenoamp.xenoservice.XenoUpnpService.onCreate(XenoUpnpService.java:109)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:2634)
        at android.app.ActivityThread.access$1800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5151)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
        at dalvik.system.NativeStart.main(Native Method)

A: you need servlet-api-3.0.jar
found out after days of internet researches.. : http://www.gubatron.com/blog/2013/03/12/jar-dependencies-if-you-plan-to-use-the-cling-upnp-library-in-your-android-project/

A: you also need
compile files('libs/seamless-http-1.1.1.jar')
compile files('libs/seamless-util-1.1.1.jar')
compile files('libs/seamless-xml-1.1.1.jar')

Got them here


text:
Q: Python how compare contents of two CSV files with pandas I have a CSV file with 60 different server names, but how do I save all the server names to a list and make a loop that checks if every servername is in the list? Lets say tommorow I compare with a similar CSV file, but it only contains 50 server names. I want it to spit out the servers missing in a print operation how can I do that?
Here is my current code - It reads the CSV file and prints all the server names with an index from 0-59.
csv_file = 'C:\Users\admin\Desktop\csvfolder/some_file.csv'
df = pd.read_csv(csv_file, delimiter=';', skiprows=0, low_memory=False)
print(df)

A: What you need to do is to use python set.
See below:
yesterday_servers = {'s1','s3','s8'}
today_servers = {'s1','s8','s19'}

new_servers = today_servers - yesterday_servers
missing_servers  = yesterday_servers - today_servers
print(f' missing {missing_servers}')
print(f' new {new_servers}')

output
 missing {'s3'}
 new {'s19'}


text:
Q: Google Actions - how to add testers before final deployment someone knows how to add testers to an action on google package?
So other users can test the implementation on their Google Home devices?
Thanks!

A: Today you must use the developer's account to test except for the case of account linking where testers can put their own credentials in for that specific step, and test any functionality that relies on that. I am told by the Actions on Google support team that providing a mechanism for testers (with different accounts than the developer) to access Actions/agents prior to deployment is the number 1 requested feature "by far" so hopefully we will see it down the road.

A: Yes. Make sure everything under "Directory information" is filled out. Then go to the "Release" tab under "Deploy", and click on Alpha (which allows a quicker deploy for up to 20 users without review). Click "Submit for Alpha", and ensure you meet the requirements to check the checkboxes there. After that, you can press "Manage alpha testers" under the Alpha pane, where you can generate a link or add email addresses.
(screenshots anyone?)


text:
Q: How I can read several files How can I read several files and extract only certain lines and write them in their own appropriate file
Example:
file1.txt - file1_output;
file2.txt - file2_output;
file3.txt - file3_output;
file4.txt - file4_output;
file5.txt - file5_output;

more *.log | cat
cat *.log | tee file1.txt file2.txt

File1:
    at com.lhs.ccb.sfw.application.ServiceObjectImpl.validate(Unknown Source)
    at com.lhs.cil.core.AggregatedServiceObjectImpl.validate(Unknown Source)
    at com.lhs.ccb.sfw.application.ServiceObjectImpl.validateI(Unknown Source)
    at com.lhs.ccb.soi.ServiceObjectIPOA._invoke(Unknown Source)
    at com.sun.corba.se.impl.protocol.CorbaMessageMediatorImpl.handleRequestRequest(CorbaMessageMediatorImpl.java:1700)
    at com.sun.corba.se.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1558)
    at com.sun.corba.se.impl.protocol.CorbaMessageMediatorImpl.handleInput(CorbaMessageMediatorImpl.java:940)
    at com.sun.corba.se.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:198)
    at com.sun.corba.se.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:519)

РЯа. 19, 2021 4:14:16 PM com.lhs.ccb.sfw.application.ServiceObjectImpl executeLocaleI
SEVERE: ServiceObjectI.executeLocaleI CONTRACT.WRITE

File2:
Error code: CommonDomain.InvalidStateTransition
    at com.lhs.CommonDomain.bscs_core.ae.a(Unknown Source)
    at com.lhs.Contract.bscs_core.services.ContractWrite.a(Unknown Source)
    at com.lhs.cil.core.AggregatedServiceObjectImpl.executeLocaleI(Unknown Source)
    at com.lhs.ccb.soi.ServiceObjectIPOA._invoke(Unknown Source)
    at com.sun.corba.se.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:198)
    at com.sun.corba.se.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:519)

РЯа. 19, 2021 4:14:16 PM com.lhs.FrameworkExtension.bscs_core.d getErrorMessage
WARNING: no localized text available for:
ErrorCode : InvalidStateTransition
BundleName: CommonDomain_ErrorDictionary
Locale    : en_US
Reason    : XMlResourceException: ResourceBundleManager: Can not find resource bundle 'CommonDomain_ErrorDictionary'
РЯа. 19, 2021 4:14:16 PM com.lhs.FrameworkExtension.bscs_core.d getErrorMessage
WARNING: no localized text available for:
ErrorCode : InvalidStateTransition
BundleName: CommonDomain_ErrorDictionary
Locale    : en_US
Reason    : XMlResourceException: ResourceBundleManager: Can not find resource bundle 'CommonDomain_ErrorDictionary'
РЯа. 19, 2021 4:15:42 PM com.lhs.ccb.sfw.application.ServiceObjectImpl executeLocaleI
SEVERE: ServiceObjectI.executeLocaleI CONTRACT.WRITE

File3:
Error code: CommonDomain.InvalidStateTransition
    at com.lhs.CommonDomain.bscs_core.ae.a(Unknown Source)
    at com.lhs.Contract.bscs_core.services.ContractWrite.a(Unknown Source)
    at com.lhs.Contract.bscs_core.services.ContractWrite.execute(Unknown Source)
    at com.lhs.cil.core.LocalCommandAdapter.localExecute(Unknown Source)
    at com.lhs.cil.core.AggregatedServiceObjectImplProxy.execute(Unknown Source)
    at com.sun.corba.se.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1558)
    at com.sun.corba.se.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:519)

РЯа. 19, 2021 4:15:42 PM com.lhs.FrameworkExtension.bscs_core.d getErrorMessage
WARNING: no localized text available for:
ErrorCode : InvalidStateTransition
BundleName: CommonDomain_ErrorDictionary
Locale    : en_US
Reason    : XMlResourceException: ResourceBundleManager: Can not find resource bundle 'CommonDomain_ErrorDictionary'
РЯа. 19, 2021 4:15:42 PM com.lhs.FrameworkExtension.bscs_core.d getErrorMessage
WARNING: no localized text available for:
ErrorCode : InvalidStateTransition
BundleName: CommonDomain_ErrorDictionary
Locale    : en_US
Reason    : XMlResourceException: ResourceBundleManager: Can not find resource bundle 'CommonDomain_ErrorDictionary'
РЯа. 19, 2021 4:17:19 PM com.lhs.ccb.sfw.application.ServiceObjectImpl executeLocaleI
SEVERE: ServiceObjectI.executeLocaleI CONTRACT.WRITE

OUTPUT:
FILE1_OUTPUT: SEVERE line... from File1
FILE2_OUTPUT: SEVERE line... from File2
FILE3_OUTPUT: SEVERE line... from File3

***SEVERE line is always on a different position

A: I would use awk as following:
awk 'FNR==1{ close(ofname); ofname="output_"FILENAME }
  /^SEVERE/{ print >ofname }' infile*


text:
Q: Searching key terms (Corpus) into another in R I asked this question before and got negative feedback because I did not provide code. I spent the whole day trying and trying and now I am stuck in an issue.
This code has been fetched by a user in Stackoverflow "Tyler Rincker" <- big thanks to him!
here is the code:
strip <- function(x, digit.remove = TRUE, apostrophe.remove = FALSE){
          strp <- function(x, digit.remove, apostrophe.remove){
            x2 <- Trim(tolower(gsub(".*?($|'|[^[:punct:]]).*?", "\\1", as.character(x))))
            x2 <- if(apostrophe.remove) gsub("'", "", x2) else x2
            ifelse(digit.remove==TRUE, gsub("[[:digit:]]", "", x2), x2)
          }
          unlist(lapply(x, function(x) Trim(strp(x =x, digit.remove = digit.remove,
                              apostrophe.remove = apostrophe.remove)) ))

corpus2 <- "In Westerman's disruptive article, Quantitative research as
        an interpretive enterprise: The mostly
        unacknowledged role of interpretation in research efforts."

    corpus2 <- gsub("\\s+", " ", gsub("\n|\t", " ", corpus2))
    corpus2.wrds <- as.vector(unlist(strsplit(strip(corpus2), " ")))

    corpus2.Freq <- data.frame(table(corpus2.wrds))
    corpus2.Freq$corpus2.wrds  <- as.character(corpus2.Freq$corpus2.wrds)
    corpus2.Freq <- corpus2.Freq[order(-corpus2.Freq$Freq), ]
    rownames(corpus2.Freq) <- 1:nrow(corpus2.Freq)

    key.terms <- c("research as")

My issue is that i want to search for bigrams or trigram (2 or 3 words) in the corpus.
When i execute this line of code:
corpus2.Freq[corpus2.Freq$corpus2.wrds %in%key.terms, ]

I get this results which should show a frequency of "1".
[1] corpus2.wrds Freq
<0 rows> (or 0-length row.names)

However, if the keyterm is only 1 word:
key.terms <- c("research")
    corpus2.Freq[corpus2.Freq$corpus2.wrds %in%key.terms, ]

the code is working fine and i get the following result:
corpus2.wrds Freq
research    2

Thanks a lot! and hopefully someone can help.

A: you cannot find any bigrams, because you haven't created them. You use function strsplit(strip(corpus2), " ") which creates only unigrams.
I also recommend you to use preprocessing functions which are available from tm package instead of your own strip() function.
You can try something like this for unigrams :
library(tm)

# create corpora
corp = VCorpus(VectorSource(corpus2))

# this should replace your strip() function
ctrl = list(tokenize = function(x) unlist(strsplit(as.character(x), "[[:space:]]+")),
        removePunctuation = TRUE,
        removeNubers = TRUE,
        tolower = TRUE)

tdm = TermDocumentMatrix(corp, control = ctrl)
inspect(tdm)
inspect(tdm[c("research"),])

Or similar code for both unigrams and bigrams:
ctrl2 = list(tokenize = function(x) unlist(lapply(ngrams(words(x), 1:2), paste, collapse = " "), use.names = FALSE),
        removePunctuation = TRUE,
        removeNubers = TRUE,
        tolower = TRUE)

tdm_bigrams = TermDocumentMatrix(corp, control = ctrl2)
inspect(tdm_bigrams)
inspect(tdm_bigrams[c("research"),])
inspect(tdm_bigrams[c("research as"),])


text:
Q: How to insert an iframe on linkedIn via oEmbed? I am trying to embed an audio player in an iframe (for instance: http://radio.immo/share/player_mini/video=false&digest=true&auto=true&resp=false&mode=broadcast&id=97475) to listen to podcasts or live
broadcasts within linkedIn posts.
Basically, however, my questions would be the same for any player or web application to be embedded in an iframe.
I managed to use oEmbed, as explained in the following post:
https://www.linkedin.com/pulse/embedding-content-linkedin-posts-using-oembed-david-max ,
I implemented it for test purpose on the following web page:
http://saooti.wikiradios.com/broadcast/42660-Emission-avec-Antoine
I added in this page a link:
<link rel="alternate" type="text/json+oembed" href="/attachments/HPUserContent/oembed.json?url=https%3A%2F%2Fsaooti.wikiradios.com%2Fbroadcast%2F42660-Emission-avec-Antoine&format=json"/>

pointing to the json file:
{
  "version": 1,
  "type": "rich",
  "provider_name": "Saooti",
  "provider_url": "https://saooti.wikiradios.com",
  "height": 41,
  "width": 319,
  "title": "Emission avec Antoine",
  "description": "Une émission en direct pour Antoine... (Insertion, jeunesse, test)",
  "thumbnail_url": "https://saooti.wikiradios.com/attachments/images/broadcast/42660/image.png",
  "html": "<iframe id=\"iframe\" style=\"width:319px;height:281px;border:none;overflow:hidden;\" src=\"http://saooti.wikiradios.com/share/player_mini/video=false&digest=true&auto=true&resp=false&mode=broadcast&id=42660\"></iframe>",
  "author_name": "Saooti Admin",
  "author_url": "http://saooti.wikiradios.com/user/3-3-Saooti-Admin"
}

It doesn't work:
when I share this web page, I get the matching photo, with a nice "play" button on it, but when I click the button, I am just forwarded to the page, when I was hoping to get an audio player in an iframe.
I guess it's because a validation from linkedIn is required…
My questions are:

*

*is it really a question of validation/authorization by linkedIn or did I make any mistake?

*If it is a question of validation/authorization:

*

*which is the process to follow for retrieving this authorization?

*Is this authorization granted by web domain ?

Thank you for your answers,


text:
Q: The user is being created in server but is not being updated in the redux store, it is getting rejected in the onQueryStarted function. Used RTK Query User is being created in server but not updating in redux store getting rejected in onQueryStarted functionenter image description here

A: I'm not entirely sure because there is very little to go off of but it looks like this is still a server side error. It seems like your code is able to save the user record, but right after that, something on the server side goes wrong? You need to provide more code and context

A: The server seems to return just a string message, not valid JSON.
In that case you will have to set responseHandler: "text" for the endpoint.


text:
Q: Q: SQLAlchemy 1.4 (2.0) problem converting results from session.execute(statement).scalars().all() or session.execute(statement).all() I have this table defined as follows
class Carrier(Base):
    __tablename__ = 'Carrier'
    __table_args__ = {'comment': 'Carrier Code List'}

    Id = Column(Integer, primary_key=True, comment='PK for carrier table')
    Code = Column(String(50), index=True, comment='code to use')
    Description = Column(String(255), comment='description of the code')

To query the table I use the following
with Session(self.sqlengine, future=True) as session:
        statement = select(Carrier)
        #result = session.execute(statement).all()
        result = session.execute(statement).scalars().all()

I can loop through the results as follows
 for row in result:
    print(row.Id, row.Code)

According to the documentation, the following should return
# list of tuples
result = session.execute(statement).all()

# list of first element of each row (i.e. User objects)
result = session.execute(statement).scalars().all()

This is where I am getting confused.  I am not getting a list of tuples or the first element of each row.  I am getting an address to the instance of the class.  For example <Carrier object at 0x000001B30ACB1D00>
It would be nice if it actually returned a tuple or a class with properties as I defined it in the table class but it is not.
I have also failed in all my attempts to convert it to a class that would be useful.
If I should be doing some mapping or converting I have no idea how nor have I been able to find an example.  I feel the documentation is not very good either at least for 1.4/2.0
I would appreciate some assistance I know I am missing a nuance on how to convert but I do not know how to proceed.

A: For this setup
with sa.orm.Session(engine, future=True) as session:
    # create test data
    session.add_all([Carrier(Code="Alfa"), Carrier(Code="Bravo")])
    session.commit()

    # define our select statement
    statement = sa.select(Carrier)

    results = session.execute(statement).all()
    print(results)
    # [(<Carrier(Id=1, Code='Alfa')>,), (<Carrier(Id=2, Code='Bravo')>,)]

version 1.4 returns a list of Row objects. They are tuple-like and are represented in the same way as a tuple, surrounded with round brackets: (<Carrier(Id=1, Code='Alfa')>,).
Using .scalars()
    results = session.scalars(statement).all()
    print(results)
    # [<Carrier(Id=1, Code='Alfa')>, <Carrier(Id=2, Code='Bravo')>]

returns a list of "plain" ("scalar") Carrier objects. Notice that they are not enclosed in ( …,). The .scalars() call "looks inside" each Row object and returns the first element it finds (by default, index=0).
The difference is easier to see with simple scalar values:
    statement = sa.select(Carrier.Id)  # just the .Id column

    results = session.execute(statement).all()
    print(results)
    # [(1,), (2,)]

    results = session.scalars(statement).all()
    print(results)
    # [1, 2]


text:
Q: Haskell String-> Int Type Conversion I'm taking my first few steps in Haskell, and I'm trying to convert a string to an integer, but I'm not managing. I've looked at similar questions and I'm still not sure.
All I want to do is convert, e.g. '6' or "271" to integers, that is, 6 or 271 respectively. How do I do this?
The analogue would be that in Python, I could do this easily: e.g.int("2723") would get the job done.

A: If you know that the string is a valid integer, or you don't mind it blowing up if that's not the case, read will work. If you are unfamiliar with Haskell's typeclasses, just know that you might have to tell Haskell what type you want to read it as:
main :: IO ()
main = do
  let x = read "271" :: Integer
  print x

You don't always have to do this, if Haskell has some other way of knowing what type you want, like if you proceed to do arithmetic with it.
If you don't know for sure that the string is a valid number, recent versions of base (not sure since when) include a function readMaybe that will safely return Nothing if it is not a readable integer.


text:
Q: Disable CTRL + Up Arrow = Home on DataGridView When I press CTRL and Up Arrow on DataGridView I go to the first row. When I do the same with Down Arrow I go to  last row in DGV. How to disable this behavior in this direction that when I will do CTRL+Up I will go one row up and when I do CTRL+Down I go one row down?

A: You should not override OnKeyPress () because the navigation handlers eat navigation keystrokes before they're sent to OnKeyPress ().
Instead, you should override ProcessDialogKey () and/or ProcessDataGridViewKey (), which exist explicitly to handle navigation.
ProcessDialogKey
ProcessDataGridViewKey

ETA: with all due respect, in general it's usually not a particularly good idea to change navigation behavior. A lot of applications use DataGridView, and users typically expect the default behavior, because that's what most applications will use. There are exceptions and sometimes good reasons to change the default navigation, but just because you personally don't like the default behavior is usually not a sufficient reason to change it. This is, of course, just my personal opinion; YMMV.

A: look into overriding the OnKeyPress event... You may have to declare your own class
not exact, but a start...
public class MyDataGridView : DataGridView
{
   ...
   ...

   public override void OnKeyPress( object sender, KeypressEventArgs e )
   {
      trap your own "e." values
   }
}

A: You need to override ProcessDialogKey and 'cancel' the event if you detect a certain key or key combination.


text:
Q: Change style on hover while a key is held down I've set up a style to turn a single-cell table, for example:

        This is a button

Into a button via CSS such as:
table.mybutton {
    border : 1px solid;
    border-radius : 8px;
    border-spacing : 2px;
    font-size : 80%;
    display : inline-table;
    cursor : pointer;
}
table.mybutton:hover {
    background-color : black;
    color : white;
}

I've managed to get it to visit one of two URLs depending on whether the Shift key is held down via this Javascript:
var shift = false;

function shiftHandler(event) {
    shift = event.shiftKey;
};

window.addEventListener("keydown", shiftHandler, false);
window.addEventListener("keypress", shiftHandler, false);
window.addEventListener("keyup", shiftHandler, false);

function goSomewhere(url1, url2) {
    if (shift) {
        window.location.href = url2;
    } else {
        window.location.href = url1;
    }
}

function goSomewhereElse(url) {
    window.location.href = url;
}

The last piece is that I'd like the background color of the button while hovering to change depending on whether the Shift key is held as well. Can this be done? Can it be done without extra libraries?
Example Fiddle

A: I would do it by changing an element's class when the key is pressed or released. Adding a line to your code:
function shiftHandler(event) {
    shift = event.shiftKey;
    document.body.className = shift ? 'shift-pressed' : '';
};

Then you can select that class in your CSS:
.shift-pressed table.mybutton:hover {
    background-color: green;
    color: white;
}

A: Sure. Use a 'mouseover' event attached to the button.
var element = document.getElementById("#button-id");
element.addEventListener("mouseover", function(event) {
    if (shift) {
         //make the color change here
    }
})


text:
Q: how to read a file line by line and append some string each line? I want to open a file and then read it line by line. In some lines I want to append a string to exactly this line. Is this possible?
I have a code for opening the file and reading it like the following:
File file = new File("MyFile.txt");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));

String line = null;

try {
    while((line = bufRdr.readLine()) != null)
    {
        // read line by line and append some string to the line

    }
} catch (IOException e) {
    // ...
}

but how can I append a string to the current line and write this to the file?

A: As you are reading file line by line. append your text to line and write it to other file. Say for example file with different name and later you can rename the file.
Just like
try {
   while((line = bufRdr.readLine()) != null)
    {
    // read line by line and append some string to the line
    //pseudo code
    newline = line + "yourtext";
    outputstreamtootherfile.write(newline);

    }
}

I think there is no way you can read and write to same file concurrently, as it holds read/write locks.
Thanks

A: Create new file and keep on writing to this file (as you read other file line by line) with the modification you want. Then delete the existing one and give the newly created file the name of deleted file.This is how i would approach it.
Here is the link which confirms this approach alongwith other alternatives.
Modify a .txt file in Java

A: *

*readLines read lines to List<String> and change some String (line) if you need it

*create new temp file

*write lines (or line by line) to it by append

*remove old file

*rename


text:
Q: subquery or condition not working in my project i want to execute this type of query but it returns error so please help me. i want this type of query to be execute.
SELECT
    *
FROM
    company_details
WHERE
    com_id NOT IN (SELECT com_id FROM com_size)
OR (SELECT com_id FROM com_cat)

above query returns error and i want com_id that is in company_details but not in com_size or com_cat table.and i also try this.
SELECT
    *
FROM
    company_details
LEFT JOIN com_size ON com_size.com_id != company_details.com_id
LEFT JOIN com_cat ON com_cat.com_id != company_details.com_id

A: Try this:
select * from company_details
where
    com_id not in (select com_id from com_size) AND
    com_id not in (select com_id from com_cat)

A: Note:  You should probably use not exists rather than not in:
select cd.*
from company_details cd
where not exists (select 1 from com_size cs where cs.com_id = cd.com_id) and
      not exists (select 1 from com_cat cc where cc.com_id = cd.com_id);

The reason not exists is better is because of how it handles NULL values in the subquery:  if any of the values are NULL, then all comparisons fail (either "false" or NULL).
As an added bonus, not exists is often faster in MySQL.


text:
Q: VB.net Receiving error BC30201: Expression expected Im using this to declare a connection to a SQL
Public CONN As New SqlConnection("Data Source=" & My.Settings.SrvName & ";Initial Catalog=" & My.Settings.Catalog & ";Persist Security Info=" & True & ";User ID=" & My.Settings.USER & ";Password=" & My.Settings.PASSWRD & ";Integratedsecurity=" & My.Settings.InterSec & ";Connection Timeout=" & My.Settings.CnnTimeOut &)

but on the Closing ')' Im getting the error BC30201: Expression expected, this same method Ihave use in other proyects and works, can anyone tell me where my error?, please help.
Thanks.

A: This is a fine example of why lots of string concatenation is a bad idea. Your code is hard to read - even for you, obviously - and so it's error prone. With all those & operators in there, you haven't noticed that you have one you don't need at the end, This:
& My.Settings.CnnTimeOut &)

should be this:
& My.Settings.CnnTimeOut)

You should avoid using multiple & operators in one line and instead use the String.Format method or string interpolation. In this case, don't use any of those options. You should be using a SqlConnectionStringBuilder, e.g.
Dim builder As New SqlConnectionStringBuilder With {.DataSource = My.Settings.SrvName,
                                                    .InitialCatalog = My.Settings.Catalog}

Using connection As New SqlConnection(builder.ConnectionString)
    '...
End Using

Notice that I have created the connection with a Using statement, which is what you should be doing too. Don't use a single, common connection. You can use a single connection string builder to generate the connection string, but you should then create, use and destroy connection objects where and when you need them.
Note that you can set as many properties of the connection string builder as you need to when you create it. I have just set two here for brevity.


text:
Q: How to run a script when accessing a specific non existing path? I have some path I have to access, which is the result of mounting.
I would like the mounting to be automatic, via a script, and I want that script to run just before an error is thrown from not being able to access the path.
For example, assume the script is
echo scripting!
mkdir -p /non_existing_path

and I want it to run when trying to access (in any way) to the path /non_existing_path.
So when I do for example
cd /non_existing_path

or
touch /non_existing_path/my_file.txt

It would always succeed, with the output scripting!. In reality, the script would be more elaborated than that.

Is this possible at all?


text:
Q: Cocoa: basic problem getting string from file Is there some blindingly obvious reason why this is producing a nil string instead of the actual text content of the file?
NSString *fromFile = [NSString stringWithContentsOfFile:
                       @"file://localhost/Users/username/Desktop/test.txt"];

NSLog(@"%@", fromFile);

PRINTS: "(null)"

The file is a plain ASCII text file saved from TextWrangler with contents ' abc '.
The path comes from dragging the actual file from the desktop into the Xcode editor window.
I've also tried without "file://localhost".
The method documentation says "Returns nil if the file can't be opened". There's nothing unusual about the file (not locked, etc.). It has default Unix permissions and was created by the same user as is running Xcode.
I know this method is deprecated -- trying to get this working first.

A: You have stringWithContentsOfFile: and stringWithContentsOfURL: mixed up.
If you are passing in a URL e.g.
 @"file://localhost/Users/username/Desktop/test.txt"
the you want stringWithContentsOfURL: and make the parameter a NSURL e.g.
[NSURL URLWithString:@"file://localhost/Users/username/Desktop/test.txt"]
If you want to use stringWithContentsOfFile: the the parameter should be
@"/Users/username/Desktop/test.txt"

A: Have you tried ~/Desktop/test.txt or /Users/username/Desktop/test.txt?


text:
Q: multiprocess or multithread? - parallelizing a simple computation for millions of iterations and storing the result in a single data structure I have a dictionary D of {string:list} entries, and I compute a function
f( D[s1],D[s2] ) --> float
for a pair of strings (s1,s2) in D.
Additionally,
I have created a custom matrix class LabeledNumericMatrix that allows me to perform assignments such as m[ ID1, ID2 ] = 1.0 .
I need to calculate f(x,y) and store the result in m[x,y] for all 2-tuples in the set of strings S, including when s1=s2.
This is easy to code as a loop, but execution of this code takes quite some time as the size of the set S grows to large values such as 10,000 or more.
None of the results I store in my labeled matrix m depend on each other.
Therefore, it seems straightforward to parallelize this computation by using python's multithread or multiprocess services.
However, since cPython doesn't truly allow my to simultaneously execute calculation of f(x,y) and storage of m[x,y] through threading, it seems that multiprocess is my only choice.
However, I don't think multiprocess is designed to pass around 1GB data structures between processes, such as my labelled matrix structure containing 10000x10000 elements.
Can anyone provide advice of (a) if I should avoid trying to parallelize my algorithm, and (b) if I can do the parallelization, how to do such, preferably in cPython?

A: First option - a Server Process
Create a Server process. It's part of the Multiprocessing package which allows parallel access to data structures. This way every process will access the data structure directly, locking other processes.
From the documentation:

Server process
A manager object returned by Manager() controls a server process which
holds Python objects and allows other processes to manipulate them
using proxies.
A manager returned by Manager() will support types list, dict,
Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event,
Queue, Value and Array.

Second option - Pool of workers
Create a Pool of workers, an input Queue and a result Queue.

*

*The main process, acting as a producer, will feed the input queue with pairs (s1, s2).

*Each worker process will read a pair from the input Queue, and write the result into the output Queue.

*The main thread will read the results from the result Queue, and write them into the result dictionary.

Third option - divide to independent problems
Your data is independent: f( D[si],D[sj] ) is a secluded problem, independent of any f( D[sk],D[sl] ) . furthermore, the computation time of each pair should be fairly equal, or at least in the same order of magnitude.
Divide the task into n inputs sets, where n is the number of computation units (cores, or even computers) you have. Give each input set to a different process, and join the output.

A: You definitely won't get any performance increase with threading - it is an inappropriate tool for cpu-bound tasks.
So the only possible choice is multiprocessing, but since you have a big data structure, I'd suggest something like mmap (pretty low level, but builtin) or Redis (tasty and high level API, but should be installed and configured).

A: Have you profiled your code?  Is it just calculating f that is too expensive, or storing the results in the data structure (or maybe both)?
If f is dominant, then you should make sure you can't make algorithmic improvements before you start worrying about parallelization.  You might be able to get a big speed up by turning some or all of the function into a C extension, perhaps using cython.  If you do go with multiprocessing, then I don't see why you need to pass the entire data structure between processes?
If storing results in the matrix is too expensive, you might speed up your code by using a more efficient data structure (like array.array or numpy.ndarray).  Unless you have been very careful designing and implementing your custom matrix class, it will almost certainly be slower than those.

A: Thank you everyone for your responses.
I have created a solution (not "the" solution) to the proposed problem, and since others may find it useful, I am posting the code here.  My solution is a hybrid of options 1 and 3 suggested by Adam Matan.  The code contains line numbers from my vi session, which will help in the discussion below.
 12 # System libraries needed by this module.
 13 import numpy, multiprocessing, time
 14
 15 # Third-party libraries needed by this module.
 16 import labeledMatrix
 17
 18 # ----- Begin code for this module. -----
 19 from commonFunctions import debugMessage
 20
 21 def createSimilarityMatrix( fvFileHandle, fvFileParser, fvSimScorer, colIDs, rowIDs=None,
 22                             exceptionType=ValueError, useNumType=numpy.float, verbose=False,
 23                             maxProcesses=None, processCheckTime=1.0 ):
 24  """Create a labeled similarity matrix from vectorial data in [fvFileHandle] that can be
 25  parsed by [fvFileParser].
 26  [fvSimScorer] should be a function that can return a floating point value for a pair of vectors.
 27
 28  If the matrix [rowIDs] are not specified, they will be the same as the [colIDs].
 29
 30  [exceptionType] will be raised when a row or column ID cannot be found in the vectorial data.
 31  [maxProcesses] specifies the number of CPUs to use for calculation; default value is all available CPUs.
 32  [processCheckTime] is the interval for checking activity of CPUs (if completed calculation or not).
 33
 34  Return: a LabeledNumericMatrix with corresponding row and column IDs."""
 35
 36  # Setup row/col ID information.
 37  useColIDs = list( colIDs )
 38  useRowIDs = rowIDs or useColIDs
 39  featureData = fvFileParser( fvFileHandle, retainIDs=(useColIDs+useRowIDs) )
 40  verbose and debugMessage( "Retrieved %i feature vectors from FV file." % len(featureData) )
 41  featureIDs = featureData.keys()
 42  absentIDs = [ ID for ID in set(useColIDs + useRowIDs) if ID not in featureIDs ]
 43  if absentIDs:
 44   raise exceptionType, "IDs %s not found in feature vector file." % absentIDs
 45  # Otherwise, proceed to creation of matrix.
 46  resultMatrix = labeledMatrix.LabeledNumericMatrix( useRowIDs, useColIDs, numType=useNumType )
 47  calculateSymmetric = True if set( useRowIDs ) == set( useColIDs ) else False
 48
 49  # Setup data structures needed for parallelization.
 50  numSubprocesses = multiprocessing.cpu_count() if maxProcesses==None else int(maxProcesses)
 51  assert numSubprocesses >= 1, "Specification of %i CPUs to calculate similarity matrix." % numSubprocesses
 52  dataManager = multiprocessing.Manager()
 53  sharedFeatureData = dataManager.dict( featureData )
 54  resultQueue = multiprocessing.Queue()
 55  # Assign jobs evenly through number of processors available.
 56  jobList = [ list() for i in range(numSubprocesses) ]
 57  calculationNumber = 0 # Will hold total number of results stored.
 58  if calculateSymmetric: # Perform calculations with n(n+1)/2 pairs, instead of n^2 pairs.
 59   remainingIDs = list( useRowIDs )
 60   while remainingIDs:
 61    firstID = remainingIDs[0]
 62    for secondID in remainingIDs:
 63     jobList[ calculationNumber % numSubprocesses ].append( (firstID, secondID) )
 64     calculationNumber += 1
 65    remainingIDs.remove( firstID )
 66  else: # Straight processing one at a time.
 67   for rowID in useRowIDs:
 68    for colID in useColIDs:
 69     jobList[ calculationNumber % numSubprocesses ].append( (rowID, colID) )
 70     calculationNumber += 1
 71
 72  verbose and debugMessage( "Completed setup of job distribution: %s." % [len(js) for js in jobList] )
 73  # Define a function to perform calculation and store results
 74  def runJobs( scoreFunc, pairs, featureData, resultQueue ):
 75   for pair in pairs:
 76    score = scoreFunc( featureData[pair[0]], featureData[pair[1]] )
 77    resultQueue.put( ( pair, score ) )
 78   verbose and debugMessage( "%s: completed all calculations." % multiprocessing.current_process().name )
 79
 80
 81  # Create processes to perform parallelized computing.
 82  processes = list()
 83  for num in range(numSubprocesses):
 84   processes.append( multiprocessing.Process( target=runJobs,
 85                                              args=( fvSimScorer, jobList[num], sharedFeatureData, resultQueue ) ) )
 86  # Launch processes and wait for them to all complete.
 87  import Queue # For Queue.Empty exception.
 88  for p in processes:
 89   p.start()
 90  assignmentsCompleted = 0
 91  while assignmentsCompleted < calculationNumber:
 92   numActive = [ p.is_alive() for p in processes ].count( True )
 93   verbose and debugMessage( "%i/%i complete; Active processes: %i" % \
 94               ( assignmentsCompleted, calculationNumber, numActive ) )
 95   while True: # Empty queue immediately to avoid underlying pipe/socket implementation from hanging.
 96    try:
 97     pair, score = resultQueue.get( block=False )
 98     resultMatrix[ pair[0], pair[1] ] = score
 99     assignmentsCompleted += 1
100     if calculateSymmetric:
101      resultMatrix[ pair[1], pair[0] ] = score
102    except Queue.Empty:
103     break
104   if numActive == 0: finished = True
105   else:
106    time.sleep( processCheckTime )
107  # Result queue emptied and no active processes remaining - completed calculations.
108  return resultMatrix
109 ## end of createSimilarityMatrix()

Lines 36-47 are simply preliminary stuff related to the problem definition that was a part of the original question.
The setup for the multiprocessing to get around cPython's GIL is in lines 49-56, with lines 57-70 used to evenly create the subdivided tasks.  Code in lines 57-70 is used instead of itertools.product, because when the list of row/column IDs reaches 40,000 or so, the product ends up taking an enormous amount of memory.
The actual computation to be performed is in lines 74-78, and here the shared dictionary of ID->vector entries and shared result queue are utilized.
Lines 81-85 setup the actual Process objects, though they haven't actually been started yet.
In my first attempt (not shown here), the "try ... resultQueue.get() and assign except ..." code was actually located outside of the outer control loop (while not all calculations finished).  When I ran that version of the code on a unit test of a 9x9 matrix, there were no problems.
However, moving up to 200x200 or larger, I found this code to hang, despite not changing anything in the code between executions.
According to this discussion (http://bugs.python.org/issue8426) and the official documentation for multiprocess, the use of multiprocess.Queue can hang if the underlying implementation doesn't have a very large pipe/socket size.  Therefore, the code given here as my solution periodically empties the queue while checking on completion of processes (see lines 91-106) so that the child processes can continue to put new results in it and avoid the pipe being overfull.
When I tested the code on larger matrices of 1000x1000, I noticed that the computation code finished well ahead of the Queue and matrix assignment code.  Using cProfile, I found that one bottleneck was the default polling interval processCheckTime=1.0 (line 23), and lowering this value improved the speed of results (see bottom of post for timing examples).  This might be useful information for other people new to multiprocessing in Python.
Overall, this probably is not be the best implementation possible, but it does provide a starting point for further optimization.  As is often said, optimization via parallelization requires proper analysis and thought.
Timing examples, all with 8 CPUs.

200x200 (20100 calculations/assignments)
t=1.0 : execution time 18s
t=0.01: execution time 3s
500x500 (125250 calculations/assignments)
t=1.0 : execution time 86s
t=0.01: execution time 23s

In case anyone wants to copy-and-paste the code, here is a unit-test I used for part of the development.  Obviously, the labelled matrix class code is not here, and the fingerprint reader/scorer code is not included (though it is pretty simple to roll your own).  Of course, I'm happy to share that code as well if would help someone.
112 def unitTest():
113  import cStringIO, os
114  from fingerprintReader import MismatchKernelReader
115  from fingerprintScorers import FeatureVectorLinearKernel
116  exampleData = cStringIO.StringIO() # 9 examples from GPCR (3,1)-mismatch descriptors, first 10 columns.
117  exampleData.write( ",AAA,AAC,AAD,AAE,AAF,AAG,AAH,AAI,AAK"  + os.linesep )
118  exampleData.write( "TS1R2_HUMAN,5,2,3,6,8,6,6,7,4" + os.linesep )
119  exampleData.write( "SSR1_HUMAN,11,6,5,7,4,7,4,7,9" + os.linesep )
120  exampleData.write( "OXYR_HUMAN,27,13,14,14,15,14,11,16,14" + os.linesep )
121  exampleData.write( "ADA1A_HUMAN,7,3,5,4,5,7,3,8,4" + os.linesep )
122  exampleData.write( "TA2R_HUMAN,16,6,7,8,9,10,6,6,6" + os.linesep )
123  exampleData.write( "OXER1_HUMAN,10,6,5,7,11,9,5,10,6" + os.linesep )
124  exampleData.write( "NPY1R_HUMAN,3,3,0,2,3,1,0,6,2" + os.linesep )
125  exampleData.write( "NPSR1_HUMAN,0,1,1,0,3,0,0,6,2" + os.linesep )
126  exampleData.write( "HRH3_HUMAN,16,9,9,13,14,14,9,11,9" + os.linesep )
127  exampleData.write( "HCAR2_HUMAN,3,1,3,2,5,1,1,6,2" )
128  columnIDs = ( "TS1R2_HUMAN", "SSR1_HUMAN", "OXYR_HUMAN", "ADA1A_HUMAN", "TA2R_HUMAN", "OXER1_HUMAN",
129                "NPY1R_HUMAN", "NPSR1_HUMAN", "HRH3_HUMAN", "HCAR2_HUMAN", )
130  m = createSimilarityMatrix( exampleData, MismatchKernelReader, FeatureVectorLinearKernel, columnIDs,
131                              verbose=True, )
132  m.SetOutputPrecision( 6 )
133  print m
134
135 ## end of unitTest()

A: In reference to my last comment attached to the code posted on March 21, I found multiprocessing.Pool + SQLite (pysqlite2) unusable for my particular task, as two problems occurred:
(1) Using the default connection, except for the first worker, every other worker process that performed an insert query only executed once.
 (2) When I change the connection keywords to check_same_thread=False, then the full pool of workers is used, but then only some queries succeed and some queries fail.  When each worker also executed time.sleep(0.01), the number of query failures was reduced, but not entirely.
 (3) Less importantly, I could hear my hard disk reading/writing frantically, even for a small job list of 10 insert queries.
I next resorted to MySQL-Python, and things worked out much better.  True, one must setup the MySQL server daemon, a user, and a database for that user, but those steps are relatively simple.
Here is sample code that worked for me.  Obviously it could be optimized, but it conveys the basic idea for those who are looking for how to get starting using multiprocessing.
  1 from multiprocessing import Pool, current_process
  2 import MySQLdb
  3 from numpy import random
  4
  5
  6 if __name__ == "__main__":
  7
  8   numValues   = 50000
  9   tableName   = "tempTable"
 10   useHostName = ""
 11   useUserName = ""  # Insert your values here.
 12   usePassword = ""
 13   useDBName   = ""
 14
 15   # Setup database and table for results.
 16   dbConnection = MySQLdb.connect( host=useHostName, user=useUserName, passwd=usePassword, db=useDBName )
 17   topCursor = dbConnection.cursor()
 18   # Assuming table does not exist, will be eliminated at the end of the script.
 19   topCursor.execute( 'CREATE TABLE %s (oneText TEXT, oneValue REAL)' % tableName )
 20   topCursor.close()
 21   dbConnection.close()
 22
 23   # Define simple function for storing results.
 24   def work( storeValue ):
 25     #print "%s storing value %f" % ( current_process().name, storeValue )
 26     try:
 27       dbConnection = MySQLdb.connect( host=useHostName, user=useUserName, passwd=usePassword, db=useDBName )
 28       cursor = dbConnection.cursor()
 29       cursor.execute( "SET AUTOCOMMIT=1" )
 30       try:
 31         query = "INSERT INTO %s VALUES ('%s',%f)" % ( tableName, current_process().name, storeValue )
 32         #print query
 33         cursor.execute( query )
 34       except:
 35         print "Query failed."
 36
 37       cursor.close()
 38       dbConnection.close()
 39     except:
 40       print "Connection/cursor problem."
 41
 42
 43   # Create set of values to assign
 44   values = random.random( numValues )
 45
 46   # Create pool of workers
 47   pool = Pool( processes=6 )
 48   # Execute assignments.
 49   for value in values: pool.apply_async( func=work, args=(value,) )
 50   pool.close()
 51   pool.join()
 52
 53   # Cleanup temporary table.
 54   dbConnection = MySQLdb.connect( host=useHostName, user=useUserName, passwd=usePassword, db=useDBName )
 55   topCursor = dbConnection.cursor()
 56   topCursor.execute( 'DROP TABLE %s' % tableName )
 57   topCursor.close()
 58   dbConnection.close()


text:
Q: Composite Component doesn't work when attribute expression bind I've made a composite component which seems to works fine if used in a "static" way but it doesn't work if I bind one of its attributes to an expression.
If I use my component like
<ez:indicadorEstadoSubsistema subSystemName="Server"
status="someIntLiteral"/>
works fine but I need to use it in a more dynamic way, like
<ez:indicadorEstadoSubsistema subSystemName="Server"
status="#{serverData.status}"/>.
I've read that JSTL tags run on view build time instead view rendering time, so thats maybe the reason I'm not getting the status expression bind evaluated at the right time, but I don't know how to workaround this.
My component is just an image with a tooltip. Both of them depend on the "status" attribute value.
Component
<cc:interface>
    <cc:attribute name="status" shortDescription="Represents the SubSystem status." required="true" default="1" type="java.lang.Integer"/>
    <cc:attribute name="subSystemName" required="true" type="java.lang.String"/>
</cc:interface>

<cc:implementation>
    <c:choose>
        <c:when test="#{cc.attrs.status eq 0}">
            <h:graphicImage id="icon" value="#{resource['images:delete.png']}" width="16" height="16"/>
            <c:set var="message" value="#{cc.attrs.subSystemName} subsystem doesn't responds."/>
        </c:when>
        <c:when test="#{cc.attrs.status eq 1}">
            <h:graphicImage id="icon" value="#{resource['images:delete.png']}" width="16" height="16"/>
            <c:set var="message" value="Unconsistent status."/>
        </c:when>
        <c:when test="#{cc.attrs.status eq 2}">
            <h:graphicImage id="icon" value="#{resource['images:warning.png']}" width="16" height="16"/>
            <c:set var="message" value="#{cc.attrs.subSystemName} system not working properly."/>
        </c:when>
        <c:when test="#{cc.attrs.status eq 3}">
            <h:graphicImage id="icon" value="#{resource['images:check.png']}" width="16" height="16"/>
            <c:set var="message" value="#{cc.attrs.subSystemName} system works fine."/>
        </c:when>
    </c:choose>
    <p:tooltip for="icon" value="#{message}" showEffect="fade" hideEffect="fade" />
</cc:implementation>

Thank you.

A: Generally, it's not a good idea to use JSTL tags in JSF. Why don't you use <h:panelGroup>? Try something like this:
<h:panelGroup rendered="#{cc.attrs.status eq 0}">
    <h:graphicImage id="icon" value="#{resource['images:delete.png']}" width="16" height="16"/>
    <ui:param var="message" value="#{cc.attrs.subSystemName} subsystem doesn't responds."/>
</h:panelGroup>
<p:tooltip for="icon" value="#{message}" showEffect="fade" hideEffect="fade" />


text:
Q: output clause VS triggers On our database, most tables have a dbupddate field which indicates the datetime of the last INSERT or UPDATE applied at the row.
In order to avoid this field having an erroneous value, there exist triggers (sometimes AFTER, sometimes INSTEAD OF) which make sure that in the end, the value is correct and not whatever "manual" other value someone might try to write into that field.
Now I am performing an update statement (actualy MERGE) and I want to have an OUTPUT clause including that field. As I've read in the appropriate MS article, OUTPUT ignores triggers.
Is there any workaround to have OUTPUT return the value dbupddate has after the triggers? I don't want to make another query to draw the info, because I am not guaranteed that in the split second between those queries, a third query of another user might not have changed quite everything.

Results after following Larnu's suggestions
I ran the examples provided, with the only exception of changing the default values of the updatetime fields to convert(datetime2,'1900-01-01') so that I might make some sense. I ran each of the 4 queries, followed by a select from their respective table and compared the updatetime values:
INSERT INTO dbo.Sample1 (Someint)
OUTPUT inserted.*
INTO @inserted
SELECT 1;

SELECT 'Sample1 INSERT',*
FROM @inserted; -- 1900-01-01 00:00:00.000000
select * from Sample1  -- 2018-11-05 13:12:13.141580

I guess the output here ignores the trigger and returns the default value that was inserted before the after trigger took effect.
DECLARE @inserted table (ID int, Someint int, updatedtime datetime2(6))
INSERT INTO dbo.Sample2 (Someint)
OUTPUT inserted.*
INTO @inserted
SELECT 1;

SELECT 'Sample2 INSERT',* --1900-01-01 00:00:00.000000
FROM @inserted;
select * from Sample2 --2018-11-05 13:12:35.580190

Same. Now the crazy part comes. I drew both the inserted and the deleted dates out:
DECLARE @updated table (ID int, Someint int, ins_updatedtime datetime2(6),del_updatedtime datetime2(6))
UPDATE dbo.Sample1
SET Someint = 2
OUTPUT Inserted.*,Deleted.updatetime
INTO @updated;

SELECT 'Sample1 UPDATE',*
FROM @updated;   --Sample1 UPDATE   1   2   2018-11-05 13:30:01.348490  2018-11-05 13:30:01.348490
select * from Sample1  -- 1 2   2018-11-05 13:31:31.851047

DECLARE @updated table (ID int, Someint int, ins_updatedtime datetime2(6),del_updatedtime datetime2(6))
UPDATE dbo.Sample2
SET Someint = 2
OUTPUT Inserted.*,Deleted.updatetime
INTO @updated;

SELECT 'Sample2 UPDATE',* -- Sample2 UPDATE 1   2   2018-11-05 13:30:20.286422  2018-11-05 13:30:20.286422
FROM @updated;
select * from Sample2 --1   2   2018-11-05 13:31:51.679726

So, in the update cases, the default value is not present, but I have different values in the actual table and in the query's output. I know neither how to make these values the same, nor what exactly happens with the datetimes in the update case.

A: You can use OUTPUT with a TRIGGER but you also have to make use of the INTO clause as well. Take these sample tables and triggers:
CREATE TABLE dbo.Sample1 (SomeID int IDENTITY(1,1),
                          Someint int,
                          updatetime datetime2(6) DEFAULT SYSDATETIME());
CREATE TABLE dbo.Sample2 (SomeID int IDENTITY(1,1),
                          Someint int,
                          updatetime datetime2(6) DEFAULT SYSDATETIME());

GO

CREATE TRIGGER dbo.AfterInsertUdpate ON dbo.Sample1
AFTER INSERT, UPDATE
AS
    UPDATE S
    SET S.updatetime = SYSDATETIME()
    FROM dbo.Sample1 S
         JOIN Inserted i ON S.SomeID = i.SomeID;
GO

CREATE TRIGGER dbo.InsteadInsert ON dbo.Sample2
INSTEAD OF INSERT
AS
    INSERT INTO dbo.Sample2 (Someint,
                             updatetime)
    SELECT Someint, SYSDATETIME()
    FROM Inserted;

GO

CREATE TRIGGER dbo.InsteadUpdate ON dbo.Sample2
INSTEAD OF UPDATE
AS
    UPDATE S
    SET S.Someint = i.Someint,
        S.updatetime = SYSDATETIME()
    FROM dbo.Sample2 S
         JOIN Inserted i ON S.SomeID = i.SomeID;

If we were to run the following SQL you would get an error:
INSERT INTO dbo.Sample1 (Someint)
OUTPUT inserted.*
SELECT 1;

Msg 334, Level 16, State 1, Line 44
  The target table 'dbo.Sample1' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.

The error gives you the tip here, use the INTO clause. Thus you can, instead, do:
DECLARE @inserted table (ID int, Someint int, updatedtime datetime2(6))

INSERT INTO dbo.Sample1 (Someint)
OUTPUT inserted.*
INTO @inserted
SELECT 1;

SELECT 'Sample1 INSERT',*
FROM @inserted;

This works for both INSERT and UPDATE, regardless of if it's AFTER or INSTEAD OF:
DECLARE @inserted table (ID int, Someint int, updatedtime datetime2(6))
INSERT INTO dbo.Sample2 (Someint)
OUTPUT inserted.*
INTO @inserted
SELECT 1;

SELECT 'Sample2 INSERT',*
FROM @inserted;

GO
DECLARE @updated table (ID int, Someint int, updatedtime datetime2(6))
UPDATE dbo.Sample1
SET Someint = 2
OUTPUT Inserted.*
INTO @updated;

SELECT 'Sample1 UPDATE',*
FROM @updated;

GO
DECLARE @updated table (ID int, Someint int, updatedtime datetime2(6))
UPDATE dbo.Sample2
SET Someint = 2
OUTPUT Inserted.*
INTO @updated;

SELECT 'Sample2 UPDATE',*
FROM @updated;
GO

--Clean up
DROP TABLE dbo.Sample1;
DROP TABLE dbo.Sample2;


text:
Q: Fastapi async sql unique constraint throws Internal Server Error. Instead of returning a error message I am using FastAPI and Async SQl. I have defined the schema with email unique. But when I pass the same email to the FastAPI route. It throws error on development server
sqlite3.IntegrityError: UNIQUE constraint failed: users.email and returns a 500 Internal response via Postman. I want to show error as a message and not 500 error what should I do ?

A: what is happening is an Error that the client should NOT have access to,
there is a difference between validation errors that YOU define and between the ORM and database engine errors the library shows,
what you should do is check why are you sending a database query with an empty email! if you do so, the SQL engine will tell you that you can not put a NULL value there, which is something you did set.
there should be a validation before sending the query to the DB,
in FastApi, such validation should be done with Pydantic models.
EDIT:
thanks to @Mecid X Recebli for his comment, I think the question has been changed and my answer is no longer valid. \
I answered as if you are sending an empty value of email to DB query, but your question says that you are sending a duplicate email,
you should do email validation in the Pydantic schema, and that is by querying the DB for that email, if you have an account with the same email, raise a validation exception inside the validation method in the pydantic shema.


text:
Q: Switch statement with two arguments I have a question related to switch statement with 2 arguments. I do not understand which value to look for. I've read somewhere that comma(,) is equal to AND,but that is not helping me much since when debugging it goes to case 1,case 1,and then default,so I  really don't get it.
Any help would be appreaciated,Thanks!
#define ADD(x, y) x+y
#define MUL(x, y) x*y
void main() {
    int arr[6] = { 012, -2, 7 - 011, 0x1F, 3 }, res = 0;
    int n = sizeof(arr) / sizeof(int), i, j;
    for (i = -1, j = n; i <= n / 2;) {
        switch (--j, ++i) {
        case 0: res += MUL(arr[i], arr[j]);
        case 1: res += ADD(arr[i], arr[j]); break;
        case 4: res += MUL(ADD(arr[i], arr[j]), ADD(arr[i + 1], res));
        default: res++; break;
        }
    }
    printf("%d", res);
} ```

A: Operator comma is not equal to  AND. Operator comma evaluates operands from left to right, and returns the last result. Thus,
switch (--j, ++i) {

i = 0;
it goes to the case 0, you don`t have break statement so you go to the case 1


text:
Q: Port forward from OpenShift via Java How to programmatically execute
oc port-forward <podName> <podPort>:<localPort>

via Java?
At the moment I managed to get the list of pods under through the library io.fabric8:openshift-client.
OpenShiftClient config = new DefaultOpenShiftClient();
client.pods().inNamespace("namespace").list().getItems();

But in this library don't exist port-forwarding functionality and I didn't find any information on the net

A: Something like this works like a charm :
OpenShiftClient client = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class);

Resource<Namespace> openShiftProject = client.namespaces().withName(yourNamespace);

PodResource openShiftPod = client.pods().inNamespace(yourNamespace).withName(yourPodName);

openShiftPod.portForward(REMOTE_PORT_NBR, LOCAL_PORT_NBR);

Feel free to add some checks (isReady for instance) to secure your code.  And don't forget to close the client once its job is over.


text:
Q: Visual Studio: Exclude Project by default when running tests from test explorer I've added an integration test project to my solution and I'd like to not run them by default when using the test explorer.
The only solution I've come across to isolate these tests is to manually categorize them and choose not to run tests with a particular trait from test explorer. Ideally, I could exclude them so that people on my project don't have to make this choice explicitly.
Thanks!

A: There is a special attribute in NUnit to mark your tests that should not be run automatically.

[Explicit]
The Explicit attribute causes a test or test fixture to be skipped unless it is explicitly selected for running.
https://github.com/nunit/docs/wiki/Explicit-Attribute

You just put it on the class or method:
[TestFixture]
[Explicit]
public class IntegrationTests
{
    // ...
}

[TestFixture]
public class UnitTests
{
    [Test]
    public void ShouldNotFail()
    {
         // This will run
    }

    [Test]
    [Explicit]
    public void ManualTest()
    {
        // This will be ignored
    }
}

This is the result:


text:
Q: Create Delay Before Typing "No Results Found" to Screen I am trying to print a "No Results Found" message if a user's search query finds no results in my Angular2 app. I am also trying to delay this from happening because there is a delay set on the search query evaluation itself, and right now "No Results Found" prints to the screen for a millisecond, while the delay on the query happens. Then the "No Results Found" disappears while the query is evaluated, and then reappears if no results are indeed found. So the issue is that millisecond printing of the message to the screen prematurely because of the delay set on the query. I have tried wrapping the function in a timeout to match the delay, like this:
setTimeout(noResultsFound, 2000);

    noResultsFound(): boolean
    {
        if (this.query && !this.hasResults) {
        return true;
    }

And my view code is like this:
<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div>

But it's not working, and I'm getting an error message saying "Function declaration my be 'setTimeout". Is this something you can't do in Typescript? Is there an alternative? What am I missing here?

A: This code:
 setTimeout(noResultsFound, 2000);
 noResultsFound(): boolean

Has a few things wrong:

*

*noResultsFound is not a global. Its a class member. Thus you need this e.g. setTimeout(this.noResultsFound, 2000);.

*If you use this you need to be aware of its issues (its a JavaScript thing). Recommend an arrow so noResultsFound(): boolean becomes noResultsFound = (): boolean =>. More : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

*Don't use setTimeout for debouncing. Use a better functional approach e.g. underscore.debounce
Hope that helps.


text:
Q: Sar data not collected for 10 minutes We have a RedHat server whose only job is to run a JBoss server.  Monitors said that memory usage spiked (we have the JVM limited to far less than the total memory on the system) and JBoss crashed.  We restarted and everything seems ok now.
Odd thing is that sar data for 10 min leading up to the crash is simply not there.  Load average got up to the 50s.  I have seen severely busy systems (350+ Load Average) still collect sar data.  Does anyone have any idea what could cause sar to stop collecting data?

A: Turns out we were out of memory and swap space.  Question now becomes (for another thread) what would cause a JBoss instance take up at least 4 more GB of memory than it is allocated in perm space and heap?


text:
Q: Text Environments: Vertical and Horizontal How does one obtain two text environments in TeX - one vertical, one horizontal, as in the attached image? It would be useful to be able to specify two text environments per page akin to something like this:
\vertical{This text appears on the side}

\horizontal{This text appears horizontally}

While being able to specify the width available to text appearing vertically and having the horizontal text naturally flow down the page naturally - as if were a document with shortened page width. I tried implementing this with minipage and rotation but was not able to create coherent environments. Is there a 'natural way' of doing this?

A:
I tried implementing this with minipage and rotation but was not able to create coherent environments.

This should be enough.

\documentclass{article}
\usepackage{graphicx,lipsum}
\begin{document}
\rotatebox[origin=c]{90}{%
\begin{minipage}{.7\textheight}
\lipsum[2]
\end{minipage}}
\hfill
\begin{minipage}[c][.7\textheight][t]{.65\linewidth}
\lipsum[1]
\end{minipage}
\end{document}


text:
Q: Heatmap: order y axis based on single x axis variable In my heatmap I would like to order Species based on percent value (decreasing) in Haul 1. Here is my current code:

ggplot(data, aes(Haul, Species)) + geom_tile(aes(fill = Percent)) +
  scale_fill_gradient(low = "white", high = "red") +
  labs(fill = "% Sites")+ theme_bw()

So the Species order should be b, c, d, a, based on decreasing Percent in Haul 1. I have tried using reorder() but can't find a way to specify the ordering based on Haul 1.

ggplot(data, aes(Haul, reorder(Species, Percent))) + geom_tile(aes(fill = Percent)) +
  scale_fill_gradient(low = "white", high = "red") +
  labs(fill = "% Sites")+ theme_bw()

My dataframe is set up like this:
Species = rep(c("a","b","c","d"),3)
Haul = rep(c(1,2,3),4)
Percent = c(25,0,25,50,25,0,75,0,50,100,0,50)
data = data.frame(Species, Haul, Percent)

Thank you for your help!
Elise

A: In the reorder, we can use ifelse to make other haul values NA:
ggplot(data, aes(Haul, reorder(Species, ifelse(Haul == 1, Percent, NA), na.rm = TRUE))) +
  geom_tile(aes(fill = Percent)) +
  scale_fill_gradient(low = "white", high = "red") +
  labs(fill = "% Sites", y = "Species") +
  theme_bw()


text:
Q: Searching JTS STR tree Hi I've been following this tutorial http://googledevelopers.blogspot.com/2014/12/building-scalable-geofencing-api-on.html , and here's my problem,
I have a list of longitude and latitude coordinates that I've added to a JTS(Java Topology Suite) STR tree as Points.
Now I would like to send an area that is in the shape of a circle to the STR tree to find all of the Points that land in the circle.
    Coordinate center = new Coordinate(entity.getLongitude(), entity.getLatitude());
    GeometricShapeFactory gsf = new GeometricShapeFactory();

    gsf.setCentre(center);
    gsf.setNumPoints(20);
    **gsf.setSize(320.0);**
    Polygon poly = gsf.createCircle();
    Coordinate[] coordinates = poly.getCoordinates();

    //Create polygon from the coordinates.
    GeometryFactory fact = new GeometryFactory();

    LinearRing linear_ring = new GeometryFactory().createLinearRing(coordinates);

    Polygon polygon = new Polygon(linear_ring, null, fact);

    List<STRLeaf> items = strTree.query(polygon.getEnvelopeInternal());

However the result of the search sends back all of the data in the in the tree of longitude and latitude Points.  When I lower the size of the circle below 320 then I receive no results from the search of the STR tree.  Does anyone have experience with this ideally I would like to create the circle that finds all the points within a circle of ~7miles.
thanks for your time

A: It turns out that I had a silly mistake in the backend. When I added the items to the tree I mixed up the x and y coords, so that the Lat Longs were reversed. After switching them, I can now set the size of the circle to around 0.1 and it works well.


text:
Q: What is the benefit of copy over xcopy on the command line? I know that xcopy has more options however are there any benefits to using copy rather than xcopy?

A: *

*xcopy is an external program, while copy is part of the interpreter (cmd.exe, command.com). This means that xcopy might not be present on another machine or a rescue disk.
Since we have Windows and rescue CDs, that isn't really an issue anymore.

*copy can concatenate files.
copy file1 + file2 file3

creates a file (file3) which contains file1's and file2's contents.

*copy can copy more than just files.
For example,
copy con file

lets you write directly from the keyboard (console) to file.
Likewise, you can print a file using
copy file prn
copy file \\computer\printer

where the latter is for shared printers.
You can even combine the above: The command
copy con prn

lets you write directly to the printer.

A: I think the main difference is (or was) that xcopy is able to copy folder hierarchies and copy was intended to work on files only.
That being said, I don't think there is anything to gain (functionality- or performance-wise) from using copy.
Please note, even xcopy is outdated by today's standards. Robocopy is the new copy utility of choice on modern Windows platforms.
Also note that all the mentioned copy utilities have Wikipedia articles that could contain further information:

*

*http://en.wikipedia.org/wiki/Copy_(command)

*http://en.wikipedia.org/wiki/Xcopy

*http://en.wikipedia.org/wiki/Robocopy

A: Anyone remember DOS on dual floppy PCs? Xcopy minimises the number of read seeks by loading multiple files into memory on a single read to speed up the copy. Probably still makes a trivial speed improvement with HDDs.

A: If you consider Powershell a "command line" then there is another "copy" command available.  The Powershell "copy" apparently maps to a cmdlet.
One thing not mentioned by the other answers is that since Powershell expands a deeply embedded wildcard at the shell level, this command will work (only from PS not from DOS):
% copy G:\git\one\source\*\morePath\SomePattern*.dll destDir

while xcopy claims "file not found" since it accepts a single source.

A: One command line argument to pay attention to between copy and xcopy is /V.
While xcopy's help states /V has xcopy compare source and destination file sizes, copy does not state the method used to verify the copy was accurate.
I suspect, but do not know, if the internal command, copy, being primarily a file command verse a directory command, uses CRC or binary compare to verify the copied file.


text:
Q: Convergence of asymptotic series for $z^k/(z)_k$, $z\to\infty$ Let $z>0$, $k\in\Bbb Z$, and $(s)_n=\Gamma(s+n)/\Gamma(s)$ denote the Pochhammer symbol. According to DLMF 5.11.13 as $z\to\infty$:
$$
\frac{z^k}{(z)_k}\sim\sum_{\ell=0}^\infty\binom{-k}{\ell}B_\ell^{(1-k)}\frac{1}{z^\ell},
$$
where $B_n^{(k)}$ is the Norlund polynomial.

What conditions guarantee this asymptotic series converges?

What I have so far:
If $k=0,-1,-2,\dots$ then the series terminates after $1-k$ terms yielding
$$
\frac{z^k}{(z)_k}=\sum_{\ell=0}^{-k}\binom{-k}{\ell}B_\ell^{(1-k)}\frac{1}{z^\ell},
$$
which in this case converges for all $z>0$. Furthermore, if $k=1$ then $B_\ell^{(0)}=\delta_\ell$ so that
$$
\frac{1}{(z)_0}=1.
$$
Also, of $k=2$ then $B_\ell^{(-1)}=\frac{1}{\ell+1}$ so that
$$
\frac{z^2}{(z)_2}\sim\sum_{\ell=0}^\infty\binom{-2}{\ell}\frac{1}{\ell+1}\frac{1}{z^\ell}=\frac{1}{1+\frac{1}{z}},
$$
which obviously converges for $z>1$.

So what I still need is the case for $k=3,4,5,\dots$

Maybe one could use induction and noting that
$$
\frac{z^{k+1}}{(z)_{k+1}}=\frac{1}{1+\frac{k}{z}}\frac{z^k}{(z)_k}?
$$

A: Assume that $k \geq 2$ is an integer. You can write your expansion in terms of the Stirling numbers of the second kind as follows: $$
\frac{{z^k }}{{(z)_k }} \sim \sum\limits_{\ell  = 0}^\infty  {( - 1)^\ell  S(\ell  + k - 1,k - 1)\frac{1}{{z^\ell  }}} .
$$
From the asymptotics
$$
S(\ell  + k - 1,k - 1) \sim \frac{{(k - 1)^{\ell  + k - 1} }}{{(k - 1)!}}, \quad \ell \to +\infty
$$ we can see that the series converges if $k-1<|z|$ (you have to study the case $|z|=k-1$ separately). Alternatively, you can notice that the series is the Laurent expansion of the meromorphic function on the left-hand side. The function has simple poles at $z=-1,-2,\ldots,1-k$, whence the Laurent expansion will converge for $k-1<|z|$.

A: Piggybacking off @Gary's answer we also have the following proof by induction. There may be a couple refinements needed but this should work.
Setting $k=2$ we find
$$
\frac{z^2}{(z)_2}\sim\sum_{\ell=0}^\infty\binom{-2}{\ell}\frac{1}{\ell+1}\frac{1}{z^\ell}=\frac{1}{1+\frac{1}{z}},
$$
which converges absolutely for $z>2-1$. Now assume the series in question converges absolutely for $z>k-1$. It follows that
$$
\frac{z^{k+1}}{(z)_{k+1}}=\frac{1}{1+\frac{k}{z}}\frac{z^k}{(z)_k}=\sum_{\ell=0}^\infty(-k)^\ell \frac{1}{z^\ell} \sum_{\ell=0}^\infty  (-1)^\ell S(\ell+k-1,k-1)\frac{1}{z^\ell}.
$$
The first series converge if $z>k$ while the second converges absolutely if $z>k-1$. It follows that the product of these series must also converge if $z>k$. Furthermore,
$$
\begin{aligned}
\sum_{\ell=0}^\infty(-k)^\ell \frac{1}{z^\ell} \sum_{\ell=0}^\infty  (-1)^\ell S(\ell+k-1,k-1)\frac{1}{z^\ell}
&=\sum_{\ell=0}^\infty\sum_{m=0}^\ell(-k)^{\ell-m} (-1)^m S(m+k-1,k-1)\frac{1}{z^\ell}\\
&=\sum_{\ell=0}^\infty(-1)^\ell S(m+k,k)\frac{1}{z^\ell},
\end{aligned}
$$
where we have used this identity. But this is our asymptotic series for $k+1$; hence,
$$
\frac{z^{k}}{(z)_{k}}=\sum_{\ell=0}^\infty  (-1)^\ell S(\ell+k-1,k-1)\frac{1}{z^\ell}
$$
converges for $z>k-1$.


text:
Q: using Single/First methods to return multiple values in linq or lambda expression Consider the following examples, in all of which, I am trying to get the code and the name of a province/state having a known ID, into a single string variable, with a format like "CA-California":
string stateName = _repository.States.Single(s => s.StateId == stateId).Name;
string stateCode = _repository.States.Single(s => s.StateId == stateId).Code;
string stateCodeName = stateCode + "-" + stateName;

var state = _repository.States.Single(s => s.StateId == stateId);
string stateCodeName = state.Code + "-" + state.Name;

string stateCodeName = _repository.States.Where(s => s.StateId == stateId)
                                         .Select(s => s.Code + "-" + s.Name)
                                         .First();

In the first example, only the needed properties of the state are retrieved, but at the cost of running two different queries. The second example runs one query only, but it retrieves all of the properties of the state. The third example seems to be all right, but my question is if there is a way to use Single and First methods to retrieve an arbitrary number of properties from an object (or columns from a table), as opposed to getting them all or only one at a time?
Thank You

A:
my question is if there is a way to use Single and First methods to
  retrieve an arbitrary number of properties from an object (or columns
  from a table), as opposed to getting them all or only one at a time?

You can use an anonymous type to do this:
var state = _repository.States.Where(s => s.StateId == stateId)
     .Select(s => new { Code = s.Code, Name = s.Name })
     .First();

This will return an anonymous type with two properties: Code and Name.
(Whether you use First() or Single() depends on how you want the program to behave if there is more than one match. Single() would throw an exception if there was more than one.)

A: If you were to change the use of First() to Single() in your third example, you would have exactly the query you're looking for.
The query would return only the single result that you're expecting and would only return the fields (already concatenated) that you're interested in.