text:
Q: How to update Existing Server Name used on View (SQL Server 2014) using ASP.NET There is a Supply Management System that has been assigned to me, I have to study that for the customization request of the client. I have been searching for a while to find a  possible solutions for my scenario. But still no luck, however I got a back up plan to do so.
Here's the details(My new PC):
My local SQL Server Name : DEV01\SQLExpress
Database : S_Premium -      The database of the supply management system
               GeoBos         - This is dedicated for another system,                       I restored it for testing purposes to my local SQL Server Name.
S_Premium and GeoBos is dedicated to a different systems but the data being used is Integrated with each other.
Scenario:
I have been moved to another PC with another SQL Server.
The S_Premium is using 50+ Views and Stored procedures which some of their queries is integrated to the servername of GeoBos(Example Above).
S_Premium Views query example:
SELECT DISTINCT ..... FROM  LnkdSrvrBOSS.GEOBOS.BOS.T_OBR_Hdr
LnkdSrvrBOSS - came from GeoBos previous server name
GeoBos - database name
BOS.T_OBR_Hdr - is a table under database "GeoBos"

What I did is deleting the LnkdSrvrBOSS manualy for every Views/Stored Procedures(It worked), But my problem is I have to do it manually for all Views and stored procedures that causing me a long time process.
Question:
1.) Is there a query that can replace or update the "LnkdSrvrBOSS" of "SELECT DISTINCT ..... FROM  LnkdSrvrBOSS.GEOBOS.BOS.T_OBR_Hdr" from Views/Stored Procedure ?
2.) Do I really have to delete the "LnkdSrvrBOSS" manually(One by one)?
3.) Or should I create a another SQL Server name "LnkdSrvrBOSS" and restore the database in there?
Thank you!

A: Create a Linked-Server with the same Name on your local-machine


text:
Q: Why does principal component analysis give me drastically different results? The problem I am trying to solve is like this: given a blob in an image, I want to get its orientation to guide me draw lines to fill the area. I want the lines to follow the long axis of the area, to use as few lines as possible.
I googled around, and come across PCA (principal component analysis) as a good method to get orientation of blob, by feeding PCA algorithm all the point coordinates:
https://alyssaq.github.io/alyssaq.github.io/2015/computing-the-axes-or-orientation-of-a-blob/index.html
But copying the exact algorithm, I get very surprising results. Given similar shaped areas, the PCA algorithm returns completely different eigenvectors. They seem perpendicular:

The lines above are rendered by following the slope given by PCA algorithm, with slight random variation.
I don't know much about data processing, what is happening here? How should I address this problem?
Code:
import numpy as np

# I tried passing different set of points to pca:
# 1. Only points at the perimeter of the area
# 2. Random sample of points within the area
# 3. All points in the area

# points are like [(x1, y1), (x2, y2), ... ]
def pca(points):
    xs, ys = zip(*points)
    x = np.array(xs)
    y = np.array(ys)

    # Subtract mean from each dimension. We now have our 2xm matrix.
    x = x - np.mean(x)
    y = y - np.mean(y)
    coords = np.vstack([x, y])

    # Covariance matrix and its eigenvectors and eigenvalues
    cov = np.cov(coords)
    vals, evecs = np.linalg.eig(cov)

    # Sort eigenvalues in decreasing order (we only have 2 values)
    sort_indices = np.argsort(vals)[::-1]

    evec1, evec2 = evecs[:, sort_indices]  # Eigenvector with largest eigenvalue
    eval1, eval2 = vals[sort_indices[0]], vals[sort_indices[1]]
    print("PCA:", evec1, evec2, eval1, eval2)
    return evec1, evec2, eval1, eval2

I tried passing different set of points to pca:

*

*Only points at the perimeter of the area

*Random sample of points within the area

*All points in the area

But it doesn't matter, with each of the point selection, my algorithm can produce the above 2 patterns. Although it seems the one on the right (the incorrect one) are produced more often.

A: The mistake is in this line:
evec1, evec2 = evecs[:, sort_indices]

The eigenvectors are in the columns, but that assignment assigns the first row of evecs[:, sort_indices] to evec1 and the second row to evec2.  A quick fix is
evec1, evec2 = evecs[:, sort_indices].T

redpajama_set_name: RedPajamaStackExchange


text:
Q: Awake PC from sleep using only one button? I have a Thinkpad X1 tablet running Ubuntu 20.04 LTS. The keyboard is pretty flexible and the keys get easily pressed when the laptop is closed. When the PC is in my backpack it presses keys and drains it for battery.
I would like a way of the PC to wake from sleep ONLY when the power button is pressed. Is there any way to do this? - e.g. disabling "wake when lid opens", keyboard presses and touchpad movements/clicks.
Any help is much appreciated, thanks.
Summary; I would like my PC to wake from sleep by nothing but the POWER BUTTON.

A: I found it out.
For me the best solution was disabling XHC in /proc/acpi/wakeup.
I did this by typing into the terminal:
sudo sh -c "echo XHC > /proc/acpi/wakeup" - this disables the keyboard and the touchpad. - When i then suspend my PC I can only wake it up by pressing the power button.
I tried making this automatic when turning on my PC, but after a lot of testing and trying and failing I gave up. I ended up with just a simple script that I found online, that I type into the terminal upon reboot. (Because the previous command get reset to default upon reboot).
The script:
#!/bin/sh
for device in XHC
do
    if grep -q "$device.*enabled" /proc/acpi/wakeup
    then
        echo $device > /proc/acpi/wakeup
    fi
done

I then just run it in the terminal like this: sudo sh Desktop/clickme.sh
I tried putting the script file in /etc/rc.local ... but that did nothing. Also tried making the script a startup application by writing sudo sh Desktop/clickme.sh into the Startup Applications GUI. But that did nothing. - If anyone sees an error I made in my troubleshooting... please tell me, I would love to forget about the script upon every reboot.
My top sources for this problem were these: Desktop wakes from suspend at random (14.04) and Disable USB keyboard wakeup


text:
Q: Send email once per day using pm2 and nodemailer We are using a Ubuntu 18.04 server with pm2 to schedule the launch of a node.js backend on startup and have a working nodemailer script that sends an email to our team members with the state of some resources on the server.
This script works if launched manually, using node script.js.
If it is started using pm2 start script.js it just keeps sending emails without stopping. I think that is because pm2 keeps the script working by restarting it after it finishes. After searching around, I found the --no-restart option and I could run it only once with
`pm2 start script.js --no-autorestart`

Since the goal is to send emails everyday at 09h00 and pm2 has integrated cron features, I tried running
pm2 start reportOfflineDevices.js --no-autorestart --cron "0 9 * * *"

but it did not send any email. After some more searching I found out that pm2 only uses its cron features to restart running processes. Since I include the --no-autorestart option, after it runs once, it is listed in pm2 status as being stopped, therefore it won't be restarted.
Finally, I tried a naive approach of including a while(1); at the end of my script to keep it running but it won't even send an email and top shows the script eating 100% CPU resources. In hindsight, I guess that makes sense...
In the end I will have to either find a way to keep the script working without consuming CPU resources or forget about pm2 and just use plain old cron. What do you think?
I post here a simplified minimum working example of my script (if correct server and auth are configured in the transporter).
const fetch = require("node-fetch");
const moment = require('moment');
const nodemailer = require('nodemailer');

const report = async () => {
    var transporter = nodemailer.createTransport({
        auth: {
            user: 'abc@server.blabla',
            pass: 'password'
        },
        host: 'our.server.blabla',
        port: 465,
        secure: true
    });

    var sendToEngineering = {
        from: 'noreply@server.blabla',
        to: 'engineering@server.blabla',
        subject: 'Report',
        text: "report"
    };

    transporter.sendMail(sendToEngineering, function (error, info) {
        if (error) {
            return error;
        } else {
            return 'Email sent: ' + info.response;
        }
    });
}
report();

A: Looks really interesting and good, but what I would have done is to create it as an express application and add the node-cron package and then you could change the code as following:

const fetch = require("node-fetch");
const moment = require('moment');
const nodemailer = require('nodemailer');

const express = require("express");
const cron = require("node-cron");

// setup your express server as an app
var app = express();

const report = async () => {
    var transporter = nodemailer.createTransport({
        auth: {
            user: 'abc@server.blabla',
            pass: 'password'
        },
        host: 'our.server.blabla',
        port: 465,
        secure: true
    });

    var sendToEngineering = {
        from: 'noreply@server.blabla',
        to: 'engineering@server.blabla',
        subject: 'Report',
        text: "report"
    };

    transporter.sendMail(sendToEngineering, function (error, info) {
        if (error) {
            return error;
        } else {
            return 'Email sent: ' + info.response;
        }
    });
}

