text:
Q: Insert multiple entities at a time: Room I have an entities called BloodShareContact. I want to store list of this entities at a time. But it stores only one entity though it has more than one.
@Dao
public interface BloodShareDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    List<Long> insertAllBloodShareContact(List<BloodShareContact> contactList);

}

Repository Looks like.
public class BloodShareRepository {

private BloodShareDatabase bloodDatabase;

public BloodShareRepository(Context context) {
    bloodDatabase = BloodShareDatabase.getDataBaseInstance(context);
}

public void insertContacts(List<BloodShareContact> contactArrayList) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {

            bloodDatabase.bloodShareDao().insertAllBloodShareContact(contactArrayList);

            return null;
        }
    }.execute();
}

BloodShareContact Entity
@Entity
public class BloodShareContact {

    @PrimaryKey
    private int bid;

    private String blood_group;
    private String mobile;
    private String name;

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getMobile() {
        return mobile;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    public void setBlood_group(String blood_group) {
        this.blood_group = blood_group;
    }

    public String getBlood_group() {
        return blood_group;
    }

    @Override
    public String toString() {
        return
                "BloodShareContact{" +
                        "mobile = '" + mobile + '\'' +
                        ",blood_group = '" + blood_group + '\'' +
                        "}";
    }
}

Am i missing something?

A: I would try setting the primary key to auto generate.
@PrimaryKey(autoGenerate = true)
private int bid

Then set all of the bid to 0. This will make sure all the primary keys are unique. https://developer.android.com/reference/android/arch/persistence/room/PrimaryKey.html#autoGenerate()


text:
Q: Show when clicked on any of
* elements I have a page with different
 elements with content under them. The content is hidden, and it is meant to be that when you click on the
 element, the content under it, which is hidden, slides down and becomes shown. I have tried different methods, but none currently have worked as intended.
Here is a JSFiddle where only the first element works, but I need it for all elements, and, if possible, then with a slide effect. Thank you.
Link To fiddle
HTML

{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}

    {{ post.content }}

CSS
.storijs {
  display: none;
}

.para {
  display: block;
}

JS
document.getElementById("virsraksts").onclick = function() {
  myFunction()
};

function myFunction() {
  document.getElementById("kontents").classList.toggle("para");
}

A: Few Issues in your code:
1) You have used duplicate IDs. IDs must be unique. getElementById only selects first element with that ID.
2) You have added div as child element in ul. which makes the markup invalid. You should rather put that div element in li.

{{ post.date | date: "%B %d, %Y" }}: {{ post.title }}

  {{ post.content }}

Solution:
Use classname(slid) to target these elements as they have common class. and to target relevant .kontents element, traverse using .next() selector as its immediate next sibling of .slid:
$('.slid').click(function(){
   $(this).next().slideToggle();
});

Working Demo

A: Id is unique attribute and can be assigned to one element only. Every time you will try to getElementById it will get first LI only. Try using Class.

A: In your html code you have use ID in
 tag. ID should be unique. If you use different id name it will be work

redpajama_set_name: RedPajamaStackExchange


text:
Q: how open a pdf file from assents in an xamarin Android forms I want to open a PDF file from assents folder to activity in Xamarin Android

A: in MainActivity.cs
using Com.Joanzapata.Pdfview;
using Com.Joanzapata.Pdfview.Listener;
namespace openpdf
{
    [Activity(Label = "openpdf", MainLauncher = true)]
    public class MainActivity : Activity
    {
    PDFView pdf;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);

        **pdf = FindViewById<PDFView>(Resource.Id.pDFView1);
        pdf.FromAsset("finished.pdf").Load();**
    }
}

}
Main.Axml
<com.joanzapata.pdfview.PDFView
    android:layout_width="match_parent"
    android:layout_height="548.5dp"
    android:id="@+id/pDFView1" />


text:
Q: Posterior distribution of exponential prior and uniform likelihood I am working on Question 2 of this exam from Duke: First Year Exam - 2017
Let $X\mid\theta\sim \mathcal{U}(0,\theta)$ be a uniform likelihood and $\theta\mid\lambda\sim\text{Exp}(\lambda)$ be a prior on the upper limit of the uniform distribution. My question is, What is the posterior distribution of $\theta\mid X$?
I know Bayes' Theorem says,
\begin{align}
p(\theta\mid X)&\propto p(X\mid\theta)p(\theta) \\
&= \left(\frac{1}{\theta}\right)\left(\lambda\cdot\exp\left(-\lambda \theta\right)\right).
\end{align}
So far, so good. But I am having trouble because now I might try to find the normalizing constant of this posterior distribution:
\begin{align}
C &= \int_0^\infty p\left(\theta\mid X\right) \, d\theta \\
&=\int_0^\infty \left(\frac{1}{\theta}\right)\left(\lambda\cdot\exp\left(-\lambda \theta\right)\right) \, d\theta.
\end{align}
But according to WolframAlpha, this integral does not converge! How can one proceed to characterize this posterior distribution? Judging from the examination, you'd need to find the posterior mean to state what the Bayes estimator is under squared loss, but this expectation is proportional to the normalizing constant that doesn't seem to exist.

A: Why is your integral going from $0$ to $\infty$?
$\theta$ cannot be less than $X.$ Work with the interval $\theta\in [X,\infty).$


text:
Q: Jmeter RegEx Extractor I am new to Jmeter's Regular Expression Extractor. For an HTTP Request, I am getting an HTML Response. I want to extract all the URL strings.
This is one example; the number after tools in the id part changes.
    li>
 li>
 li>

How can this be done?

A: I have created jMeter tutorials for the very subject.
http://my.kpoint.com/kapsule/gcc-e1bad3ad-61cf-4620-9733-e44a74af8a3e/t/jmeter-tutorial-regex-extractor-basics
http://my.kpoint.com/kapsule/gcc-1dadaeee-1572-4c83-81fc-8d401cade743/t/jmeter-tutorial-multivalue-regex
http://my.kpoint.com/kapsule/gcc-744b552e-c91e-4db2-9d39-37c6e66f22ac/t/jmeter-tutorial-json-array-extraction

A: To extract url strings use regular expression- href="(.+?)"
To extract number after after tools in the id part use regular expression- id="link_sub_sub_cat_(.+?)"


text:
Q: SQL Update a table after comparing value with another table I have 3 tables involved in this scenario. Table1 (a temp table) has some order numbers. table2 has details about those(and all other) orders but maybe missing data in a few fields. table3 has those missing details.
what I need to do is, select each order from table2 that are in table1. There could be one or multiple orders in table1. So for those orders, I need to go and check table3.fieldx and see if there are any contents there. if not null, copy table3.fieldx to table2.fieldx.
some help would be appreciated.
sample table and data here
http://www.sqlfiddle.com/#!6/02947
Thanks.

A: Thanks for the sqlfiddle. With sample data this is actually something we can help with.
Think you want something like this.
update t2
set fieldx = ISNULL(t3.fieldx, t2.fieldx)
from #table2 t2
join #table1 t1 on t1.ord_num = t2.ord_num
left join #table3 t3 on t3.ord_num = t2.ord_num


text:
Q: Stencil Component - use querySelector() to select element within the shadow dom I'm creating a component that is wrapping a canvas library I've been using, to make it portable between a few of my applications and scope it's functionality/style to be consistent across applications.
The problem is, part of the library requires me to pass the canvas element as a parameter for a class.
Is it possible to select the element from inside the stencil class? The only way I've managed to accomplish it so far is by turning off the shadow DOM, which defeats the purpose a little bit.

A: To access elements in the Shadow DOM you have to use the shadowRoot property:
@Element() el;

// ...

const canvas = this.el.shadowRoot.querySelector('canvas');

A: After much searching (before asking) and very little searching (after asking) I've found an answer. Apparently refs are usable here.
<canvas ref={(el) => {this.canvas = el}}>
</canvas>


text:
Q: Clearing output of a terminal program in Linux C I want to clear the output of a C program produced with printf statements. I want to clear only one line, for example:
[source]
printf("AAAAAAAAAAAAAA\n");
printf("BBBBBBBBBBBBBB\n");
printf("CCCCCCCCCCCCCC\n");
printf("DDDDDDDDDDDDDD\n");

[terminal]
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC
DDDDDDDDDDDDDD

[I hope]
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC

I will "DDDDDDDDDDDDDD" line in write other string.
I just want the above A, B, C sentences to left.
Only clear D sentences to change the other sentences,
unconditionally output D sentences.
How do I do this?

A: If you are using X-Term compatibles (Gnome Terminal included), then print the following
printf("\033[2J");

or
cout << "\033[2J";

where \033 is the escape character in ASCII and [2J is the specific action (clear).

A: There're several ways to delete the DDDDDDDDDDDDDD

*

*Print backspace several times
printf("\b");

*Print carriage-return and then print something to override the original line
printf("\r");

*If you are in a newline. You may use terminal commands to move your cursor
such as printf("\033[8;5Hhello");  // Move to (8, 5) and output hello
Other commands:
printf("\033[XA"); // Move up X lines;
printf("\033[XB"); // Move down X lines;
printf("\033[XC"); // Move right X column;
printf("\033[XD"); // Move left X column;
printf("\033[2J"); // Clear screen
...

*Don't forget ncurses
It is the best ways to control the exact layout and format in a terminal

A: I tried answering for what is best expected here.
printf("AAAAAAAAAAAAAA");
printf("BBBBBBBBBBBBBB");
printf("CCCCCCCCCCCCCC");
//printf("DDDDDDDDDDDDDD");

comment the last line or delete if you dont want to display in terminal.
printf("xxxx") is the statement used for printing output in terminal.


text:
Q: How to mock RequestContext.getCurrentContext()? I am new bee here stuck in one problem regarding Zuul. I am writing test cases for Zuul filters first I want to know do I need to write UT's for my Zuul filters if yes then I am writing unit test of shouldFilter() method of my zuul filter in which I have to mock requestContext.
How can I achieve this goal ?
I have already mocked HttpServletRequest and RequestContext but when I go in debug mode it shows as null .. what am I missing ?
@Override
public boolean shouldFilter() {

    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    if (request.getHeader(Constants.AUTHORIZATION.getValue()) != null) {
        return true;
    }
    return false;
}

That is my original method
@Test
public void testShouldFilter(){

    MockHttpServletRequest request = new MockHttpServletRequest(context);
    request.addHeader("Authorization","123");
    RequestContext rc = new RequestContext();
    rc.setRequest(request);

    Mockito.when(requestContext.getCurrentContext().getRequest()).thenReturn(request);
    doReturn(request).when(requestContext).getRequest();
    doReturn(rc).when(requestContext)
    Mockito.when(request.getHeader()).thenReturn(rc);
    Mockito.when(RequestContextHolder.(Constants.AUTHORIZATION.getValue())).thenReturn(request.getHeader("Authorization"));
   boolean Sf = authorizationFilter.shouldFilter();
    Assert.assertFalse(Sf);
}

That is my Unit test
and Sorry for bad English
I expect request should have any mock object so that it can compare header value but its returning null.

A: RequestContext.testSetCurrentContext(new RequestContext());

or
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url");
RequestContext context = new RequestContext();
context.setRequest(request);
RequestContext.testSetCurrentContext(context);

Unit tests for filters are not something super good, but why not, it is up to you


text:
Q: Entire JS inside one global variable? I've got a school assignment of creating an app and one of the restrictions were that only one global variable was allowed, named "App". So I need to put the whole JS inside this variable.
I thought of doing something like:
App = function() { this.test = () => alert("test"); }

And then calling it with App.test().
But this doesn't work, the error I'm getting is:

Uncaught TypeError: App.test is not a function at HTMLLIElement.onclick (index.html:25)

Am I doing something wrong?

A: You need to define your app in a variable as an object and then you can use those members of the object such as:
// Object creation
window.App = {};

Then you add more properties like functions or variables and use it later inside of that variable.
window.App.test = function() {
   alert('test');
}

window.App.variable = 'my variable';

console.log( App.test() );
console.log( App.variable );

Another thing is you can omit the word window from App.

A: To be able to use your function that contains this.test..., you'll need to use it as a "constructor function" because this in a function declaration means "instance property", meaning you will need to explicitly create an instance of App with the new keyword:

    // Declare the global
    var App = function() { this.test = () => alert("test"); }

    // Make an instance of an object via the constructor function
    var myApp = new App();

    // Invoke the functionality via the instance
    myApp.test()

Or, set up App as an object, connect that object to the Global window object and set test as a property of App all without any instance properties (this references), which avoids having to make the explicit instance:

// Declare the global property as an Object
// and set up a "test" property that stores
// a function in that object:
window.App = { test: function(){alert("test");}}

// Invoke the functionality directly
App.test()

A: Keeping most of your approach as it is, you could return an object that has functions as properties.

App = function() {
  return {
    test: () => alert("test"),
    test2: () => alert("test2")
  };
}

App().test();
App().test2();

A: The test function is not defined before executing the App function:

App = () => test = () => alert("test")
<button onclick='App(); test()'>:</button>

App can be defined as object instead:

App = { test: () => alert("test") }
<button onclick='App.test()'>:</button>

A: Just to piggyback on to what the other answers have suggested, this technique is most commonly used (in browser developement) when you "namespace" some JS code. Namespacing is useful because it helps the developer reduce global variable pollution by adding all their code under one namespace under window.
This also helps the developer modularise the code.
Here's a pattern you might see from time to time that adds code to a single namespace under window.
// This first function is what's known as an Immediately-invoked
// function expression (IIFE). `window` is passed in as an argument
// to the function - all other declared variables are local to the scope
// of the function so you don't get anything leaking to global.
// PS, the semi-colon is there before the opening parenthesis to prevent
// any errors appearing if you minimise your code
;(function (window) {

  // Here we declare something new to add to the namespace
  // It could be another object, a string, an array, or a constructor
  // like Model
  function Model() {...}

  // If namespace `window.app` doesn't exist instantiate it with
  // an empty object. If it _does_ exist it probably means that another
  // module like this one has already been added to the namespace.
  window.app = window.app || {};

  // Then assign your new module as a property under that namespace
  window.app.Model = Model;

})(window);

You can then use it later something like this:
var model = new app.Model();
var game = new Game(model);

For further reading: Addy Osmani on namespacing.


text:
Q: the correct term for the killing of an entire species in research of this word, I don't believe there is an exact word. But I'm looking for a word with the suffix "-cide" at the end. If we go by other words in a similar formate like genocide (Geno being greek for race) then it's possible it would be: eídoscide (Eidos being greek for species). The correct term has to cover all of any one species, but only the one species. (so no, omnicide or mundicide)

A: Speciocide is "the elimination of an entire species" [Collins English Dictionary].

A: I wanted to supplement user282290's answer by noting some alternative forms that are also in use:

*

*specicide. In 2003, the New York Times published the opinion piece "A Bug's Death", by Olivia Judson, which uses the term "specicide" and defines it as "the deliberate extinction of an entire species". (The phrase "deliberate extinction" also works as a less neologistic term for this.)

*speciescide (mentioned on Wiktionary). (perhaps compare "speciesism"/"speciesist" for the first part, and "viruscide" for the second part) and

*speciecide (also mentioned at the Wiktionary link)

*speciesicide. Seems to have been used by some people, including in at least one book.


text:
Q: Facebook Messenger Customer Chat Plugin not appearing when not logged in I have integrated Facebook Customer Plugin on one of our websites. I followed the instructions in the developer documentation. It is working fine when there is an active facebook session. However, the plugin does not appear at all when there is no active fb session. I might be missing something but I have no clue on what that is.

A: The solution for me was adding #xfbml=1&version=v2.12&autoLogAppEvents=1 after the xfbml.customerchat.js file like :
js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js#xfbml=1&version=v2.12&autoLogAppEvents=1';

A: i solved my problem using this script :
<div class="fb-customerchat"
 page_id="<ENTER-YOUR-FACEBOOK-ID-HERE>"
 minimized="true">

Another case might be that, fb messenger only show when it it hosted, not locally.
For more info have a deep look at doumentation:
https://developers.facebook.com/docs/messenger-platform/discovery/customer-chat-plugin

A: It is May 2018 now, the instruction in Page --> Settings --> Messenger platform --> Customer chat plugin is much more clear.
Plus checking Country Restrictions

A: I only added this code to the customer chat code provided in the page's settings:
    window.fbAsyncInit = function() {
    FB.init({
      appId            : '1175565702494581', // Trokis Philippines App ID; you may use your App ID but this App ID might work on you too.
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v2.11'
    });
  };

Original Code:

Final Code:

A: Well, shamelessly it was the "Whitelisted Domains" that I didn't operate right.
After you insert your domain you should click "Save"...

A: At first I tried with a code generated by Facebook Customer Chat Plugin wizard - no luck. To make it work I had to add FB.init section providing valid developer appId:

You can find more info on the Facebook Customer Chat Plugin here

A: For me problem was, that i had whitelisted non www domain, but opened it through www. Both cases should be added as whitelist cases.

A: If you are using brave and probably debugging the site with included messenger plugin code. Most likely you'll find setting Block cross-site trackers to be disabled, Block scripts to be disabled, Cookies to be Allow all cookies, and lastly Fingerprinting to Allow all fingerprinting be helpful.
Once you changed the settings and you find that you have no problem in your code, then it will be most likely to work.

A: If you are using Angular Framework you have to know that you need to add your code in the index.html page and not in the app or component. That solved my problem.

A: Mine was because my "page visibility" was set to "page unpublished". So I resolved mine by changing the "page visibility" to "page published"
page setting->General->page visibility

A: Found a solution. If anyone encounters this, please check your Facebook Page's Country Restrictions (Settings->General->Country Restrictions). It must be available everywhere in order for the plugin to render even if there is no active session


text:
Q: Given an interval stored as [{name, value},...], how would I find where x lies? To easily illustrate this example, I have a interval like this:
        -6        -3        0         3        6
<-------o---------o---------o---------o--------o------->
  danger| warning |                   | normal | good

Which I store as an object, (notice nothing for interval -3 to 3)
EDIT: This is data structure is what I've been given, cannot make any changes.
{ name: 'good', value: 6 },
{ name: 'normal', value: 3 },
{ name: 'warning', value: -3 },
{ name: 'danger', value: -6 },

Given a value x I want to determine where it sits. So if:

*

*x = 3 or 4, it will return normal

*x = 6 or 100, it will return good

*x = -1 or 1 or -2, it will return '' (since nothing was assigned to those intervals)

*and similarly for negative numbers

My implementation in js was to loop through each object and if it was >=, it will overwrite. But I'd then write the same code again for negatives but with <=, does anyone have a better implementation?
var x = 4;
var returnInterval = '';
for (var point in interval) {
   if (x >= interval[point].value) {
       returnInterval = interval[point].name;
   }
}

return returnInterval;

A: Consider defining your ranges like this:
[
  { name: 'good', range: [6, Infinity },
  { name: 'normal', range: [3, 6] },
  { name: 'warning', value: [-6, -3] },
  { name: 'danger', value: [-Infinity, -6] }
]

With the existing data, you can build such a range like so:
var points = [
  { name: 'danger', value: -6 },
  { name: 'warning', value: -3 },
  { name: 'normal', value: 3 },
  { name: 'good', value: 6 }
];

// PRE CONDITION: elements are sorted by value (ascending)
var prev = -Infinity;

for (i = 0, j = 0; i <= points.length; ++i) {
  var current = i == points.length ? Infinity : points[i].value;

  if (prev >= 0 || current <= 0) {
    points[j].range = [prev, current];
    ++j;
  }

  prev = current;
}

It basically skips the segment with negative start and positive finish value.
Then, you can do simple bounds checks for each region.
function name(value)
{
  for (var i = 0; i != points.length; ++i) {
    var range = points[i].range;
    if (value >= range[0] && value <= range[1]) {
      return points[i].name;
    }
  }
  return '';
}

The nitty gritty of whether the checks are >=, >, < or <= is up to you.

A: This fits your data structure, but it seems a bit brittle. It just applies different logic depending on which side of the centre the value is on. It can be applied to any size range data array, as long as it has an even number of members.
var rangeData = [
  { name: 'good', value: 6 },
  { name: 'normal', value: 3 },
  { name: 'warning', value: -3 },
  { name: 'danger', value: -6 }
];

function getRangeName(rangeData, value) {

  // Get the middle range index, assume length is always even
  var midRange = rangeData.length / 2 - 1;
  var v, next;

  for (var i=0, iLen=rangeData.length; i<iLen; i++) {
    v = rangeData[i].value;
    next = rangeData[i+1]? rangeData[i+1].value : -Infinity;

    // High side of middle
    if (i <= midRange && value >= v ) {
      return rangeData[i].name;

    // Low side of middle
    } else if (i > midRange && value <= v && value > next) {
      return rangeData[i].name;
    }
  }
  // Default if in middle
  return '';
}

var testData = [7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7];

testData.forEach(function(v) {
  console.log(v + ': ' + getRangeName(rangeData, v));
});

results:
7: good
6: good
5: normal
4: normal
3: normal
2:
1:
0:
-1:
-2:
-3: warning
-4: warning
-5: warning
-6: danger
-7: danger


text:
Q: Setting access permissions to enclosed files for a NAS I'm using Ubuntu 16.04 Lts and a NAS (Synology, but I don't think the brand is relevant to my issue) where I backup my data and shares synced files with others.
My NAS synced files and folders from two different locations in my computer:

*

*home : /home (my default hdd in ubuntu)

*Data : /media/'myusername'/Data : which is a mounted hdd on which I store
data.

Everytime I reboot my computer the syncing software has trouble because it does not have sufficient access permission to sync files in Data (There is no issue to access home).
So I went to change permission (in property of Data) to give Create and Delete permissions to others. It worked until I reboot my computer. Then, the "not sufficient access permission" came back. I went back to the permission setting, the "Create and Delete permissions to others" was already activated, however, I had this time to change in "Change permissions for enclosed files" "Others : Read & Write + Create and delete files". And I have to do this every time I reboot my computer.
I have two related questions:

*

*how can I give access to this syncing software so that I don't have to change manually permission every time ?

*is there a more secure way to do it than giving all access and permission to "others" ? (I don't know why, but I feel there should be a way to say I only give these permission to the syncing software (Synology cloud station rather than every other users)

Thank you !


text:
Q: $M(x,y)\,dx+N(x,y)\,dy=0$ can always be converted to the form $dy/dx=F(y/x)$ I'm being asked to prove that all $M(x,y)\,dx+N(x,y)\,dy=0$ can always be converted to the form $dy/dx=F(y/x)$.
My guess is that I just have to manipulate and that's easy. But I have no clue what $F(y/x)$ means. I've searched on google and the closest thing I have found are "functional equations".
Can anybody help me understand this?
Thanks a lot.


text:
Q: Apply formula to all visible cells in column CK, occasionally there will be no rows I have a filter applied to column CK, I am able to select the next visible row from the header by using the following, which also applies a formula into that active cell.
How do I fill that formula down to the bottom, without affecting the hidden rows?
Occasionally there will be no data, so it's just applying a formula to a blank row..
   range("CK1").Select
        ActiveSheet.range("$A$1").AutoFilter Field:=89, Criteria1:="0"

    ' Add if formula to find missing carriers based on patterns

            Do
            ActiveCell.Offset(1, 0).Select
        Loop While ActiveCell.EntireRow.Hidden = True

ActiveCell.Formula2R1C1 = _
        "=IFS(AND(LEN(RC[1])=18,LEFT(RC[1],2)=""1Z""), ""UPS"", AND(LEN(RC[1])=12,ISNUMBER(RC[1])),""FedEx"",AND(LEN(RC[1])=10,ISNUMBER(RC[1])),""DHL"",AND(LEN(RC[1])=11,LEFT(RC[1],2)=""06""),

A: It would be great if you could refrain from selecting cells or activating sheets or workbooks like you do. The only time it is fine to have Excel change its selection on screen with VBA is if you want it to.
For your problem, a simple loop will do. Example with CK1 and all the cells below it:
Dim topCell As Range, bottomCell As Range
Set topCell = Range("CK1")
Set bottomCell = topCell.end(xlDown)

'Next test is optional, although recommended (is there no cell filled under CK1?)
If bottomCell.Row >= 1048576 Then 'Current maximal row; you may change the threshold if desired.
    Exit Sub
    'Alternatively: Exit Function
    'Other alternative example: Set bottomCell = Range("CK1000")
End If

Dim c As Range
For Each c In Range(topCell, bottomCell)
    If Not c.EntireRow.Hidden Then
        c.Formula2R1C1 = "" '<place your formula here>
    End If
Next c


text:
Q: How to create circular progress bar like below image in flutter
I want to create this circular progress bar with animation and working on percentage

A: You can either achieve this using CustomPaint to draw it yourself (recommended), or perhaps using a Stack to put 3 different-sized CircularProgressIndicators on top of each other.
It's not difficult to custom paint this: for each ring, you can first draw a grey circle as the background, then draw a colored arc path. You can round the ends by setting Paint()..strokeCap = StrokeCap.round.


text:
Q: Prove by induction that for n > 8, ${n \choose k} < 2^{n-2}$ for each $k \in \mathbb{Z}$ This problem also comes with a second-half that then asks again to prove by induction that for every $n > 7$, $\displaystyle {n \choose k} < (n-3)!$ for each integer $k$.
I have gotten to what I think is the base case for the first half, but I am very lost. Any help?

A: You know that the maximum value of ${n \choose k}$ is given as follows:
If n is even, $max {n\choose k} = \Large\frac {n!}{\frac {n}{2}!\frac {n}{2}!}$, or $k=\frac{n}{2}$ and $n-k=\frac{n}{2}$
If n is odd, $max {n\choose k} = \Large\frac {n!}{\frac {n-1}{2}!\frac {n+1}{2}!}$, or $k=\frac{n-1}{2}$ and $n-k=\frac{n+1}{2}$.
So in order to prove that ${n \choose k}<2^{n-2}$, it is sufficient to prove the inequality for the max values for both odd and even cases.
First we prove that n=9 holds.
${9 \choose 4}=\frac {9!}{4!5!}= 126 < 128=2^{9-2} $. So n=9 holds.
Let $n=p$ hold for some value of $p>9$
Case 1:
p is even. $\therefore\Large\frac{p!}{\frac{p}{2}!\frac{p}{2}!}<2^{p-2}$
Now $\Large\frac{p+1}{\frac{p}{2}+1}<2$.
Thus we can multiply the 2 given inequalities to get
$\Large\frac{p!*(p+1)}{\frac{p}{2}!\frac{p}{2}!(\frac{p}{2}+1)}<2^{p-2}*2$
Or $\Large\frac{(p+1)!}{\frac{p}{2}!(\frac{p}{2}+1)!}<2^{p-1}$. Thus it holds when p is even.
Case 2:
p is odd. $\therefore\Large\frac{p!}{\frac{p-1}{2}!\frac{p+1}{2}!}<2^{p-2}$
now $\frac{p+1}{\frac{p-1}{2}+1}=2$.
We can still multiply the inequality and the equality to get
$\Large\frac{p!*(p+1)}{\frac{p-1}{2}!\frac{p+1}{2}!(\frac{p-1}{2}+1)}<2^{p-2}*2$
Or $\large\frac{(p+1)!}{\frac{p+1}{2}!(\frac{p+1}{2})!}<2^{p-1}$. Thus it holds when p is odd also.
$\Rightarrow$ The given inequality is true for n>8

A: The inequality is true for $n=9$ since $max({9 \choose k})={9 \choose 4}={9 \choose 5}=126<2^{9-2}$
Now we use the following identity
${{n+1} \choose k} = {n \choose k} + {n \choose {k-1}}$
If the inequality is true for $n>8$, then
${{n+1} \choose k} = {n \choose k} + {n \choose {k-1}}<2^{n-2}+2^{n-2}=2^{n+1-2}$ or simply
${{n+1} \choose k}<2^{n+1-2}$
Therefore, the inequality is true for all $n>8$ by induction.


text:
Q: Tensorflow cannot open MNIST anymore I am starting to work again on tensorflow. I was relaunching some codes I did a few years ago, it's not working though.
Old version
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

import tensorflow as tf

# Parameters
learning_rate = 0.001
training_epochs = 20
batch_size = 128  # Decrease batch size if you don't have enough memory
display_step = 1

n_input = 784  # MNIST data input (img shape: 28*28)
n_classes = 10  # MNIST total classes (0-9 digits)

n_hidden_layer = 256 # layer number of features

# Store layers weight & bias
weights = {
    'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])),
    'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes]))
}
biases = {
    'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# tf Graph input
x = tf.placeholder("float", [None, 28, 28, 1])
y = tf.placeholder("float", [None, n_classes])

x_flat = tf.reshape(x, [-1, n_input])

# Hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(x_flat, weights['hidden_layer']),\
    biases['hidden_layer'])
layer_1 = tf.nn.relu(layer_1)
# Output layer with linear activation
logits = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])