// start scheduling the execution of your function on a daily basis use
// https://crontab.guru to determine your timings
// don't forget that these times are ofcourse based on the server times so you need
// to change it for your timezone
cron.schedule("0 8 * * *, function() {
    report();
});

app.listen(3129);

// next line is to ensure it executes atleast once when restarting pm2
report();

This way your report function should be executed once a day and if your server/app needs updates you can easily restart the server and receive a mail to ensure there are no issues.


text:
Q: WPF: how do i handle a click on a ListBox item? In my WPF app I'm handling a ListBox SelectionChanged event and it runs fine.
Now I need to handle a click event (even for the already selected item); I've tried MouseDown but it does not work. How can I handle a ListBox click on an item?

A: Perhaps try the PreviewMouseDown event. The MouseDown event gets swallowed and converted to the SelectionChanged event.
Only downside is that the PreviewMouseDown will occur before the SelectionChanged.

A: Listbox internally uses the mouse down to perform selection changed. So you can use preview mouse down event.
Apart from preview mouse down, you can use EventManager.RegisterClassHandler...
     EventManager.RegisterClassHandler(typeof(ListBoxItem), ListBoxItem.MouseLeftButtonDownEvent, new RoutedEventHandler(EventBasedMouseLeftButtonHandler));

     private static void EventBasedMouseLeftButtonHandler(object sender, RoutedEventArgs e)
     {
     }

Let me know if this helps...

A: Just handle PreviewMouseDown event:
private void listBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var item = ItemsControl.ContainerFromElement(listBox, e.OriginalSource as DependencyObject) as ListBoxItem;
    if (item != null)
    {
        // ListBox item clicked - do some cool things here
    }
}


text:
Q: Bottom align after pull-right This is my code:

Some header text

            @using (Html.BeginForm("ChangePageSizeAction", "myController"))
            {
                @Html.AntiForgeryToken()
                Page Size
                @Html.DropDownList("pageSize", null, htmlAttributes: new { @class = "form-control", onchange = "this.form.submit();" })
            }

            @Html.PagedListPager(Model, page => Url.Action("Index", new { page }),
                        new PagedListRenderOptions()
                        {
                            MaximumPageNumbersToDisplay = 3,
                            DisplayPageCountAndCurrentLocation = true,
                            PageCountAndCurrentLocationFormat = "Page {0} of {1}",
                        })

This is the output:

I want to align the PagedListPager to bottom beside the DropDownList like this:

I tried to set div1 style to position:relative and div2 style to position:absolute; bottom:0 but didn´t work.

A: After Morpheus comment I looked for the difference in his jsfiddle example and mine, so I found an error (margin:0) in my css classes.
So, sorry for the wrong question.


text:
Q: Create Project in Visual Studio 2015 with Entity Framework 5 I'm using VS 2015 and need to create a new project but I can't find how to use a new project template with an older version of Entity Framework.
I need to use EF 5.0 and "new Project" in VS 2015 adds reference of EF 6 with all the login and other stuff.
Tired to search in the web but I still don't know how to do this.


text:
Q: Exclude aidl files from Javadoc task with Gradle I'm currently discovering Android Studio and Gradle and migrating all the build chain of my project from bash scripts to Gradle configurations. It's probably going to be awesome in the end, but meanwhile I'm struggling.
What I want to do now is quite simple. I have a standard rule to generate Javadoc from my source (I took this snippet from http://snowdream.github.io/blog/android/2013/11/01/how-to-generate-javadocs-with-android-gradle-plugin/):
android.libraryVariants.all { variant ->
    task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
        source = variant.javaCompile.source
        def androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"

        classpath = files(variant.javaCompile.classpath.files, androidJar)
        options {
            links "http://docs.oracle.com/javase/7/docs/api/"
            linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference"
        }
        exclude '**/BuildConfig.java'
        exclude '**/R.java'
    }
}

But my project also contains AIDL files and I don't want these aidl files (nor the .java files generated from them) to be included to the Javadoc.
I tried the rule:
exclude "**/$buildDir/**"

... and I tried a thousand others, but none works and my interfaces and Stub are processed into HTML files.
I beg for your help! Thanks a lot.

A: After hours of research about how Gradle and Groovy work, the best way I found is:
exclude {
  it.file.path.contains('aidl')
}

However, I'm still unsatisfied. I do feel something less brutal could be done using variant.aidlCompile.sourceOutputDir that points to the Java files generated by AIDL. But I could not compare the iterated elements in the Closure to this File, or FileTree, or whatever shape I give it...
EDIT:
After further research, another method is to hide the interfaces defined in AIDL using a custom Doclet that supports @hide tag (like Doclava). I preferred this method because it doesn't cause errors during Javadoc generation.


text:
Q: How to find an application cache on an android device from linux I accidentally deleted my private key from my email (protonmail) on PC and didn't have it saved anywhere, and can't decrypt any of my old emails. I tried contacting the support but it was no help. I noticed that I can still read older emails fine on my phone and it even encrypts newly sent emails with the old key. I tried asking the support how to extract the key but they said it can't be done. So I'm trying to find it myself and add it to my account again. I think it's cached and the application haven't queried for the new key yet.
The problem is I don't know anything about android or where the files are stored.
I tried connecting my device (Moto G 5G) to my linux and searching through the files with no luck, the application folder is empty, but the phone shows there is data in the cache (around 57kb).
I searched around and found this. But I never used adb and I'm unable to find the device from adb and I couldn't find drivers in case it was a driver issue.
My question is why I can't find any application cache? Is it a permission issue? And is there a way to extract it from my phone? If it's a complicated issue then can you please point me to the right place to read more on connecting to android or how to get started as I can't find proper docs to do so. Thanks


text:
Q: Workflows Not Terminating Properly I am in the process of developing a workflow for my company, and I have noticed that my workflows are not terminating properly. If you go to the workflow settings for a list, it will show a very high amount of active workflows yet there isn't that many.
My current workflow shows 165 workflows in progress, but when I run this script, it only shows 16 active workflows:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$web = get-spweb -Identity ************
$list = $web.Lists["**List in Question**"]

$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($web)
$sub = $wfm.GetWorkflowSubscriptionService()
$wf = $sub.EnumerateSubscriptionsByList($list.ID)
$wfis=$wfm.GetWorkflowInstanceService()

$test

foreach ($item in $list.Items)
{
    $workflowInstances=$wfis.EnumerateInstancesForListItem($list.ID,$item.ID)

    foreach($wf in $workflowInstances)
    {
        $wfName = $wf | ?{$_.Id -eq $wf.WorkflowSubscriptionId} | select -ExpandProperty Name
        $wfID= $wf.Properties.'Microsoft.SharePoint.ActivationProperties.CurrentItemUrl'
        $wfStatus = $wf.Status
        $wfListItem = $item.Name
        $wfListItemID = $item.ID

        write-host "Workflow URL: " -ForegroundColor Green -NoNewline
        write-host $wfID -NoNewline
        write-host " Status: " -ForegroundColor Green -NoNewline
        write-host $wfStatus -NoNewline
        write-host " ListItem: " -ForegroundColor Green -NoNewline
        write-host $wfListItem -NoNewline
        write-host " ListItem ID " -ForegroundColor Green -NoNewline
        write-host $wfListITemID
    }
}

Most of these workflows were from items that were deleted. Can anyone advise on why deleting an item isn't properly terminating the workflows?

A: Check if this helps you
https://www.codeproject.com/Articles/679628/Easiest-Way-of-Cancelling-All-S
Basically, you need to check the status and cancel it:
 if($workflow.InternalState -ne 'Completed' -and $workflow.InternalState -ne 'Cancelled')
              {
                [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($workflow);
              }

Hope this gives you some idea!


text:
Q: How do you put FragmentTabhost on bottom I want to put tabwidget on bottom like iPhone App.
I know what this layout is against Google UserInterface guideline ,but i need.
so,I have read many similar post in Stackoverflow.
but every post isnt working.
I want to use FragmentTabhost,without use External library (ex:ActionBarsherlock
this is my code
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_above="@android:id/tabs" />

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_above="@android:id/tabs" />

    <TabWidget
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" />
</RelativeLayout>

and activity code is below
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_top);

    //set up FragmentTabhost
    FragmentTabHost host = (FragmentTabHost)findViewById(R.id.tabhost);
    host.setup(this,getSupportFragmentManager(),R.id.content);

    //add tabspec
    TabSpec tabSpec1 = host.newTabSpec("tab1");
    Button btn1 = new Button(this);
    btn1.setBackgroundResource(R.drawable.icon1);
    tabSpec1.setIndicator(btn1);
    Bundle bundle1 = new Bundle();
    bundle1.putString("name", "tab1");
    host.addTab(tabSpec1,SampleFragment.class,bundle1);

    TabSpec tabSpec2 = host.newTabSpec("tab2");
    Button btn2 = new Button(this);
    btn2.setBackgroundResource(R.drawable.icon2);
    tabSpec2.setIndicator(btn2);
    Bundle bundle2 = new Bundle();
    bundle2.putString("name", "tab2");
    host.addTab(tabSpec2,SampleFragment1.class,bundle2);

}