# Define loss and optimizer
cost = tf.reduce_mean(\
    tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\
    .minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

From what I have understood the cause comes from the "read_data_sets" and I should use "tf.data". The problem with "tf.data" is that I cannot use that anymore:
mnist.train.num_examples
mnist.train.next_batch

And the data is not one encoded.
I have tried something like that:
import tensorflow_datasets as tfds
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# Mandatory: to launch
#tf.enable_eager_execution()

mnist_data, info = tfds.load("mnist", with_info=True, as_supervised=True)
mnist_train, mnist_test = mnist_data["train"], mnist_data["test"]

And, mnist_train.batch instead of mnist.train.next_batch
# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        total_batch = int(info.splits["train"].num_examples/batch_size)
        print(total_batch)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist_train.batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

With the error:
RuntimeError: dataset.__iter__() is only supported when eager execution is enabled.

And if I do :
tf.enable_eager_execution()

I cannot use
tf.placeholder()

New version
import tensorflow_datasets as tfds
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# Mandatory: to launch
#tf.enable_eager_execution()

mnist_data, info = tfds.load("mnist", with_info=True, as_supervised=True)
mnist_train, mnist_test = mnist_data["train"], mnist_data["test"]

    import tensorflow as tf

    # Parameters
    learning_rate = 0.001
    training_epochs = 20
    batch_size = 128  # Decrease batch size if you don't have enough memory
    display_step = 1

    n_input = 784  # MNIST data input (img shape: 28*28)
    n_classes = 10  # MNIST total classes (0-9 digits)

    n_hidden_layer = 256 # layer number of features

    # Store layers weight & bias
    weights = {
        'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])),
        'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes]))
    }
    biases = {
        'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer])),
        'out': tf.Variable(tf.random_normal([n_classes]))
    }

    # tf Graph input
    x = tf.placeholder("float", [None, 28, 28, 1])
    y = tf.placeholder("float", [None, n_classes])

    x_flat = tf.reshape(x, [-1, n_input])

    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x_flat, weights['hidden_layer']),\
        biases['hidden_layer'])
    layer_1 = tf.nn.relu(layer_1)
    # Output layer with linear activation
    logits = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])

    # Define loss and optimizer
    cost = tf.reduce_mean(\
        tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\
        .minimize(cost)

    # Initializing the variables
    init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        total_batch = int(info.splits["train"].num_examples/batch_size)
        print(total_batch)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist_train.batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

A: When you load data using tfds.load you get an instance of tf.data.Dataset. You cannot feed this directly to a feed_dict but rather have to make an iterator and feed the values you obtain from the iterator at each step into the feedable input.You can do something roughly like this:
# one hot encode for 10 MNIST classes
def my_one_hot(feature, label):
    return feature, tf.one_hot(label, depth=10)

# load your data from tfds
mnist_train, train_info = tfds.load(name="mnist", with_info=True, as_supervised=True, split=tfds.Split.TRAIN)

# convert your labels in one-hot
mnist_train = mnist_train.map(my_one_hot)

# you can batch your data here
mnist_train = mnist_train.batch(8)

Then you can launch your graph (and initialize your iterator)
# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # make an iterator
    train_iterator = mnist_train.make_initializable_iterator()
    next_element = train_iterator.get_next()

    # Training cycle
    for epoch in range(training_epochs):

        sess.run(train_iterator.initializer)
        batch_train_x, batch_train_y = sess.run(next_element)

        total_batch = int(train_info.splits["train"].num_examples/batch_size)
        print(total_batch)
        # Loop over all batches
        for i in range(total_batch):
            # Run optimization op (backprop) and cost op (to get loss value)
            sess.run(optimizer, feed_dict={x: batch_train_x, y: batch_train_y})

For more infor on tf.data.Dataset look at the guide. Hope it helps!


text:
Q: ACH payments does not work with Authorize.NET A user is trying to make an ACH payment from our portal but it doesn't work , I get an Error - the ABA code is invalid (but its a valid code..) , when he does the same payment directly with Authorize.NET portal, it does work.
Can anybody advise? I tired to contact Authorize.NET but had no response.
This is the code:
/**
 * Debit a Bank Account
 * Use this method to process an ACH debit transaction using bank account details.
 * @param float $amount
 * @param int $routingNumber
 * @param int $accountNumber
 * @param string $nameOnAccount
 * @param string $bankName
 * @return array
 */
public function paymentTransactionsDebitBankAccount(
    float $amount,
    int $routingNumber,
    int $accountNumber,
    string $nameOnAccount,
    string $bankName,
    string $accountType,
    string $eCheckType
): array
{
    $paymentTransactions = new PaymentTransactions(
        $this->apiLoginId,
        $this->transactionKey,
        $this->apiKey,`your text`
        $this->endPointApi
    );

    $paymentTransactions->setOrderInformation(
        orderInformationInvoiceNumber: $this->contract->id,
        orderInformationDescription: 'Contract ' . $this->contract->name
    );

    $paymentTransactions->setTransactionRequest(
        transactionRequestType: 'authCaptureTransaction'
    );

    $debitBankAccount = $paymentTransactions->debitBankAccount(
        amount: $amount,
        routingNumber: $routingNumber,
        accountNumber: $accountNumber,
        nameOnAccount: $nameOnAccount,
        bankName: $bankName,
        accountType: $accountType,
        eCheckType: $eCheckType,
    );

    if ($debitBankAccount != null) {
        if ($debitBankAccount->getMessages()->getResultCode() == "Ok") {
            $tresponse = $debitBankAccount->getTransactionResponse();

            if ($tresponse != null && $tresponse->getMessages() != null) {
                $debitBankAccountMessageText = " Transaction Response code : " . $tresponse->getResponseCode() . "\n";
                $debitBankAccountMessageText .= " Debit Bank Account APPROVED  :" . "\n";
                $debitBankAccountMessageText .= " Debit Bank Account AUTH CODE : " . $tresponse->getAuthCode() . "\n";
                $debitBankAccountMessageText .= " Debit Bank Account TRANS ID  : " . $tresponse->getTransId() . "\n";
                $debitBankAccountMessageText .= " Code : " . $tresponse->getMessages()[0]->getCode() . "\n";
                $debitBankAccountMessageText .= " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";

                return [
                    'status' => 'Ok',
                    'message' => $debitBankAccountMessageText,
                    'data' => [
                        'transaction_response_code' => $tresponse->getResponseCode(),
                        'transaction_id' => $tresponse->getTransId(),
                        'auth_code' => $tresponse->getAuthCode(),
                        'message_code' => $tresponse->getMessages()[0]->getCode(),
                        'message_description' => $tresponse->getMessages()[0]->getDescription()
                    ],
                ];

            } else {
                $debitBankAccountMessageText = "Transaction Failed \n";
                if ($tresponse->getErrors() != null) {
                    $debitBankAccountMessageText .= " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                    $debitBankAccountMessageText .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
                }

                return [
                    'status' => 'Error',
                    'message' => $debitBankAccountMessageText,
                    'data' => null,
                ];
            }
        } else {
            $debitBankAccountMessageText = "Transaction Failed \n";
            $tresponse = $debitBankAccount->getTransactionResponse();
            if ($tresponse != null && $tresponse->getErrors() != null) {
                $debitBankAccountMessageText .= " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                $debitBankAccountMessageText .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
            } else {
                $debitBankAccountMessageText .= " Error code  : " . $debitBankAccount->getMessages()->getMessage()[0]->getCode() . "\n";
                $debitBankAccountMessageText .= " Error message : " . $debitBankAccount->getMessages()->getMessage()[0]->getText() . "\n";
            }

            return [
                'status' => 'Error',
                'message' => $debitBankAccountMessageText,
                'data' => null,
            ];
        }
    } else {
        return [
            'status' => 'Error',
            'message' => 'No response returned',
            'data' => null,
        ];
    }
}


text:
Q: IIS8 Reverse Proxy - Custom external port I am trying to configure my IIS reverse proxy to route http connections to an internal server however I am not sure how to achieve what I need or even if it is possible.
I have a sub domain on my IIS server for example,
testing.contoso.com and externally I would like to have http://testing.contoso.com:8080 which will then map to my internal server http://server04.contoso.local:8080. So I do not want my internal site to appear as http://testing.contoso.com on port 80.
My reason for doing this is that I will have quite a few internal and external corresponding ports.
Is it possible to configure this with my IIS reverse proxy or does IIS only support ports 80 & 443 externally?
Thanks in advance, Neil

A: From what I see in your question, it should be fairly easy to make that work using IIS Application Request Routing: http://www.iis.net/downloads/microsoft/application-request-routing
That should let you use any ports or hostnames in a machine being exposed and then let that route to any other machines (or same) in any ports or combination. It also will allow you to offload cache of static files, and many other nice features. It uses URL Rewrite for the main engine on which server to route to, so you can literally add any logic you want, and if need be you could use extensibility of URL Rewrite to add custom code to define the logic (though the built-in configuration one should be rich enough).


text:
Q: How to make the terminal font look like notepad's? The terminal font of Visual Studio 2013 text editor looks nothing like the terminal font of notepad (OS is Windows 8.1 64 bit). It's an annoyance to me, especially when coding in C; nearly superscripted (and miniature sized) star feels out of place. Funny thing is, on VS2013 text editor, Terminal and FixedSys are exactly the same thing (which is neither Terminal nor FixedSys of notepad).
Is there way to take my Terminal font back?
(Consolas is sort of okay, but it has the same issue of the elevated star character).


text:
Q: Помогите разобраться что тут делает цикл for # Hangman Game
#
# The classic game of Hangman.  The computer picks a random word
# and the player wrong to guess it, one letter at a time.  If the player
# can't guess the word in time, the little stick figure gets hanged.

# imports
import random

# constants
HANGMAN = (
"""
 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |   -+-
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   |
 |   |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | |
 |   | |
 |
----------
""")

MAX_WRONG = len(HANGMAN) - 1
WORDS = ("OVERUSED", "CLAM", "GUAM", "TAFFETA", "PYTHON")

# initialize variables
word = random.choice(WORDS)   # the word to be guessed
so_far = "-" * len(word)      # one dash for each letter in word to be guessed
wrong = 0                     # number of wrong guesses player has made
used = []                     # letters already guessed

print("Welcome to Hangman.  Good luck!")

while wrong < MAX_WRONG and so_far != word:
    print(HANGMAN[wrong])
    print("\nYou've used the following letters:\n", used)
    print("\nSo far, the word is:\n", so_far)

    guess = input("\n\nEnter your guess: ")
    guess = guess.upper()

    while guess in used:
        print("You've already guessed the letter", guess)
        guess = input("Enter your guess: ")
        guess = guess.upper()

    used.append(guess)

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        # create a new so_far to include guess
        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]
        so_far = new

    else:
        print("\nSorry,", guess, "isn't in the word.")
        wrong += 1