so i have tried another layout like this
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0" />

    <TabWidget
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" />

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

please help me,

Note
finally I solved this ploblem.
This is SupportPackage 's bug .....
try this
http://code.google.com/p/android/issues/detail?id=40035

A: Try out this:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TabWidget
    android:id="@android:id/tab"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

<FrameLayout
    android:id="@android:id/content"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</RelativeLayout>

A: Try this :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</android.support.v4.app.FragmentTabHost>

A: Try this, Following XML works for me very fine.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@android:id/tabhost"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v4.app.FragmentTabHost>

Hope this will work.


text:
Q: oracle missing keyword when creating table I am trying to create a table using sql in oracle. But using this statement it gives me missing keyword error. But it runs okay in w3school sql tryit editor. can anyone please help me to understand what causing the problem in oracle??
create table  products (product_key number(4) not null primary key, product_name varchar(50) not null unique, price_reg double(1000,2) not null, price_spec double(1000,2) not null, sell_reg double(1000,2) not null, sell_spec double(1000,2) not null)

all help will be greatly appreciated.

A: Your issue is that Oracle has a Double Precision data type and a Numeric data type. You are combining the two. The "missing keyword" here is the word "precision" after double. You either want this:
create table  products (
product_key number(4) not null primary key,
product_name varchar(50) not null unique,
price_reg double precision not null,
price_spec double precision not null,
sell_reg double precision not null,
sell_spec double precision not null)

or this:
create table  products (
product_key number(4) not null primary key,
product_name varchar(50) not null unique,
price_reg numeric(10,2) not null,
price_spec numeric(10,2) not null,
sell_reg numeric(10,2) not null,
sell_spec numeric(10,2) not null)

SQL Fiddle demo
Also note that 1000 is not a valid precision value for the numeric type, the max is 38 (I used 10 above).

A: try not to use w3school use oracle docs
already answer given
here are some useful information

*

*Singular names for tables

*Singular names for columns

*Schema name for tables prefix (E.g.: SchemeName.TableName)

*Pascal casing (a.k.a. upper camel case )

create table  Product (
product_key number(4) not null primary key,
product_name varchar(50) not null unique,
price_reg double precision not null,
price_spec double precision not null,
sell_reg double precision not null,
sell_spec double precision not null)


text:
Q: Keyboard hiding tableview cells containing textfields I have a uiviewcontroller that contains a uitableview, this uitableview is full of custom cells that contain a textfield.
This view in storyboard is loaded as a popover, so the behaviour is:
iPad - If the keyboard is loaded and the keyboard hides the current editing cell, the cell automatically moves up so it is visible, regardless of its position in the tableview
iPhone - It doesn't, the tableview dosn't move if the keyboard hides the cell.
Can anyone suggest an elegant way round this?
Thanks

A: I had similar issue using Xcode 8.2.1, swift 3 with keyboard hiding UITextView when it becomeFirstResponder(), spent few hours to figure out what was the problem without any luck, finally created new test project with single UITableViewController and it worked, thereafter re-created the Table View Controller in storyboard -  cells started to scroll to allow space for keyboard which appears just below the designated text view  as expected...
perhaps something with wiring that prevented it from working properly

A: You can use the table view method scrollToRowAtIndexPath
func scrollToRowAtIndexPath(_ indexPath: NSIndexPath,
           atScrollPosition scrollPosition: UITableViewScrollPosition,
                   animated animated: Bool)

to scroll the table view when a text field becomes the first responder, for example:
let indexPath = NSIndexPath(forItem: 4, inSection: 0)
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)

See the UITableView reference for further information
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/doc/uid/TP40006943-CH3-SW44
I hope this helps you. Feel free to ask if anything is unclear.


text:
Q: Finding a cell with a specific value and applying a class to a cell in the same row I have a ranking table with specific Elo ratings for each player. Depending on their Elo rating I want the player's name to be a specific color based on their rank. I have been using the code below:
if (parseInt($("td.data-rating").val()) > 100) {
  $(this).closest("tr").find("td.data-name").addClass("important");
}

JSFiddle
why does this code not work? Am I using "this" incorrectly?

A: You have several issues:

*

*The this keyword refers to the Window object

*Only HTMLInputElement have values, the use of .val() is incorrect

*You must iterator over each of the  elements to set the classList

This should work for you:

$(function() {
  $("td.data-rating").each((i, el) => {
    if (parseInt(el.textContent) > 1000) {
      $(el).closest("tr").find("td.data-name").addClass("important");
    }
  })
})
.important {
  color: red;
}

    Player 1
    1
    1200

    Player 2
    1
    1150

    Player 3
    1
    1000

A: $("td.data-rating") will return array so .val will not work for it. you should use each function for that. Try below one.
$("td.data-rating").each(function (index) {
if(parseInt($(this).text()) > 1100) {
$(this).siblings().eq(0).addClass("important");
}
});


text:
Q: How to get rid of annoying startup message from stack ghci? I'm using stack ghci to start my REPL, based on the answer I got for my question on how to import a module installed with stack. This works fine, but I get initially a warning message Note: No local targets specified, so a plain ghci will be started with no package hiding or package options., followed by a bunch of suggestions about package hiding and options. My guess is that this is because I have not used stack init to setup a project, since I am still in the "playing around and learning" state and don't want a project yet. I have not found an explanation about the meaning of 'no local targets', but the effect to start a plain ghci is exactly what I want at that point. Is there a way to suppress this message? I looked at stack --help, but could not find something suitable.

A: As the Note (not warning) suggests, a plain ghci is started, which is rather uncommon situation when working with stack.
~$ stack ghci

Note: No local targets specified, so a plain ghci will be started with no package hiding or package options.

      You are using snapshot: lts-14.12

      If you want to use package hiding and options, then you can try one of the following:

      * If you want to start a different project configuration than /home/username/.stack/global-project/stack.yaml, then you can use stack init to create a new stack.yaml for the packages in the
        current directory.

      * If you want to use the project configuration at /home/username/.stack/global-project/stack.yaml, then you can add to its 'packages' field.

Configuring GHCi with the following packages:
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /tmp/haskell-stack-ghci/2a3bbd58/ghci-script
Prelude>

This means though that all you need to do to get the same behavior without the Note is just start ghci manually in the context of global stack environment:
~$ stack exec -- ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Prelude>

In case that you want to make sure some package is installed for "playing around and learning" in the ghci session you can supply them as --package arguments
~$ stack exec --package massiv -- ghci
atomic-primops> using precompiled package
cabal-doctest > using precompiled package
scheduler     > using precompiled package
massiv        > using precompiled package
Completed 4 action(s).
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Prelude> import Data.Massiv.Array
Prelude Data.Massiv.Array>

A: stack exec --ghci as in lehins's answer did not work for me, but stack exec ghci did.


text:
Q: pdo select a row if it contains one word of a string I have a mysql table where users have a column with there favorit game.
They are saved like this:
id     username     games
1      user1        ,game1, game2, game3
2      user2        ,game2, game4
3      user3        ,game4, game1, game3

Now I want to select all users with at least one game as same as me.
$mygames = ,game2, game5

$statement = $pdo->prepare("SELECT * FROM users WHERE games = ?????");
$statement->execute();
$users = $statement->fetchAll();

It should give me user1 and user2 because both contain game2 and I too!
How can I do that?
Thanks for your help :)

A: Try using Like statement, example:
$query = "SELECT * FROM users WHERE game LIKE ? OR game LIKE ?";
$params = array("%,game2%", "%,game5%");
$statement = $handle->prepare($query);
$statement->execute($params);

A: You could use a regex?
select * FROM users where games REGEXP 'game4|game2'; if you want all rows containing game4 or game2 for example.
So your php needs to construct the regexp.
<?php

$games = ['game2', 'game4']; // an array of the required games

$regexp = implode('|', $games); // converts array to string with pipe as delimiter

echo ($regexp); // outputs 'game2|game4'

So your mysql now becomes
$sql = 'select * FROM users where games REGEXP '. $regexp .';

A: As Matt said, using LIKE statement
in a better & scalable way:
$mygames = ",game2, game5"; // or whatever

// split & trim the gamenames
$games = array_map('trim',split(trim($mygames, ',')));

// for ANY number of games you have, set the condition that selects anyone who have ANY of them.
$statement = $pdo->prepare("SELECT * FROM users WHERE " . substr(str_repeat(" games LIKE ? OR ", count($games)), 0, -3));
$statement->execute();
$users = $statement->fetchAll();