if wrong == MAX_WRONG:
    print(HANGMAN[wrong])
    print("\nYou've been hanged!")
else:
    print("\nYou guessed it!")

print("\nThe word was", word)

input("\n\nPress the enter key to exit.")

Помогите пожалуйста, обьясните суть работы цикла for, распишите на человеческий язык что тут происходит:
 used.append(guess)

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        # create a new so_far to include guess
        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]
        so_far = new

A: Изначально
so_far = "-" * len(word)

по коду, содержит количество символов  '-' равное длине слова или количеству букв. А далее цикл
new = "" # create a new so_far to include guess / создается переменная "new" для
                                              взаимодействия с "so_far"

for i in range(len(word)):
if guess == word[i]:  / по буквам сравнивает, если буква в этом отгадываемом слове
    new += guess      /если есть в место символа '-'вставляем букву и сохраняем в "new"
else:
    new += so_far[i]  / если нет, допечатываем символы '-' из переменной "so_far"

so_far = new
Очень своеобразный момент, идет пересохранение переменной "so_far" через переменную "new", в которой отражено реальное положение угаданных букв и прочерков в данный этап отгадывания слова.
Такое своеобразное нанизывание на ниточку бусенок, в виде отгаданных букв.
И далее следует таким макаром, до полного отгадывание или не отгадывание слова.