A: I found a solution
$mygames = ,game2, game5
$ug = explode(",", $mygames); //each word is splitted at the ,
$ug = array_filter($ug); //every empty array is deleted

$statement = $pdo->prepare("SELECT * FROM users");
$statement->execute();
$users = $statement->fetchAll();

foreach ($users as $row) {

$usg = explode(",", $row['games']); //each word is splitted at the ,
$usg = array_filter($usg);          //every empty array is deleted
$gsame= count(array_intersect($usg, $ug)) > 0; //if a user has at least one game as me it counts(onegame=1, twogames=2 etc...)

if($gsame > 0) { //if gsam is more than 0 it displays the array
<html></html>
}

Hope this helps some of you :)


text:
Q: rails db:seed will not populate a negative value this has to have an obvious answer that I'm missing!
schema.rb has
create_table "table_name", :force => true do |t|
     t.integer my_columnname, :limit =>8

seeds.rb has
TableName.create([{"my_columnname"=>-1}])

But when looking at the database the value is 0 e.g. zero. it does not populate properly.
notes:

*

*if I change -1 to say 999, the database value IS 999. so I know seeds.rb format is ok

*i have attempted using :my_columname instead of "my_columnname", no difference

*I've search for any examples of problems with seeding negative values, no-one seems to have same problem

*I did have this working in the past so I've diff'd seeds,schemas and migration files and application.rb. The ONLY difference seems to be the :limit => 8 (I need big int). But everything I've researched says that BIGINTs are signed. so that "should not" be the issue.

*I have logged into mysql to look at table type -  it is bigint

*I have removed the :limit from my current version and it still does not populate

*i have logged into mysql command line and performed an sql insert with a negative value and it populates.

*rake db:seed --trace does not show any errors.

** UPDATES **

*

*attempting to insert a value 9999999999999999999 results in error: Mysql2::Error: Out of range value for column 'qty_included_standard'

*

*I have tried setting value to "-1" or -1. no difference still will not set to -1

*using the console, the actual value being submitted to the DB is zero not -1 (see value_included_standard below). But if i make -1 888, it submits 888.
014-02-17 20:55:02", special_consideration: nil>]
    1.9.3-head :009 > TransactionType.create([{"transaction_type"=>"20", "value_included_standard"=>-1, "qty_included_standard"=>"8", "cost_per_transaction_standard"=>"1000", "standard_included_in_overall"=>"false", "special_consideration"=>nil, :plan_id=>1}])
       (0.3ms)  BEGIN
      SQL (0.4ms)  INSERT INTO transaction_types (cost_per_transaction_standard, cost_per_transaction_within, created_at, flag_fall_cost_for_transaction, min_block_for_transaction, plan_id, qty_included_standard, qty_included_within, special_consideration, standard_included_in_overall, transaction_type, updated_at, value_included_standard, value_included_within, withintype_included_in_overall) VALUES (1000, 0, '2014-02-17 20:55:43', 0, 0, 1, 8, 0, NULL, 0, '20', '2014-02-17 20:55:43', 0, 0, NULL)
what am I doing wrong. is there something in migrations/schema that is restricting signed values?
hope this is obvious to someone.
            ** Invoke db:seed (first_time)
    ** Invoke db:abort_if_pending_migrations (first_time)
    ** Invoke environment (first_time)
    ** Execute environment
    [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
    WE HAVE INITIALISED
    ** Execute db:abort_if_pending_migrations
    ** Execute db:seed

A: am I a complete idiot. sorry to all. there is a validator that was introduced that I forgot to check (we have outsourced development). I've been so fixated to schemas/migration definitions i forgot to check the "save" function! if you take out  self.send(f.to_s + '=', 0) if self.send(f) < 0  it works!!!!


text:
Q: Electron React, my form is not preventing default event I've tried everything, I used the standard input, without success, I already changed the onSubmit to onClick, without success, I already put the function in the onClick button without success, it only works when I remove the input field of type file
I am using Electron React Boilerplate
https://github.com/electron-react-boilerplate/electron-react-boilerplate
import { Button, Pane, FileUploader, FileCard, Alert } from 'evergreen-ui';
import VideoSnapshot from 'video-snapshot';
import Input from 'renderer/components/Input';
import React from 'react';
import axios from 'axios';
import ContainerMenu from '../components/ContainerMenu';

const Admin = () => {
  const [name, setName] = React.useState('');
  const [genre, setGenre] = React.useState('');
  const [path, setPath] = React.useState('');
  const [preview, setPreview] = React.useState(null);
  const [submitError, setSubmitError] = React.useState('');
  const [progress, setProgress] = React.useState(0);
  const [files, setFiles] = React.useState([]);
  const [fileRejections, setFileRejections] = React.useState([]);
  const handleChange = React.useCallback((files) => setFiles([files[0]]), []);
  const handleRejected = React.useCallback(
    (fileRejections) => setFileRejections([fileRejections[0]]),
    []
  );
  const handleRemove = React.useCallback(() => {
    setFiles([]);
    setFileRejections([]);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitError('');

    if (files.length === 0) {
      setSubmitError('O arquivo não pode ser vazio');
      return;
    }

    try {
      const snapshoter = new VideoSnapshot(files[0]);
      const previewSrc = await snapshoter.takeSnapshot();
      if (previewSrc) setPreview(previewSrc);
    } catch (error) {
      console.log(error);
    }

    try {
      // const previewData = new FormData();
      // const previewObject = {
      //   preview: previewSrc,
      // };
      // previewData.append('file', previewObject);
      // await axios.post('http://localhost:3000/api/upload', previewData);

      const formData = new FormData();
      formData.append('file', files[0]);
      formData.append('name', name);
      formData.append('genre', genre);
      formData.append('path', 'videos');

      const response = await axios.post(
        'http://localhost:3000/api/upload',
        formData,
        {
          onUploadProgress: (progressEvent) => {
            const progress = (progressEvent.loaded / progressEvent.total) * 50;
            setProgress(progress);
          },
        }
      );
    } catch (error) {
      console.log(error);
      setSubmitError(error.message);
    }
  };

  return (

      <ContainerMenu />

        <form
          encType="multpart/form-data"
          className="form-group"
          onSubmit={handleSubmit}
        >

Enviar Arquivos

            <Input
              type="text"
              label="Nome"
              placeholder="Nome ..."
              onChange={setName}
              value={name}
            />

            <Input
              type="text"
              label="Gênero"
              placeholder="Gênero ..."
              onChange={setGenre}
              value={genre}
            />

            <Pane>
              <FileUploader
                label="Upload File"
                description="You can upload 1 file. File can be up to 50 MB."
                maxSizeInBytes={50 * 1024 ** 2}
                maxFiles={1}
                onChange={handleChange}
                onRejected={handleRejected}
                renderFile={(file) => {
                  const { name, size, type } = file;
                  const fileRejection = fileRejections.find(
                    (fileRejection) => fileRejection.file === file
                  );
                  const { message } = fileRejection || {};
                  return (
                    <FileCard
                      key={name}
                      isInvalid={fileRejection != null}
                      name={name}
                      onRemove={handleRemove}
                      sizeInBytes={size}
                      type={type}
                      validationMessage={message}
                    />
                  );
                }}
                values={files}
              />
            </Pane>

            <Button
              isLoading={progress > 0 && progress < 100}
              marginRight={16}
              appearance="primary"
              type="submit"
            >
              Enviar {progress.toFixed(2)}%
            </Button>

{preview && }

            {submitError.length > 0 && (
              <Alert intent="danger" title="Error">
                {submitError}
              </Alert>
            )}

        </form>

  );
};

export default function App() {
  return <Admin />;
}


text:
Q: Calculating percentage of left over cost displaying result as NaN I am trying to show the percentage which is left after number1 has subtracted from number. The values I am calling contain a £ symbol and when running the code I get the result of NaN I guess this is to do with the £ sign as when removed the percentage shows. Anyone have any idea how I can fix this please ? I have been trying for hours with no luck :( Thanks in advance.
double number;
double number1;
double result;

double.TryParse(SelectedQuoteForEditing.JobPrice, out number);
double.TryParse(lblRate.Content.ToString().ToString(), out number1);

var left = Math.Round((number - number1) / number * 100, 2);

result = left;

ERGPerc.Content = result.ToString("P") + "%";

A: Well, double.NaN is a result of 0.0 / 0.0.
0.0 / 0.0 == double.NaN

that's why both number and number1 are 0.0. It means that
double.TryParse(SelectedQuoteForEditing.JobPrice, out number);
double.TryParse(lblRate.Content.ToString().ToString(), out number1);

either SelectedQuoteForEditing.JobPrice is 0.0 or invalid (say, empty string) and the same for lblRate.Content.ToString().ToString().
Check the value double.TryParse returns:
if (double.TryParse(SelectedQuoteForEditing.JobPrice, out number) &&
    double.TryParse(lblRate.Content.ToString(), out number1) {

  var left = Math.Round((number - number1) / number * 100, 2);
  ERGPerc.Content = left.ToString("P") + "%";
}
else {
  // at least one value is invalid
}

Edit: If you want to parse currency, say GB ones (see £150.00 in the comments), you have to let the system know about it:
double.TryParse(SelectedQuoteForEditing.JobPrice,
  NumberStyles.Any,                    // allow currency symbols
  CultureInfo.GetCultureInfo("en-GB"), // which currency? GB
  out number);

double.TryParse(lblRate.Content.ToString(),
  NumberStyles.Any,                    // allow currency symbols
  CultureInfo.GetCultureInfo("en-GB"), // which currency? GB
  out number1);

otherwise the Parse fails (what £ means? It doesn't correct part of floating point value!) you'll get 0.0 for number and number1 and double.NaN on (number - number1) / number execution

A: If SelectedQuoteForEditing.JobPrice and lblRate.Content are 2 strings with the £ at the end/beginning, like 100£, 100 £ or £100. You just have to add .Replace("£", string.Empty) to this variable.


text: Q: Threejs transparent materials union blending I have two different objects with the same transparent material in threejs, and I want to blend them in a "non-additive" way like in the following picture. There are three boxes: one blue in the background and two transparent yellow boxes in the foreground. The left image is how it currently is, and the right image is what I want. Is there a kind of material / possibly shader that can achieve this effect?


text:
Q: Camera shake effect in iMovie '11 Is there a possible way to create a camera shake effect in iMovie 11?

A: I know that in iMovie HD (2006), the effect was under the name "Earthquake effect". Try looking for it under that name.

A: Firstly make the whole clip into 0.1 second. Then go onto the crop thing in the middle of the screen and pick the Ken Burns effect. Then you have to move the start and the end wherever you want and it will be shaky.


text:
Q: Creating Activity by using AsyncTask in Android I'm having an exception when running the following code.
public class LoginActivity extends Activity {
/** Called when the activity is first created. */
Button btnSend, btnDelete;
EditText edtUsername, edtPassword;
TextView tvUsername, tvPassword;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initializeProperties();

    btnGonder.setOnClickListener(new OnClickListener() { public void onClick(View view) {
        login("aaa@bbb.com", "123456");
    }});
    btnSil.setOnClickListener(new OnClickListener() { public void onClick(View view) {
        clearView();
    }});
}

private void initializeProperties() {
    btnSend = (Button) findViewById(R.id.bSend);
    btnDelete = (Button) findViewById(R.id.bDelete);
    tvUsername = (TextView) findViewById(R.id.tvUsername);
    edtUsername = (EditText) findViewById(R.id.etUsername);
    tvPassword = (TextView) findViewById(R.id.tvPassword);
    edtPassword = (EditText) findViewById(R.id.etPassword);
}

private static final String readInputStream(java.io.InputStream stream) throws IOException {
    java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream);
    java.io.BufferedReader bufferedReader = new java.io.BufferedReader(streamReader);
    String line, redText = "";
    while ((line = bufferedReader.readLine()) != null) {
        redText += line;
    }
    bufferedReader.close();
    return redText;
}

private void clearView() {
    edtPassword.setText("");
}

private void login(String username, String password) {

    HttpPost httpPost = new HttpPost("http://192.168.1.1/api/login");

    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getApplicationContext());
    alertBuilder.setCancelable(true);

    //HttpResponse response = null;
    try {
        // Add your data
        httpPost.setEntity(new StringEntity(
            String.format("{ 'Email': '%s', 'Password': '%s' }", username, password)
        ));
        // Set Headers
        httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
        // Execute HTTP Post Request
        //response = new AsyncLoginHandler(alertBuilder).execute(httpPost).get();
        new AsyncLoginHandler(alertBuilder).execute(httpPost);

    } catch (UnsupportedEncodingException uee) {
        alertBuilder.setMessage(uee.getMessage());
    }
}

class AsyncLoginHandler extends android.os.AsyncTask<HttpPost, Void, HttpResponse> {
    AlertDialog.Builder alertBuilder;

    AsyncLoginHandler(AlertDialog.Builder alertBuilder) {
        super();
        this.alertBuilder = alertBuilder;
    }

    @Override
    protected HttpResponse doInBackground(HttpPost... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        for (int i = 0; i < params.length; i++) {
            try {
                httpResponse = httpClient.execute(params[i]);
            } catch (ClientProtocolException cpe) {
                alertBuilder.setMessage(cpe.getMessage());
            } catch (IOException ioe) {
                alertBuilder.setMessage(ioe.getMessage());
            } catch (Exception e) {
                alertBuilder.setMessage(e.getMessage());
            }
        }
        return httpResponse;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
        if (response != null) {
            try {
                java.io.InputStream stream = response.getEntity().getContent();
                String result = readInputStream(stream);
                alertBuilder.setMessage(result);
            } catch (IllegalStateException ise) {
                alertBuilder.setMessage(ise.getMessage());
            } catch (IOException ioe) {
                alertBuilder.setMessage(ioe.getMessage());
            }
        }

        super.onPostExecute(response);

        alertBuilder.create().show();
    }

}

}
Well... The Android's documentation page for AsyncTask (please refer to the title "The 4 Steps")states that onPostExecute is invoked on the UI thread; However I'm having the following error after "alertBuilder.create().show();".
 - 10-04 06:36:25.607: W/dalvikvm(711): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
 - 10-04 06:36:25.657: E/AndroidRuntime(711): FATAL EXCEPTION: main
 - 10-04 06:36:25.657: E/AndroidRuntime(711): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.ViewRootImpl.setView(ViewRootImpl.java:517)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.app.Dialog.show(Dialog.java:278)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at org.gdgankara.com.LoginActivity$AsyncLoginHandler.onPostExecute(LoginActivity.java:139)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at org.gdgankara.com.LoginActivity$AsyncLoginHandler.onPostExecute(LoginActivity.java:1)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask.finish(AsyncTask.java:602)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask.access$600(AsyncTask.java:156)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.Handler.dispatchMessage(Handler.java:99)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.Looper.loop(Looper.java:137)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.app.ActivityThread.main(ActivityThread.java:4424)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at java.lang.reflect.Method.invokeNative(Native Method)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at java.lang.reflect.Method.invoke(Method.java:511)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at dalvik.system.NativeStart.main(Native Method)

Can anyone help?

A: The doInBackground method cannot touch the view of the main thread. Meaning that you can't set the message of the alert dialog form the doInBackground method. try to remove the set 3 set messages from the catch inside the doInBackground and run the application.


text:
Q: Statement $\frac ab+\frac bc+\frac ca \ge 3$ is true for any positive $a$, $b$, $c$? Let us have $a,b,c$ arbitrary positive numbers. Prove:
$\frac{a}{b}+\frac{b}{c}+\frac{c}{a} \ge 3$
I have tried many things, but none of them seemed to work. Any ideas? (If duplicate, I am sorry, didn't see it yet) :)

A: You can Use AM-GM inequality to get $$\frac{a/b+b/c+c/a}{3}\ge (a/b\cdot b/c\cdot c/a)^{1/3}=1$$


text:
Q: Redefine static members in a derived class. Java So i was reading the book and the author says " The static members aren't involved in runtime polymorphism. You can't override the static members in a derived class, but you can redefine them."
What is that mean? Can you give me a example for this also?
Thank you.

A: If you re-define a static member (either method or variable) in a sub-class, you are hiding the definition of the super-class.
public class Super
{
    public static void methodA()
    {

    }
}

public class Sub extends Super
{
    public static void methodA()
    {

    }
}

Here static methodA is redefined in the sub-class, but it doesn't override the methodA of the super class.
Calling Sub.methodA would invoke Sub's methodA. If Sub didn't have a methodA, calling Sub.methodA would have called Super's methodA.

A: If you redefine static method in subclass, its called method hiding. Static method are resolved at compile time rather than run time, and you call them based on class like say:
class A {
    public static void mymthod() {}
}

class B extends A {
    public static void mymthod() {}
}

And you call as:
A a = new B();
a.mymthod();//resolved at compile time and associated with class A (compiler will warn although as static method doesnt necessarily need an object to call)

A: You can see for yourself with this
class A {

    static int x = 1;
    int y = 1;

    int f() {
        return 1;
    }

    static int sf() {
        return 1;
    }
}

class B extends A {

    static int x = 2;
    int y = 2;

    int f() {
        return 2;
    }

    static int sf() {
        return 2;
    }

}

public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        A b = new B();
        System.out.println("A.x=" + ((A) b).x);
        System.out.println("B.x=" + b.x);
        System.out.println("A.y=" + ((A) b).y);
        System.out.println("B.y=" + b.y);
        System.out.println("A.f() = " + ((A) b).f());
        System.out.println("B.f() = " + b.f());
        System.out.println("A.sf() = " + ((A) b).sf());
        System.out.println("B.sf() = " + b.sf());

    }

}

It pprints:
A.x=1
B.x=1
A.y=1
B.y=1
A.f() = 2
B.f() = 2
A.sf() = 1
B.sf() = 1
One would expect B.sf to be printed as 2 but no.
Same one would expect B.x and B.y printed as 2 but also no because fields are also not polymorphic, only functions.
I'm not sure if this has much practical value, one surely learns that after having done an error.
This is likely to be asked at worse job interviews though.

A: The variable in subclass hides the variable, with the same name, in the super class.


text:
Q: What are the options for finding nodes when using the composite pattern? Apart from recursively querying each node, are there any other options for searching for a node given some identifier?

A: Visitor is always fun for examining nodes within a composite object.
If they have unique id's you might want to accumulate an index with direct references to each piece of the Composite structure.
If, on the other hand, identifiers can be reused down within the composite structure, you may have to resort to XPath-like searches.

A: Well, recursion is the most natural thing if you're using a tree. Other than that, you could maintain a list or a collection outside of the tree, which seems superfluous, or you could simply linearly iterate over the list of tree nodes, which is probably going to be slower, but at least removes any traversal-specific code from the nodes, if that's of any value.
I can't see how any kind of specific tree query (e.g. xpath) that's looking for all nodes of the form a.b.c could be doing anything other than just traversing at level a for b's, and  traversing the b's for c's, in other words, some sort of filtered recursive tree traversal.

A: Only if you implement it. :-(
(The pattern itself says very little about its implementation, different tools/platforms make a big difference.)

A: You can use any search you want.
The only thing the composite pattern says is that 1 object, or a collection of those objects should implement the same interface.
What happens inside that implementation is not relevant to the composite pattern.


text:
Q: Why is this java nested while loop not working? Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but  I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;

public class Warehouse {
    static private String[] eachStockElem = new String[5];
    static private String[] eachInputElem = new String[5];

    public static void main(String[] args) throws Exception {
        Scanner str = new Scanner(new File("a.txt"));
        Scanner ip = new Scanner(new File("b.txt"));
        PrintStream st_w = new PrintStream("a.txt");
        PrintStream tx = new PrintStream("c.txt");
        ArrayList<String[]> stockArrayList = new ArrayList<>();
        ArrayList<String[]> inputArrayList = new ArrayList<>();
        ArrayList<String[]> txArrayList = new ArrayList<>();
        String eachTxElem[] = new String[6];
        int tx_id=0;
        int temp_quantity=0;
        int count=0;
        try {
            while (ip.hasNextLine()) {
                eachInputElem = ip.nextLine().split(",");
                inputArrayList.add(eachInputElem);
                while (str.hasNextLine()) { //this while not working!
                    eachStockElem = str.nextLine().split(",");
                    stockArrayList.add(eachStockElem);
                    count++;
                    //do comparing operation
                    break;
                }
            }
        }
        catch(NullPointerException e){
            System.out.print("");
        }
        System.out.println(count);
        str.close();
        ip.close();
        tx.close();
    }
}

A: By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:

The name of the file to use as the destination of this print stream.
  If the file exists, then it will be truncated to zero size; otherwise,
  a new file will be created. The output will be written to the file and
  is buffered.

The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.

A: At this line,
PrintStream st_w = new PrintStream("a.txt");

the program is writing the output in the same input file. Change the name of this output file and execute your test case.


text:
Q: How to set root view controller in Today extension programmatically I have a project without storyboard. I've set root view controller in AppDelegate. Now I've added a today extension. I got a new storyboard MainInterface.storyboard with root view controller TodayViewController. How can I delete MainInterface.storyboard and set root view controller programmatically?

A: Xcode 11.0
Open Info.plist from your Extension and change
<dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    ...
</dict>

to:
<dict>
    <key>NSExtensionPrincipalClass</key>
    <string>NameOfYourExtension.NameOfYourViewController</string>
    ...
</dict>

Delete MainInterface.storyboard and it should work without any faults.

A: Using the URL Scheme to achieve your goal, See this code.
Write the following code in TodayViewController (Today extension swift file)
@IBAction func buttonTapped(_ sender: UIButton) {
        let url = URL(string: "MyAppTodayExtension://")!
        self.extensionContext?.open(url, completionHandler: { (success) in
            if (!success) {
                print("error: failed to open app from Today Extension")
            }
        })
    }

Add URL Scheme in your info.plist file

<key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>MyAppTodayExtension</string>
            </array>
        </dict>
    </array>

When you tap in today extension then get call following method in AppDelegate.swift file.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        //Write code here for navigating to a specific controller OR set root view controller
        return true
    }


text:
Q: Hibernate extending entity for read with additional joins I have an entity that corresponds to some table in DB
@Entity
@Table
public class MyEntity {
  @Id
  private Long id;

  @Column
  private String description;

  @OneToMany
  private List<Foo> foos;
...
//getters setters
...
}

And I would like to extend that entity for read-only and have additional joins to another table. I need this joins only in one case for specific read user-case:
@Entity
public class ExtendedEntity extends MyEntity {

  @ManyToMany(fetch = FetchType.EAGER)
  private List<Bar> bars;
}

Just using extensions will create a discriminator column in DB, which I don't need since I'm using the ExtendedEntity only for the read. I found I hack with using @DiscriminatorFormula that will be resolved to the same Integer value like this:
@DiscriminatorFormula("0")
@DiscriminatorValue("0")
public class MyEntity

@DiscriminatorValue("00")
public class ExtendedEntity extends MyEntity

But this really looks like a hack. With using @MappedSuperclass I cannot have associations, but this is the main reason I need to extend my entity.
What other options do I have and what are the best practices for this use-case?


text:
Q: Calling a function using reflection that has a "params" parameter (MethodBase) I have MethodBases for two functions:
public static int Add(params int[] parameters) { /* ... */ }
public static int Add(int a, int b) { /* ... */ }

I have a function that calls the MethodBases via a class I made:
MethodBase Method;
object Target;
public object call(params object[] input)
{
    return Method.Invoke(Target, input);
}

Now if I AddTwoMethod.call(5, 4); it works fine.
If I however use AddMethod.call(5, 4); it returns:

Unhandled Exception: System.Reflection.TargetParameterCountException: parameters do not match signature

Is there any way to make it so that both calls work fine without need for manually putting the arguments in an array for the params int[]?

A: Supposing we have the following example class:
public class Test
{
    public static int Add(int i1, int i2)
    {
        return i1 + i2;
    }

    public static int Add(params int[] ints)
    {
        int sum = 0;
        foreach (int i in ints)
            sum += i;

        return sum;
    }
}

To get the MethodInfo objects for each overload of the static Add method you should do the following:
 MethodInfo Add2Ints = typeof(Test).GetMethod("Add",  new Type[] { typeof(int), typeof(int) });
 MethodInfo AddParamsInts = typeof(Test).GetMethod("Add", new Type[] { typeof(int[]) });

In order to invoke any of the two methods, symply pass the arguments with the exact type expected by the specific overload you are invoking:
 Add2Ints.Invoke(null, new object[] { 1, 2 });
 AddParamsInts.Invoke(null, new object[] { new int[] { 1, 2 } });

Note that the following will not work:
 AddParamsInts.Invoke(null, new object[] { 1, 2 });

because the signature of AddParmsInt is really (int[]) and although the compiler, as a courtesy, allows you to call such method as (int, int) under the hood what is really happening is that the call is converted for you at the call site to the equivalent (int[]) call. Via reflection you don't have the compiler's "help" so you need to pass the exact argument type defined by the method's signature.
With all that said, your call method should be as follows:
 public object call(params object[] input)
 {
     return AddParamsInts.Invoke(null /*static*/, new object[] { input.Cast<int>().ToArray() });
 }

Note that you can not directly cast a object[] array to a int[] array: int[] ints = (int[])input. Casting reference typed arrays to value-type arrays is not allowed.
Also important to note is that the defined overloads of the Add method are useless, as they overlap. Consider only using the params overload or, in case you want to guarantee that at least two arguments are needed in order to evaluate an addition, overload them the following way:
 public int Add(int i1, int i2) { }
 public int Add(int i1, int i2, params int[] args) { }

A: You should wrap the arguments in an array, but the compiler will be confused, so you need to help it a bit:
Eg:
AddMethod.call((object) new int[] {5, 4 });

A: You could modify your call method to detect the params parameter and convert the rest of the input to a new array. That way your method could act pretty much the same as the logic C# applies to the method calling.
Something i quicly constructed for you (be aware that i tested this method in a pretty limited way, so there might be errors still):
public object call(params object[] input)
{
    ParameterInfo[] parameters = Method.GetParameters();
    bool hasParams = false;
    if (parameters.Length > 0)
        hasParams = parameters[parameters.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;

    if (hasParams)
    {
        int lastParamPosition = parameters.Length - 1;

        object[] realParams = new object[parameters.Length];
        for (int i = 0; i < lastParamPosition; i++)
            realParams[i] = input[i];

        Type paramsType = parameters[lastParamPosition].ParameterType.GetElementType();
        Array extra = Array.CreateInstance(paramsType, input.Length - lastParamPosition);
        for (int i = 0; i < extra.Length; i++)
            extra.SetValue(input[i + lastParamPosition], i);

        realParams[lastParamPosition] = extra;

        input = realParams;
    }

    return Method.Invoke(Target, input);
}

Be aware that i tested this method in a pretty limited way, so there might be errors still.


text:
Q: Using pyplot to plot with a ln y scale and a ln(ln(x)) scale I'm want to plot with a ln(y) axis and a ln(ln(x)) axis.
Up to now I have been using pyplot.yscale('log',basey=numpy.e) and pyplot.xscale('log',basex=numpy.e) to plot on ln scales, however I haven't found a method to extend this to ln ln scales.
How could this be done?


text:
Q: GSM Interference - SIM800L I did a GSM based alarm system using SIM800L modules.One is transmitter & the other one is receiver.When the transmitter button pressed it will make a call to receivers number & receiver detects this number & make an alarm. The system works fine on workbench.
But when I install this receiver in a police station its not working.Police station there are plenty panels like RF alarm panels, GSM panels, CDMA panels etc…
My panel is a plastic panel (housing is plastic).& it powered from a step down transformer (not a torodial).
How can I solve my problem? Is this interference?


text:
Q: firebase crash reporting report a fatal error but with 100% crash free I'm using firebase crash reporting and i see a NullPointerException
Fatal Issue but it has a ~100% Crash free.
How can it be fatal without a crashe repoted?


text:
Q: Calendar events deleted on android phone but not deleted in web Google agenda My app download a planning and create new events in calendar (between 30 to 70). For each day, I first delete all the events of the day, then I create all new events. This is running fast : less than 5 seconds.
On my android phone, in the Google Agenda app, all the old events are correctly deleted, and all the new events are correctly added.
On the web Google Agenda (opened in Chrome), all the new events are correctly sync and added (after few seconds), but all the deleted events on phone are still there, and I have all events (if there is no change in planning) duplicated... If I try 10 times, events are duplicated 10 times (not on the phone).
How to be sure that synchronization has been successful ?
Is it a bug from Google ?
Is there a limitation for sync deletion ? (in my case more than 30 events deleted in less than 5 seconds)
Is it too much or too fast ? (I tried to add a thread.sleep(2000) between each day deletion but still the same...
Someone has a solution ?

A: Well, after testing lot of solutions, I found why events are not deleted on computer.
It comes from my phone Huawei P20.
I tried on my Samsung tablet and now events are well deleted on computer !
Now I have to find why on Huawei P20 the events are kept on computer.if someone has a solution (some parameter to change ?) Thanks in advance !
PS : may be the problem is due to Android 9 ? other devices tested are all lower than android 8...
PS 2 : I changed my phone for a Xiaomi Mi9 and it's working fine under Android 9...

A: If you delete cache from calendar app it works once! I have tried different apps for calendar. I guess that some of them use the same cache as built-in app. Now I use Calendar One, but there are probably . It is not affected with that "bug".


text:
Q: Missing concrete implementation of StatelessWidget This page is my PhotoPreviewScreen where I send the photo that comes from the camera screen to the home page after clicking the button in the code below.
I am getting some interesting errors, that I have not seen before with very little in the docs, which are in the screenshot.
Has anyone seen these before? How can I rectify?
import 'package:flutter/material.dart';
import 'dart:io';

class PhotoPreviewScreen extends StatelessWidget {
  Function setData;
  PhotoPreviewScreen({Key key, this.setData}) : super(key: key);
}

class _PhotoPreviewScreenState extends State<PhotoPreviewScreen> {
  final String imagePath;
  var image;

  Future _openGallery() async {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.pop(
            context), // Go back to the camera to take the picture again
        child: Icon(Icons.camera_alt),
      ),
      appBar: AppBar(title: Text('Photo Preview')),
      body: Column(children: [
        Expanded(child: Image.file(File(imagePath))),
        const SizedBox(height: 16.0),
        OutlineButton(
          onPressed: () {
            _openGallery();
            Navigator.pop(context);
          },
          child: Text('Okay'),
          borderSide: BorderSide(
              color: Color(
                  0xff33333D)),
        ),
      ]),
    );
  }
}

errors

A: class PhotoPreviewScreen extends StatefulWidget {Function setData;   PhotoPreviewScreen({Key key, this.setData}) : super(key: key); }

I guess it should be "StatefulWidget" instead of "StatelesWidget".

A: Try the below code snippets:
import 'package:flutter/material.dart';
import 'dart:io';

class PhotoPreviewScreen extends StatefulWidget {
  Function setData;
  PhotoPreviewScreen({Key key, this.setData}) : super(key: key);

_PhotoPreviewScreenState createState() => _PhotoPreviewScreenState();
}

class _PhotoPreviewScreenState extends State<PhotoPreviewScreen> {
  final String imagePath = ' ';
  var image;

  Future _openGallery() async {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.pop(
            context), // Go back to the camera to take the picture again
        child: Icon(Icons.camera_alt),
      ),
      appBar: AppBar(title: Text('Photo Preview')),
      body: Column(children: [
        Expanded(child: Image.file(File(imagePath))),
        const SizedBox(height: 16.0),
        OutlineButton(
          onPressed: () {
            _openGallery();
            Navigator.pop(context);
          },
          child: Text('Okay'),
          borderSide: BorderSide(
              color: Color(
                  0xff33333D)),
        ),
      ]),
    );
  }
}