A: Если введённая буква содержится в загаданном слове, то она добавляется в строку so_far, в которой записаны уже угаданные ранее буквы.


text:
Q: Is this java classpath set correctly? I really have no idea what I'm missing. I've spent many hours reading up on how to set classpaths but this still does not work, at this point I am convinced it must be something trivial which escapes me.
I'm trying to use the swing radiance libraries to change the look and feel of a swing application. I followed the build documentation to make the jar files and when those didn't work I downloaded and tried the prebuilt binaries. I opened an issue with developer and confirmed I was following the getting started instructions correctly. The code for demonstration is as follows:
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;

public class Walkthrough extends JFrame {
  public Walkthrough() {
    super("Sample app");
    this.setLayout(new FlowLayout());
    this.add(new JButton("button"));
    this.add(new JCheckBox("check"));
    this.add(new JLabel("label"));

    this.setIconImage(new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR));
    this.setSize(new Dimension(250, 80));
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);

    SwingUtilities.invokeLater(() -> {
        Walkthrough w = new Walkthrough();
        w.setVisible(true);
    });
  }
}

The code is first compiled with javac Walkthrough.java and executed with java Walkthrough. This works fine. Next the radiance jars are used to change the look and feel, this is done by setting the swing.defaultlaf property to use a skin from radiance. This is where it does not work.
I copied all the required jars into a tmp directory, where the Walkthrough example exists immediately outside of tmp. I then try to run the application as follows:
java -Dswing.defaultlaf=org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel -cp .:tmp/radiance-substance-2.5-SNAPSHOT.jar:tmp/radiance-trident-2.5-SNAPSHOT.jar:tmp/radiance-neon-2.5-SNAPSHOT.jar Walkthrough

Which leads to the following exception:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot load org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel
    at java.desktop/javax.swing.UIManager.initializeDefaultLAF(UIManager.java:1406)
    at java.desktop/javax.swing.UIManager.initialize(UIManager.java:1517)
    at java.desktop/javax.swing.UIManager.maybeInitialize(UIManager.java:1483)
    at java.desktop/javax.swing.UIManager.getUI(UIManager.java:1056)
    at java.desktop/javax.swing.JPanel.updateUI(JPanel.java:126)
    at java.desktop/javax.swing.JPanel.<init>(JPanel.java:86)
    at java.desktop/javax.swing.JPanel.<init>(JPanel.java:109)
    at java.desktop/javax.swing.JPanel.<init>(JPanel.java:117)
    at java.desktop/javax.swing.JRootPane.createGlassPane(JRootPane.java:521)
    at java.desktop/javax.swing.JRootPane.<init>(JRootPane.java:348)
    at java.desktop/javax.swing.JFrame.createRootPane(JFrame.java:279)
    at java.desktop/javax.swing.JFrame.frameInit(JFrame.java:258)
    at java.desktop/javax.swing.JFrame.<init>(JFrame.java:225)
    at Walkthrough.<init>(Walkthrough.java:7)
    at Walkthrough.lambda$main$0(Walkthrough.java:23)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

The org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel lives in radiance-substance-2.5-SNAPSHOT.jar. I have confirmed it is indeed there with jar tvf:
jar tvf radiance-substance-2.5-SNAPSHOT.jar | grep SubstanceBusinessLookAndFeel
   548 Fri Feb 01 00:00:00 GMT 1980 org/pushingpixels/substance/api/skin/SubstanceBusinessLookAndFeel.class

So at this point I'm sure that I'm messing something up with the classpath, but I just don't know what. I'm on Fedora 28 and my java version is:
java version "12.0.1" 2019-04-16
Java(TM) SE Runtime Environment (build 12.0.1+12)
Java HotSpot(TM) 64-Bit Server VM (build 12.0.1+12, mixed mode, sharing)

A: Well this had nothing to do with the classpath and rather to do with the jar libraries themselves. I observed that the font was not anti-aliased by default on my machine (Fedora 28, using i3-gaps as a window manager). I wondered if this was somehow related and did some reading on Java runtime environment fonts. In essence the fonts looked like this:

But launching the application with this system property: -Dawt.useSystemAAFontSettings=on fixed things:

It turns out that setting this property when launching Walkthrough with Radiance makes it work:
java -Dawt.useSystemAAFontSettings=on -Dswing.defaultlaf=org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel -cp .:tmp/radiance-substance-2.5-SNAPSHOT.jar:tmp/radiance-trident-2.5-SNAPSHOT.jar:tmp/radiance-neon-2.5-SNAPSHOT.jar Walkthrough.