text:
Q: Does a JsonProperty deserialize only upon access? In Google App Engine NDB, there is a property type JsonProperty which takes a Python list or dictionary and serializes it automatically.
The structure of my model depends on the answer to this question, so I want to know when exactly an object is deserialized? For example:
# a User model has a property "dictionary" which is of type JsonProperty

# will the following deserialize the dictionary?

object = User.get_by_id(someid)

# or will it not get deserialized until I actually access the dictionary?

val = object.dictionary['value']

A: ndb.JsonProperty follows the docs and does things the same way you would when defining a custom property: it defines make_value_from_datastore and get_value_for_datastore methods.
The documentation doesn't tell you when these methods get called, because it's up to the db implementation within the app engine to decide when to call these methods.
However, it's pretty likely they're going to get called whenever the model has to access the database. For example, from the documentation for get_value_for_datastore:

A property class can override this to use a different data type for the datastore than for the model instance, or to perform other data conversion just prior to storing the model instance.

If you really need to verify what's going on, you can provide your own subclass of JsonProperty like this:
class LoggingJsonProperty(ndb.JsonProperty):
    def make_value_from_datastore(self, value):
        with open('~/test.log', 'a') as logfile:
            logfile.write('make_value_from_datastore called\n')
        return super(LoggingJson, self).make_value_from_datastore(value)