Removing this property results in the error of Java being unable to load org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel.
Reading here has more information. I assume because I have customised my Fedora 28 setup (I don't use gnome) is the reason I don't have an gnome-settings-daemon running from which Java uses to get the system defaults and this is somehow a problem for Radiance...? Not sure.
I've informed the Radiance developer about this. I'll update this answer if/when he provides feedback.
UPDATE
The developer confirmed this has a bug in the library. It has been fixed.


text:
Q: too few arguments sprintf I have done this many times before, to re-use a value passed into the sprintf() function.  But this code is returning a "Warning: sprintf() [function.sprintf]: Too few arguments in..." message.
Here is the code:
$search_clause = sprintf(" (msgBody LIKE %%%1$s%% OR msgSubject LIKE '%%%1$s%%' ) ", mysql_real_escape_string($match1));

Ideally the value of $match1 will be inserted into the segment of the SQL WHERE clause shown above - twice, each wrapped by '%' characters for a wildcard search.
If $match1 = "test", the resulting string value of $search_clause would be:
(msgBody LIKE '%test' OR msgSubject LIKE '%test%' )

What is the obvious mistake I'm making??

A: Just escape the $ as \$.
$search_clause = sprintf(" (msgBody LIKE %%%1\$s%% OR msgSubject LIKE '%%%1\$s%%' ) ", mysql_real_escape_string($match1));
                                             ^                             ^

A: The $s is probably getting interpreted as a variable (see variable expansion). Try using single quotes instead:
$search_clause = sprintf(' (msgBody LIKE "%%%1$s%%" OR msgSubject LIKE "%%%1$s%%" ) ', mysql_real_escape_string($match1));


text:
Q: pd.insert ValueError: Buffer has wrong number of dimensions (expected 1, got 2) I have the following dataset(sample):
df = pd.DataFrame({'col_1':['Region1 (Y0001)','Region2 (Y0002)',
                       'Region3 (Y0003)','Region4 (Y0004)','Region5 (Y0005)'],
              'col_2':np.arange(1,6),
              'col_3':np.arange(6,11),
              'col_4':np.arange(11,16)})

NOTE: I had to change the real values, but the data types and structure are the same.
I can't get a hold of this error I get when using pd.insert().
df.insert(df.columns.get_loc('col_1'),
      'new_col',
      df['col_1'].str.extract(r'\((\w+)\)'))

I checked the correct functioning of pd.insert() by running the following, and it worked!
df.insert(0,'Random_Col',55)

As far as I can tell, this error came up after I upgraded pandas to 1.4.3; I didn't have this issue before. However, this doesn't explain why the above check was executed flawlessly.
How can I resolve this error?

A: DataFrame.insert expects 3 positional arguments. loc which is an int, column which is a valid column name, and value which is either a single value or 1 dimensional data (e.g. Series or array-like).
Currently (pandas 1.4.3) str.extract returns a DataFrame by default:
df['col_1'].str.extract(r'\((\w+)\)')

       0
0  Y0001
1  Y0002
2  Y0003
3  Y0004
4  Y0005

The error message:

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

is indicating that a 2-dimensional structure (a DataFrame) was provided as the value to insert which is 1 dimension more than the expected.

There are a few options to fix this.

*

*Since there is a single capture group we can stop the output from expanding into a DataFrame with expand=False
df.insert(
    df.columns.get_loc('col_1'),
    'new_col',
    df['col_1'].str.extract(r'\((\w+)\)', expand=False)
)

OR

*Select a column from the output. In this case column 0.

df.insert(
    df.columns.get_loc('col_1'),
    'new_col',
    df['col_1'].str.extract(r'\((\w+)\)')[0]  # Get capture group (column) 0
)

Either option produces df:
  new_col            col_1  col_2  col_3  col_4
0   Y0001  Region1 (Y0001)      1      6     11
1   Y0002  Region2 (Y0002)      2      7     12
2   Y0003  Region3 (Y0003)      3      8     13
3   Y0004  Region4 (Y0004)      4      9     14
4   Y0005  Region5 (Y0005)      5     10     15


text:
Q: OpenGL 3 program blank screen I've been converting some of my old code to OpenGL 3, and I've gotten most of it working. All the VAOs, VBOs, etc. are working fine, as verified by an OpenGL debugging program, and my shaders compile just fine, but nothing appears on the screen other than my clear color. I think all my matrices should be fine, although I'm not sure if the projection matrix is supposed to convert negative Z-coordinates to positive ones; every code sample I've tried produces such a matrix. Here are my shaders:
Vertex shader:
#version 330

uniform mat4 modelview;
uniform mat4 projection;

in vec4 position;
in vec4 normal;
in vec4 texCoord;

void main() {
    gl_Position = projection * modelview * position;
}

Fragment shader:
#version 330

out vec4 fragColor;

void main() {
    fragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

My code is complex, so I'll just post a modified, commented version of the glIntercept call log, which should have all the relevant calls:
    //Create shaders
glCreateShader(GL_VERTEX_SHADER)=1
glShaderSource(1,1,vertShaderText,vertShaderTextLen)
glCompileShader(1)
glGetShaderiv(1,GL_COMPILE_STATUS,buf)
glCreateShader(GL_FRAGMENT_SHADER)=2
glShaderSource(2,1,fragShaderText,fragShaderTextLen)
glCompileShader(2)
glGetShaderiv(2,GL_COMPILE_STATUS,buf)
glCreateProgram()=3
glAttachShader(3,1)
glAttachShader(3,2)
glLinkProgram(3)
glGetProgramiv(3,GL_LINK_STATUS,buf)
//Find uniform/attribute locations
//Extra glUseProgram() calls are for safety.
glGetUniformLocation(3,"modelview")=0
glUseProgram(3)
glGetUniformLocation(3,"projection")=1
glUseProgram(3)
glGetAttribLocation(3,"position")=0
glUseProgram(3)
glGetAttribLocation(3,"normal")=-1
glUseProgram(3)
glGetAttribLocation(3,"texCoord")=-1
//Create a texture; probably irrelevant to this code
glGenTextures(1,texId)
glBindTexture(GL_TEXTURE_2D,1)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,texData)
glGenTextures(1,01DD275C)
//Create VAO, VBO
glGenVertexArrays(1,vaoId)
glBindVertexArray(1)
glGenBuffers(1,bufId)
glBindBuffer(GL_ARRAY_BUFFER,1)
//Redundant call; actual data set later
glBufferData(GL_ARRAY_BUFFER,0,00000000,GL_STATIC_DRAW)

glGenBuffers(1,indexBufId)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,4)
glBufferData(GL_ELEMENT_ARRAY_BUFFER,0,00000000,GL_STATIC_DRAW)

//Set up buffer data
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,4)
glBufferData(GL_ELEMENT_ARRAY_BUFFER,96,indexData,GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER,1)
glBufferData(GL_ARRAY_BUFFER, 48,01DC3D00,GL_STATIC_DRAW)

//Start drawing
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
glUseProgram(3)
glUseProgram(3)
//Modelview
glUniformMatrix4fv(modelviewLocation,1,false,[1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,-6.000000,1.000000])
glUseProgram(3)
//Projection
glUniformMatrix4fv(projectionLocation,1,false,[0.200000,0.000000,0.000000,0.000000,0.000000,0.150000,0.000000,0.000000,0.000000,0.000000,-1.000200,-1.000000,0.000000,0.000000,-0.200020,0.000000])
//Bind VAO, VBOs, and attribute positions
glBindVertexArray(1)
glBindBuffer(GL_ARRAY_BUFFER,1)
glVertexAttribPointer(positionAttributeLocation,3,GL_FLOAT,false,12,00000000)
glEnableVertexAttribArray(positionAttributeLocation)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,4)
glDrawElements(GL_TRIANGLES,24,GL_UNSIGNED_INT,00000000) GLSL=3  Textures[ (0,2) ]
glDisableVertexAttribArray(0)

I've got a plane facing directly into the camera, but it doesn't show up at all. All I see is the clear color. Culling and depth test are off.

A: When passing uniforms to a shader i've used glGetUniformLocation() in the following way:
myUniformLocation = glGetUniformLocation(program, "myUniform")
glUniform1f(myUniformLocation, variable_value)

A: Your log does not show any glEnableVertexAttribArray call. Did you forget that?

A: As it turns out, my problem was in my initialization code. I had uninitialized variables that were being passed to glViewport, giving me a 0x0 viewport.


text:
Q: Sharing LINQ-to-SQL classes/models between multiple projects in a solution I have multiple C# projects in a Visual Studio solution right now that will all use the same SQL Server database.
What is the proper way to share LINQ-to-SQL classes between projects?
I'm considering just copying the dmbl files into each project, but I think that may be too redundant. Is there a better way to approach this?

A: I suppose you need to share database access code between projects not linq-2-sql classes as they are.
Build Data Access Library (DAL) that expose operations over database that are implemented via linq-2-sql classes rather then expose classes.
I'd suggest to use Repository Pattern
Refer DAL library from projects you want.

A: You could: Build it as a class library and include it. It is just a class, right.

A: If they are in the same solution you could add references to the Linq-project in the projects that needs to access the Linq-classes. Or am I misunderstanding your question? You do this by right-clicking the "References" folder of the project that needs to access the Linq-classes, select the "Projects" tab and the select the Linq-project.
If it is strict data access you are after, follow Andrew Florko's advice and build a Data Access Layer to get the data you need.

A: What you need to do is create a Class Library that contains your DBML classes.  Then you add that as a reference to your other projects.  Make sure there's nothing in that class library except for database-related code so it's easy to add to future projects.
Then do what Andrew Florko suggested and read up on data access patterns.  Repository is nice, though I like the DAO.

A: I would separate not only the Model classes but the entire Data Access Layer (DAL) into a separate assembly that you reference from other parts of your application.
The DAL will encapsulate the details of how it interacts with the database (in this case the usage of LINQ to SQL) and hide them behind a well-defined interface that is meaningful for the application.
Also, since the classes generated from the LINQ to SQL DBML file are just Plain Old CLR Objects (POCO), I don't see a problem in exposing them directly as part of your DAL's interface.


text:
Q: PHP detection of iPad to prevent file upload So apparently the iPad does not allow you to upload images to a server via the browser ... so I need to be able to detect that the user is using an iPad and then hide the ability for them to "browse" for a file.
Is there any particular best practice for such a thing via PHP?

A: I'd ignore that myself, but if you really want, you check UserAgent using get_browser(). Please note you need browse.cap file installed and PHP pointed to it - see docs for details.
Alternatively inspect it by hand: $_SERVER['HTTP_USER_AGENT'].
Docs for get_browser(): http://php.net/manual/en/function.get-browser.php

A: you can check the user agent.
$isiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');


text:
Q: How to know what function to use to transform $X$ to get the best model fit in logistic regression? I have simple model $Y~X$ where $Y \sim Bin(1, p)$, so it's a case of simple logistic regression. $X$ is continuous. How to know what function to use to transform $X$ to get the best model fit?

A: There are many ways to go about this.  If you had only a single $X$ you could just use the loess nonparametric smoother with outlier detection turned off to estimate the probability that $Y=1$ given $X=x$ (e.g., see the R Hmisc package plsmo function).  In general, regression splines are great solutions because they are flexible and because they are honest about how many parameters (degrees of freedom) there are in the fit, which results in accurate confidence bands and $P$-values.  Much more detail is in my handouts available through http://biostat.mc.vanderbilt.edu/rms.


text:
Q: In LINQ to SQL how can I make it so I can add items to a collection of an entity without saving the entity first? var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();

A: The sub items will be saved along with the main item, and even identities will be set properly, if you give your DataClasses an association between these classes.
You do this by adding LoadOptions to your O/R-Designer DataClasses like this:
  MyDataContext mydc = new MyDataContext();
  System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions();
  lo.LoadWith<E1>(p => p.e2s);
  mydc.LoadOptions = lo;

This way LINQ will take care of adding the sub-items, you don't need to InsertOnSubmit every one by itself.
A side effect: upon loading the item, the subitems will be retrieved, too.

A: Well - I don't know if your initial code block would work, but I'm guessing you have to mark your new e2 as insert on submit. Thus:
var e1 = new E1();
var e2 = new e2();
e1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.insertonsubmit(e1);
context.e2s.insertonsubmit(e2);
context.submitchanges();