You can log the JSON string, the backtrace, etc. if you want. And obviously you can use a standard logging function instead of sticking things in a separate log. But this should be enough to see what's happening.
Another option, of course, is to read the code, which I believe is in appengine/ext/db/__init__.py.
Since it's not documented, the details could change from one version to the next, so you'll have to either re-run your tests or re-read the code each time you upgrade, if you need to be 100% sure.

A: The correct answer is that it does indeed load the item lazily, upon access:
https://groups.google.com/forum/?fromgroups=#!topic/appengine-ndb-discuss/GaUSM7y4XhQ


text:
Q: Terminal fails to open and gives this message: bash: /usr/local/bin/powerline-shell: /usr/bin/python: bad interpreter: No such file or directory When I tried to open terminal today to force an update of Firefox, this message comes up in Terminal:
bash: /usr/local/bin/powerline-shell: /usr/bin/python: bad interpreter: No such file or directory
Ubuntu ver 22.04 lts 64 bit

Now after trying to reinstall Python 3 this is what appears
sudo apt install --reinstall python-is-python3
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 3 not upgraded.
Need to get 2,788 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://us.archive.ubuntu.com/ubuntu jammy/main amd64 python-is-python3 all 3.9.2-2 [2,788 B]
Fetched 2,788 B in 1s (4,161 B/s)
(Reading database ... 420664 files and directories currently installed.)
Preparing to unpack .../python-is-python3_3.9.2-2_all.deb ...
Unpacking python-is-python3 (3.9.2-2) over (3.9.2-2) ...
Setting up python-is-python3 (3.9.2-2) ...
Processing triggers for man-db (2.10.2-1) ...
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 1.16.0-unknown is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release
  warnings.warn(
Traceback (most recent call last):
  File "/usr/local/bin/powerline-shell", line 6, in <module>
    from pkg_resources import load_entry_point
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3267, in <module>
    def _initialize_master_working_set():
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3241, in _call_aside
    f(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3279, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 573, in _build_master
    ws.require(__requires__)
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 891, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 777, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'powerline-shell==0.7.0' distribution was not found and is required by the application

When I close and reopen Terminal this is what is displayed:
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 1.16.0-unknown is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/lib/python3/dist-packages/pkg_resources/__init__.py:116: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release
  warnings.warn(
Traceback (most recent call last):
  File "/usr/local/bin/powerline-shell", line 6, in <module>
    from pkg_resources import load_entry_point
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3267, in <module>
    def _initialize_master_working_set():
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3241, in _call_aside
    f(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 3279, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 573, in _build_master
    ws.require(__requires__)
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 891, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 777, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'powerline-shell==0.7.0' distribution was not found and is required by the application

A: Run the following commands to fix the problem by linking /usr/bin/python to /usr/bin/python3:
sudo apt update
sudo apt install python-is-python3

To explain:
older versions of Ubuntu used Python2 as the default version. Traditionally, /usr/bin/python was linked to /usr/bin/python2 and most scripts explicitly ran /usr/bin/python3 for Python3. A couple of years ago and after the transition to Python3, they left this option up to the user for backwards compatibility.
In earlier versions after the transition, there were two options: python-is-python2 and python-is-python3. Installing either one of these packages would link their respective Python version to /usr/bin/python. Again, this was to ensure backwards compatibility. Since then, Python2 has become somewhat obsolete and it appears that python-is-python3 is now the only option available. Without this package, there is no symlink to /usr/bin/python unless you create one manually.
See this related question for more info.

EDIT:
So, it looks like you have a couple of options to fix this.
First, run the following command to try and uninstall powerline-shell:
sudo pip uninstall powerline-shell

If that works, run the following series of commands to install it locally:
/usr/bin/pip3 install --upgrade pip

Now, log out and log back in and run the following:
pip install powerline-shell

If you still have the powerline-shell problem after you open the terminal, run the following commands:
pip uninstall powerline-shell
git clone https://github.com/b-ryan/powerline-shell
cd powerline-shell
python setup.py install


text:
Q: truncated output parameter from executenonquery I am trying to implement ExecuteNonQuery in C#.
The storedProcedure on its own is working fine when I execute in SQL. It is returning a GUID for SubmissionId and the text 'submit sequence' for SubmitSequence. But in .net, it's returning one character as output for SubmitSequence
ALTER PROC [dbo].[test_SP]
(
    @FormId uniqueidentifier,
    @FormCode varchar(10),
    @FormTitle nvarchar(200),
    @User nvarchar(50),
    @Url nvarchar(255) = NULL,
    @Host nvarchar(50),
    @RemoteHost nvarchar(50) = NULL,
    @UserAgent nvarchar(255) = NULL,
    @Referrer nvarchar(255) = NULL,
    @SubmissionId uniqueidentifier out,
    @SubmitSequence varchar(30) out
) AS

BEGIN

SET @SubmissionId = newid();
set @SubmitSequence = 'submit sequence'

-- INSERT Query
SELECT
    @SubmissionId as SubmissionId,  @SubmitSequence  as SubmitSequence
END

But in the .net, I am getting the GUID for SubmissionId(which is correct) and the text 's' for SubmitSequence.
public SubmissionHeaderDTO GetRefNo()
        {
            var inPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase)
                            {
                                {"FormId", Guid.NewGuid()},
                                {"FormCode", "TST"},
                                {"FormTitle", "Test form"},
                                {"User", "test"},
                                {"Host", "iisserver"}
                            };
            var outPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase) {
                            { "SubmissionId", Guid.NewGuid() },
                            { "SubmitSequence", "two"}
                            };
            var result = DBHelper.ExecSP(Constants.SPNames.SubmissionHeaderInsert, inPrms, outPrms);
            SubmissionHeaderDTO refNo = DictionaryToObject<SubmissionHeaderDTO>(result);
            return refNo;
        }

DBHelper.cs
public static Dictionary<string, object> ExecSP(string sp, Dictionary<string, object> paramIn, Dictionary<string, object> paramOut)
        {
            var dbAccess = new DBAccess();
            var results = dbAccess.ExecuteQuery(sp, paramIn, paramOut);
            return results;
        }

DBAccess.cs
public class DBAccess
    {
        public Dictionary<string, object> ExecuteQuery(string storedProcedure, Dictionary<string, object> parameters,
                                          Dictionary<string, object> outParameters)
        {

            using (var sqlConn = new SqlConnection(Configuration.DBConnection))
            {
                sqlConn.Open();
                using(var transaction = sqlConn.BeginTransaction("Results"))
                {
                    using(var sqlcmd = new SqlCommand(storedProcedure, sqlConn, transaction))
                    {
                        sqlcmd.CommandType = CommandType.StoredProcedure;
                        foreach(var kv in parameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value);
                        }
                        foreach(var kv in outParameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value).Direction = ParameterDirection.Output;
                        }

                        try
                        {
                            sqlcmd.ExecuteNonQuery();
                            var result = GetOutputParameters(sqlcmd.Parameters);
                            transaction.Commit();
                            return result;
                        }
                        catch(Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }

        }

        private Dictionary<string, object> GetOutputParameters(SqlParameterCollection paramCollection)
        {
            var returnParameters = new Dictionary<string, object>();
            foreach (SqlParameter par in paramCollection)
            {
                if ((par.Direction == ParameterDirection.Output) || (par.Direction == ParameterDirection.ReturnValue))
                {
                    returnParameters.Add(par.ParameterName, par.Value);
                }
            }
            return returnParameters;
        }
    }

A: I put your code into my own solution and recreated the problem. You are running into one of the reasons you should actually never do AddWithValue. Since you are adding a generic object, there is no way to infer what data type the sql parameter should be. If you break before ExecuteNonQuery and inspect the parameter list you will see it is defined as NVARCHAR with no length. So by default it is length 1.
You need to build your sql parameters with a real SqlDbType and you should set them with the Value property instead of AddWithValue.

UPDATE

To get started dynamically querying the parameter meta-data look at this. Note you still have more work to do, like mapping the sql types to SqlDbType:
DECLARE @spName sysname;
SET @spName = 'test_SP';

DECLARE @objId int;
SELECT @objId = ISNULL([object_id], 0) FROM sys.procedures WHERE [name] = @spName;

SELECT p.[name], p.[system_type_id], t.[name], p.[max_length], p.[precision],
    p.[scale], p.[is_output], p.[is_nullable]
FROM sys.parameters p
INNER JOIN sys.systypes t
    ON p.[system_type_id] = t.[xtype]
WHERE [object_id] = @objId;

A: Basically you need to give the correct SQLDbType and Size to your parameter. Especially if you omit the Size, your output will be truncated to 1 character.
SQL:
    @szError nvachar(max) output

C#:
    SqlParameter szError = new SqlParameter("szError", System.Data.SqlDbType.NVarChar)
    {
      Direction = System.Data.ParameterDirection.Output,
      Size = 4000
    };


text:
Q: Update inner.html before calling function If user inputs a value less than 5, I want the inner.html to update and the user to be prompted again. The code is functional on its own, but I want it to do an inner.html update AND the user to be prompted again, instead of having just the prompt without the inner.html changing.
Edit: I don't think this is a duplicate, the other question asks when and how reflow operations occur. But it doesn't solve the problem I have, which is to update inner.html before prompting, unless there's something I missed.

players = []
function numberOfPlayers() {
    playerCount = prompt("Please enter number of players. A minimum of 5 players is required.", "5");
    if (playerCount === null) {
      return;
    }
    if (parseInt(playerCount) >= 5) {
        document.getElementById("intro").innerHTML =
          "There are " + playerCount + " players.";
        namesOfPlayers(playerCount);
        } else {
      document.getElementById("intro").innerHTML =
        "Invalid. A minimum of 5 players is required. Hit the button to try again."

          numberOfPlayers(); //I want it to update the text before calling numberOfPlayers() again
//the prompt pops up without the text changing.
          }
    }
function namesOfPlayers(playerCount) {
    for (i = 1; i <= playerCount; i++) {

        var playerName = prompt("Enter name of player " + i, "John Doe")
        players.push(playerName)
        }
      document.getElementById("names").innerHTML =
        "The players are " + players.toString();
    }

</script>

Click the button to begin the game.

<button onclick="numberOfPlayers()">Begin</button>