A: there we go, apparently when you create another ctor, you have to actually call the no arg ctor in order for the stuff in the ctor to happen


text:
Q: how to transform the values for each group into a percentage in R i have such dataset
mydata=structure(list(MDM_Key = c(10265L, 10265L, 10265L, 10265L, 1L,
1L, 1L, 1L, 1L), subgroup_id = c("08.01.2002", "08.01.2002",
"08.01.2002", "08.01.2002", "09.10.2011", "09.10.2011", "09.10.2011",
"09.10.2011", "09.10.2011"), sale_count = c(200L, 1000L, 300L,
100L, 300L, 200L, 100L, 400L, 500L), iek_base_price = c(18.85,
18.85, 14.26, 16.16, 9, 19, 9, 16, 15), iek_disc_price = c(9.425,
9.053655, 7.00879, 7.82952, 12, 16, 10, 19, 18)), class = "data.frame", row.names = c(NA,
-9L))

For each MDM_Key category, I need to convert the absolute values of the sale_count variable into a percentage value according to the condition:Replace each first value of sale_count of each category with the value 100(100%).
Then we look at how much the next value has changed from the previous one.
For example, for MDM_Key=10265 it looks like this.
MDM_Key subgroup_id sale_count  iek_base_price  iek_disc_price
10265   08.01.2002  100          18,85             9,425
10265   08.01.2002  500          18,85             9,053655
10265   08.01.2002  -700         14,26             7,00879
10265   08.01.2002  -200         16,16             7,82952

The very first value 200 is replaced by 100%, then relative to the first value, the second has increased 5 times (500%). Then the value decreased by 700%, and then by another 200%
Therefore, how to make such percentage transformations for each MDM_Key group so that the desired output is
MDM_Key subgroup_id sale_count  iek_base_price  iek_disc_price
10265   08.01.2002  100 18,85   9,425
10265   08.01.2002  500 18,85   9,053655
10265   08.01.2002  -700    14,26   7,00879
10265   08.01.2002  -200    16,16   7,82952
1   09.10.2011  100          9        12
1   09.10.2011  -100         19       16
1   09.10.2011  -100         9        10
1   09.10.2011  500          16       19
1   09.10.2011  100         15        18

thanks for your any valuable help

A: Here's a solution using the tidyverse (well dplyr one of the main packages in the tidyverse).
mydata %>%
  group_by(MDM_Key) %>%
  mutate(
    lag_sc = lag(sale_count, default = sale_count[1]),
    perc_change = (sale_count - lag_sc)/ lag_sc * 100,
  )

The perc_change column then gives you the percentage increase or decrease from the last value.
# A tibble: 9 × 7
# Groups:   MDM_Key [2]
  MDM_Key subgroup_id sale_count iek_base_price iek_disc_price lag_sc perc_change
    <int> <chr>            <int>          <dbl>          <dbl>  <int>       <dbl>
1   10265 08.01.2002         200           18.8           9.43     NA        NA
2   10265 08.01.2002        1000           18.8           9.05    200       400
3   10265 08.01.2002         300           14.3           7.01   1000       -70
4   10265 08.01.2002         100           16.2           7.83    300       -66.7
5       1 09.10.2011         300            9            12        NA        NA
6       1 09.10.2011         200           19            16       300       -33.3
7       1 09.10.2011         100            9            10       200       -50
8       1 09.10.2011         400           16            19       100       300
9       1 09.10.2011         500           15            18       400        25

The main things here are:

*

*using the lag() function which allows you to access the value at i-1 at when you are at row i.

*using the group_by function so that you can do these calculations separately in each group.


text:
Q: Was the locomotive hijacking in Back to the Future III really needed? So we see Marty eventually travel back to 1885 using the Delorean that Doc hid in the mine, and we also see it being hit in the fuel tank by an arrow, hence crippling its ability to get itself up to 88 mph.
Both Doc and Marty are then seen trying various ways of getting the car up to the required 88mph, including using horses to pull it.  Eventually they both have a lightbulb moment when presented with the locomotive and realise they might just be able to get it up to 88mph and have a chance at getting home.
However, Doc doesn't seem to ever consider something much simpler - rockets.  He has gun powder, he has the ability to create packages to make the steam engines burn hotter, so why couldn't he have built a rocket propulsion sled?
It would have been much less risky than hijacking the locomotive - a siding car could have been borrowed or purchased, and they wouldn't have been beholden to any particular schedule that the train was on...
Why did they choose to do things this way?

A: The schedule you are referring to does not only included the train, but also the fact that one of them will be killed the following Monday: as they start making arrangements, Buford is gunning for Doc, but as events occur, his target shifts to Marty. This puts them on quite a tight deadline (pun very much intended), as it gives them 3-5 days to leave.
Building a rocket propulsion sled and making/buying enough gunpowder to generate enough energy to propel the DeLorean up to 88 MPH would most likely take longer than the few (3-5) days they have left.
All in all, I think that Time was in short supply and that the train was the simplest and most reliable option available within the deadline.

A: It seems to boil down to two factors; Time + Money.
Marty and the Doc urgently need to leave town. We know from the pictures of the gravestones that either Marty or the Doc are liable to be killed in the showdown with Biff the following day. As you can see from the slightly longer 'final draft script', the doc devises a solution that will allow them to get the hell out of Dodge before then :

MARTY : Uh, Clint Clint Eastwood.
BLACK BIFF : Well, Mr. Eastwood. I'll see you out on the street Friday the 13th, front of the saloon. And you'd better be there!
MARTY : Yeah, right. When? High noon?
BLACK BIFF : Noon? I do my kilin" before breakfast 8 o'clock!

later...

DOC : Now. in order to get a steam locomotive up to 88, we need a long stretch of track on a downhill grade, which still exists in 1985.
  That's here — Carson Spur, which goes off the main line at this switch
  track and out to Carson Ravine. We'll load the DeLorean onto the
  tracks here, on Carson Spur. The train leaves the station at 7:57
  tomorrow morning...
MARTY : Whew. I'm glad it's before 8.
DOC : Indeed. So: we'll hijack — uh. borrow the train, uncouple the cars from the tender, throw the switch track, and then we'll butt
  the locomotive against the DeLorean. You'll get in the DeLorean while
  I run the steam engine, pushing the DeLorean along Carson Spur. I'll
  open up the throttle, putting her into a full highball, climb to the
  front of the locomotive, jump onto the DeLorean and get in, in time to
  reach 88 miles per hour, at which tine Mr. Fusion will kick on the
  flux capacitor, generating the traditional 1.21 jigowatts which will
  send us back to 1985.

As to why they don't build a rocket sled, the simple answer is that they're in a hurry. Renting a train is also out of the question because regardless of their success or failure their plan will destroy the train's firebox and possibly cause an explosion. That's an expensive and extremely dangerous proposal that most train companies would shy away from, even if they were offered a pile of cash (which the Doc doesn't have).
Stealing a train is both quicker and free.

A: They were looking for a direct solution that got them (or just Marty) out in a timely fashion.  I don't recall if the gravestone photo was the driver, or if it was the simple fact of Marty didn't want to grow older in the past.
I know they were trying multiple solutions.  If I remember correctly, while they were trying alternate fuels and ended up blowing out a part with high punch whiskey, Doc said he could repair the car, it would just take months.  I don't doubt he could figure out a high octane process in that amount of time.  A rocket sled would need custom parts in the same way, some way to harness a longer burning fuel for momentum... time to build, time to test, time one of them didn't have.  The train already HAD all that, and a speed potential that just needed to be pushed.  They wouldn't need to make one, just take one.

A: One possibility is that the people who wrote the movie's script either did not consider it, or decided it was either not feasible or not dramatic enough. My guess, though, is that it has to do with consistency of speed. In the various iterations of Delorean impulse, the constant factor has been getting up to 88 MPH and then maintaining that speed for a few seconds while the transport process takes hold. Steam engines and internal combustion engines (and presumably fusion engines) are relatively easy to finetune to stay at a consistent speed. Trying to adjust the fuel of a rocket, and to do so without blowing yourself up, is much trickier.

A: As Richard said I think the main issue was time, but I thought I'd add some calculations on how much gunpowder would actually be needed. The Tsiolkovsky rocket equation tells us that the change in velocity of the final payload is equal to the "effective exhaust velocity" (around 800 meters/second for a "black powder" rocket according to this) times the natural logarithm of the ratio of initial mass (including fuel) to final payload mass (with all fuel used up). Rearranging this equation, the ratio of initial to final mass would be e^(change in velocity / effective exhaust velocity). So with a change in velocity of 88 mph = 39 m/s, the ratio is e^(39/800) = 1.05, meaning the fuel must have a mass equal to 0.05 times the mass of the payload. A DeLorean with a full tank of gas has a mass of 1233 kg according to this, and the gas should weigh around 80 lb = 36 kg so let's say without gas it would be about 1200 kg. That means you'd need about 5% of that mass in gunpowder, or 60 kg (130 pounds). This might well be more gunpowder than local stores would actually stock at any given time, a poster here says that with a muzzleloader you can get around 70 shots per pound of gunpowder, enough for a fair number of hunting expeditions. Although this article indicates that the 36 barrels of gunpowder used by Guy Fawkes added up to about 2500 kg of gunpowder, or about 70 kg per barrel, so if there were some similar-sized barrels of the stuff around then it might be enough (not sure if those barrels were just used as supplies for cannons in the navy or if regular gun stores would have stocked them).


text:
Q: Connecting to a MySQL database using PhoneGap, AJAX, and JQuery Mobile I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:

*

*On our html file, we have a

^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?

*Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {

    // cache this page for later use (inside the AJAX function)
    var $this = $(this);

    // make an AJAX call to your PHP script
    $.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {

        // create a variable to hold the parsed output from the server
        var output = [];

        // if the PHP script returned a success
        if (response.status == 'success') {

            // iterate through the response rows
            for (var key in response.items) {

                 // add each response row to the output variable
                 output.push('
' + response.items[key] + '
');
            }

        // if the PHP script returned an error
        } else {

            // output an error message
            output.push('
No Data Found
');
        }

        // append the output to the `data-role="content"` div on this page as a
        // listview and trigger the `create` event on its parent to style the
        // listview
        $this.children('[data-role="content"]').append('
' + output.join('') + '
').trigger('create');
    });
});

Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php

//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);

//include your database connection code
// include_once('database-connection.php');

//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());

//create an output array
$output = array();

//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {

    //iterate through the results of your query
    while ($row = mysql_fetch_assoc($query)) {

        //add the results of your query to the output variable
        $output[] = $row;
    }

    //send your output to the browser encoded in the JSON format
    echo json_encode(array('status' => 'success', 'items' => $output));

} else {

    //if no records were found in the database then output an error message encoded in the JSON format
    echo json_encode(array('status' => 'error', 'items' => $output));
}
?>

Yet nothing is showing here. What do we do from here?

A: First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)


text:
Q: Elaboration: Method overloading is a static/compile-time binding but not polymorphism. Is it correct to correlate static binding with polymorphism? Before I ask my question, let me to explain my understanding and opinion.

*

*By only Overriding we can't achieve polymorphism unless there is upcasting. And as it can only seen at runtime people might have named it as Run time ploymorphism. (I have no objection to call polymorphism as Run Time Polymorphism)

*I have objection to call method overloading as compile time polymorphism or polymorphism.

I agree that method overloading is static binding (compile time binding), but I can't see polymorphism in that.
According to the javadoc, there is only polymorphism. There is no compile time or run time polymorphism.
According to javadoc in a section called Defining Methods, it explains Overloading of Methods. But there is nothing about compile time polymorphism.
According to me:
If you put polymorphism in to category of Run time polymorphism, you can only see "compile time polymorphism" when you change your JDK version:
If you switch from a higher JDK version higher to a lower one, you will start seeing compilation errors. The same code behaving differently during compilation time, eg: lambda expression, diamond operator, string in switch case, generics etc.
Let me elaborate my opinion, my prediction about how run time polymorphism and compile time polymorphism came to blogs/tutorials:
Conversation1

Developer 1: Hey I read about polymorphism today. If you do coding to interface, you can achieve polymorphism. writing codes not tightly coupling to a class but instead writing it to interface by making loose coupling, calling a superclass method or interface method actually invokes method of subclass depending on instance passed.
Developer 2: Sorry, I didn't get you.
Developer 1: It's simple at run time which object instance you will pass, that instance method will be executed.
Developer 2: Ohh! Run Time. I got it.
Developer 1: Yes same piece of code, but at Run Time passed instances are different.
Developer 2: **Run Time! Okay, I got it.

Conversation2

Developer 2: Hey yesterday I've met Developer1, he was telling about some run-time polymorphism. By overriding methods in a sub-class we can achieve it.
Developer 3: Run time polymorphism by overriding methods? Then what is oveloading? Compile time polymorphism?
Developer 2: How do you say overloading as compile time polymorphism?
Developer 3: Because it is decided at compile time only.
Developer 2: Silent!

Polymorphism and coding to interface best example is java.sql:
java.sql.Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
java.sql.Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery(sql);

The same piece of code behaves differently based on the Driver registered. This means, if we register the Mysql driver, due to polymorphism this code executes methods of mysql instances. I.e. it executes overridden methods. If you register the Oracle driver, it works for Oracle, and so on.
Above we found same code behaving differently.
Now can anyone show me same code behaving differently in compile time. Or in other words show me add(3,4) method bounded to different methods (other signatured methods) during compile time?
According to javadoc,

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures.

The method will be executed depending on signature matched. Having same name for methods does not mean there is a polymorphism, because calling methods signature is different:
Queestion1: If you won't change calling method signature will it call different method other than method for which signature has matched? In any condition will it behave differently?
Let's look at Method overloading:
public void add(int a, int b)
{
    System.out.println(a+b);
}

public void add(int a, int b, int c)
{
    System.out.println(a+b+c);
}

public static void main(String[] args)
{
    add(3,4);
    add(3,4,5);
}

Question 1: If method overloading is polymorphism, Which piece of code behaving differently in above block of code? Where is polymorphism here?
Question 2: Method invocation add(3,4); on what scenario it shows ploymorphism, unless it is modified to add(3,4,5)?

EDIT
@FutureVisitor since this thread found no answers in favor of method overloading as a type of polymorphism(Even after a month of question being asked), without any justification accepting answer in favor of Method overloading is not a polymorphism, if any answer points problem in my argument of method overloading is not polymorphism will be accepted and supported their views.

A: In the Java world, polymorphism means polymorphism between classes. I.e. refering possibly multiple child classes with their common parent. In Java, there is no polymorphism between methods.
void add(int a, int b) and void add(int a, int b, int c) are entirely different methods in the Java syntax. It shouldn't be so - for example, in C++, you can cast them to each other -, but it is so in Java.
The key concept to understand here is the method signature. The method signature defines in a language, what identifies the induvidual methods. (For example, beside a void add(int a, int b);, you simply can't declare an int add(int a, int b); method - the return value is not a part of the method signature in Java, thus the compiler would interpret it as a method re-definition.)

A: People say

*

*overriding is run time polymorphism and

*overloading is compile time polymorphism.
Both are wrong.
Only Overriding is not polymorphism. But overriding helps to achieve polymorphism. If there is no upcasting you can't achieve polymorphism.
Overloading is a concept where method-name along with argument signature is used to bind method call to method body and it can be predicted during compile time only. But this is nowhere related to polymorphism. There is NO behavioral change that can be found in the case of method overloading. Either you compile today or compile after one year behavioral change can only be found if you change calling method signature i.e, only if you modify code to say add(3,4); to add(3,4,5); and hence method overloading is not polymorphism.


text:
Q: Having issue with Email personalize with %%First Name%% I have created an email template on Salesforce Marketing Cloud and I want to add %%FirstName%% personalization string to it. However, I haven't been able to do so after trying different syntaxes. Below is my current syntax:
 %%[
IF Empty(@First Name) OR @First Name == "Unknown" THEN
 set @FirstName = "colleague and friend of NALRC"
ENDIF
]%%

Dear %%=v(@FirstName)=%%,

I would appreciate any help.

A: I believe the issue is with the space in the Data Extension column name. I try to avoid spaces in column names as it inevitably causes me problems somewhere.
In this case I used AttributeValue to retrieve the value from the row and UpperCased the Unknown just to be extra safe in case of casing issues.
%%[
var @FirstName

IF Empty(AttributeValue("First Name")) OR Uppercase(AttributeValue("First Name")) == "UNKNOWN"
THEN
SET @FirstName = "colleague and friend of NALRC"
ELSE
SET @FirstName = AttributeValue("First Name")
ENDIF

]%%

Dear %%=v(@FirstName)=%%

A: It could be good practice to use underscores instead of spaces in column names for your target audience. I hope the code below helps in some way.
%%[
VAR @FirstName
SET @FirstName = Trim(AttributeValue("First Name"))

IF EMPTY(@FirstName) OR @FirstName == "Unknown" THEN
    SET @FirstName = "colleage and friend of NALRC"
ENDIF
]%%
Dear %%=v(@FirstName)=%%,


text:
Q: Monkey patching in new and already imported modules I have 3 files in the same directory:
# foo.py (my source code, I can make changes here)
def patched_f_bar():
    print('patched_f_bar')
import bar
import baz
bar.f_bar = patched_f_bar
bar.f_bar()
baz.f_baz()

# baz.py (library, I can't change this)
from bar import f_bar
def f_baz():
    print('from baz:')
    f_bar()
    print('from baz.')

# bar.py (library, I can't change this)
def f_bar():
    print("f_bar")

I am calling python foo.py with the hope to replace function f_bar defined in bar.py with patched_f_bar. Unfortunately, it doesn't work for calls from other modules.
patched_f_bar
from baz:
f_bar          # expected: patched_f_bar
from baz.

This issue can be fixed by reordering import baz and bar.f_bar = patched_f_bar in foo.py:
patched_f_bar
from baz:
patched_f_bar      # as expected
from baz.

I am looking for a general solution to do such monkey patching without relying on the order of imports. After patching, I expect all calls from any module to be redirected to the new function.

A: All works as expected. Let us see what happens under the hood:
Nothing special in foo for the beginning of your code:
# foo.py (my source code, I can make changes here)
def patched_f_bar():
    print('patched_f_bar')
import bar
import baz

Now at baz import time
# baz.py (library, I can't change this)
from bar import f_bar  # here is the point
def f_baz():
    print('from baz:')
    f_bar()
    print('from baz.')

You do not simply import the bar module. from bar import f_bar actually creates a variable in baz pointing to the current f_bar function of bar
Let us go on:
bar.f_bar = patched_f_bar    # patches f_bar IN BAR MODULE
bar.f_bar()                  # calls the patched function
baz.f_baz()

but baz.f_baz will still use the cached version, meaning here the original function.
You must patch the function in baz module as well, because it contains a from ... import ...:
...
bar.f_bar = patched_f_bar
baz.f_bar = patched_f_bar
bar.f_bar()
baz.f_baz()   # it now calls the patched version!

The bad news is that it may be hard to guess the import model used by a third party module. If it used:
from bar import f_bar as bar_f_bar

you would have to patch it that way:
baz.bar_f_bar = patched_f_bar

because the rule is that all references in the third party module must point directly (like above) or indirectly (if it just imported the bar module) to your patched function.