text:
Q: What is the variance of java .class files across different compilers, versions, dependencies? Hi I was wondering how much Java class files change across different compilers. So how much do the actual bytes change if a .java files is compiled by say a Sun JDK 1.4, 1.5 1.6 or even IBM JDK. I know that class files can be different with regards to debug information and obfuscation, but let's assume for the question that those options are the same, so debug information included, no obfuscation. If I ran a MD5 or SHA-1 has on a .class file that was compiled by JDK 1.4 would the Hash be different if I compiled it in JDK 1.5 but targeting 1.4 what when targeting JDK 1.5?
Also related to that, does a binary of a class file change when different dependencies are used, or asked differently can the binary of a class file change based on it's dependencies ?
And last but not least are there programmatic ways to analyse the metadata of a .class file in order to identify compiler version and or switches that were used when compiling it ?

A: The Java compilers have quite some freedom when creating classes and bytecode from source. They can reorder the methods, reorder the constant pool (with class names, method names and strings - this results in different method byte code, too) and reorder the actual byte code commands, as long as the result when executing them is the same.
So, using MD5 or similar hashes to prove that two class files came from the same source is not really sensible.

A: For the format of class files, see http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html
Yes, class files can and usually do change depending on which specific compiler is used to build them. There are many compiler implementation details which will result into different bytecode -- e.g. listing dependencies in different orders in the interfaces[] or fields[] arrays. Plus compilers are free to use different optimizations.
Adding or removing an "import" statement does not necessarily change the class file -- but using a class in one package instead of another certainly would. Not sure if this answers your 2nd question.
I don't believe compilers leave their identity in class files. Any such analysis would need to be indirect and most likely heuristic (in the lines of telling the author of a book by its style) -- unless you've got the source code and can compile with each compiler and compare.

A: Paŭlo has answered your question about hashing well. As for your other question:

Also related to that, does a binary of a class file change when different dependencies are used, or asked differently can the binary of a class file change based on it's dependencies ?

Yes. The class file contains signatures for all methods invoked, and these could have changed. Consider:
void test() {
    Foo.bar(1,2);
}

where Foo in version 1 is defined by:
class Foo {
    public static void bar(int x, int y) {
        // do something
    }
}

and in version 2 by:
class Foo {
    public static <T> T bar(T... ts) {
        // do something
    }
}


text:
Q: Clojure gen-class this keyword Is it possible to refer to Java's 'this' keyword from within a gen-class method?
I am trying to implement daredesm's answer here, in Clojure. However, when I try to use 'this' in the run function, I get "java.lang.RuntimeException: Unable to resolve symbol: this in this context."
(gen-class
  :name ClipboardListener
  :extends java.lang.Thread
  :implements [java.awt.datatransfer.ClipboardOwner]
  :prefix ClipboardListener-
  :methods [[takeOwnership [Transferable] void]])

(def systemClipboard (.getSystemClipboard (java.awt.Toolkit/getDefaultToolkit)))

(defn ClipboardListener-run []
  (let [transferable (.getContents systemClipboard this)]
    (.takeOwnership transferable)))

(defn ClipboardListener-lostOwnership [clipboard trasferable] (prn "hit lost"))
(defn ClipboardListener-takeOwnership [transferable] (prn "hit take"))
(defn processClipboard [transferable clipboard] (prn "hit process"))

Note: This is my first time generating Java classes in Clojure, so any general feedback/resources is greatly appreciated.

A: Instance methods can take an implicit 'self' arg- as the first argument. So to take your example:
(defn ClipboardListener-run [this]
  (let [transferable (.getContents systemClipboard this)]
    (.takeOwnership transferable)))

Note the this argument :)
Same goes for any instance method, e.g:
(defn ClipboardListener-toString [this]
  "override Object#toString with something cool")

Have a look at this (no pun intended) for more info on gen-class.
Also consider reify for cases like Runnable, Callable, e.t.c where you just need to implement a small-ish interface.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apex cron job command to schedule an apex job to run every 4 hours daily I have a requirement where i need to run an apex batch job every 4 hours daily monday to friday and all months in a year. I looked at the apex cron job documentation to be setup using code snippets in execute anonymous window. But it is not very clear. I am not sure whether i can do this through the gui but i would like to atleast do this through the system.schedule at run time is fine. Could you guys give me exact syntax for the cron please?

A: use this site to make cron for every scenario.
cronmaker

A: If you use the following chron string for your scheduled job, it will run every 4 hours (at set times) Monday through Friday.
apexScheduledJob j = new apexScheduledJob ();
String sch = '0 0 0,4,8,12,16,20 ? * MON-FRI';
System.schedule('My Job', sch, j);

If you wanted it to run every day, you would just change it to
String sch = '0 0 0,4,8,12,16,20 ? * *';


text:
Q: How to access elements inside an array of objects in Javascript for a movieapp prototype I've only shown the JS part of my code because the .html part only has one input box with name="my-input" inside a form.
What happens in this function is, if I enter 'Adventure' in my input box it gives me Edge of Tomorrow as the title of the movie and if I enter Romantic it gives me Lalaland likewise. Now what I want is,  shown in the movieList1() function i.e. I have two objects with same genre 'Adventure' for example, then I would want both the movie title, 'Edge of Tomorrow' and 'Dark Force' to be shown in my empty list with id 'here'. I want title of all the movies to be shown if the genre is similar but I'm able to only get one movie title at a time that is shown. I'm new to JS and object and array of objects looks a little confusing. Any help would be very much appreciated.
 function movieList(){
 //This function is called in an 'onkeyup' event inside the input box.
 var x = document.forms["my-form"]["my-input"].value; // x has what the user enters inside the
 inputbox.
 const objList = [{
       title:'Edge of Tommorow',
       Genre: 'Adventure',
 },
 {
    title:'DarkForce',
    Genre: 'Tactical',
 },
 {
    title:'LalaLand',
    Genre:'Romantic'

 }];
  objList.forEach((ele,index) => {
 if(ele.Genre=='Adventure' && x==ele.Genre) {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans; // 'here' has the id of an empty

 where
   the title is shown.

 }
 else if(ele.Genre=='Tactical' && x==ele.Genre)
 {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans;
 }
 else if(ele.Genre=='Romantic' && x==ele.Genre)
 {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans;
 }
 else if(x=='')
 {
    document.getElementById('here').innerHTML='';
 }

 });
 }

 function movieList1(){
 //This function is called in an 'onkeyup' event inside the input box.
 var x = document.forms["my-form"]["my-input"].value; // x has what the user enters inside the input
 box.
 const objList = [{
       title:'Edge of Tommorow',
       Genre: 'Adventure',
 },
 {
    title:'DarkForce',
    Genre: 'Tactical, Adventure',
 },
 {
    title:'LalaLand',
    Genre:'Romantic,Tactical'

 }];
 objList.forEach((ele,index) => {
 if(ele.Genre=='Adventure' && x==ele.Genre) {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans; // 'here' has the id of an empty

 where
 the title is shown.

 }
 else if(ele.Genre=='Tactical' && x==ele.Genre)
 {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans;
 }
 else if(ele.Genre=='Romantic' && x==ele.Genre)
 {
    var ans = ele.title;
    document.getElementById('here').innerHTML = ans;
 }
 else if(x=='')
 {
    document.getElementById('here').innerHTML='';
 }

 });
 }

A: I'm guessing this is what you want to do.
const objList = [{
    title: 'Edge of Tommorow',
    Genre: 'Adventure',
},
{
    title: 'DarkForce',
    Genre: 'Tactical',
},
{
    title: 'LalaLand',
    Genre: 'Adventure'

}];

let Gen = "Adventure";  // suppose this is from your input
let temp = [];   // create an array to store all similar genre title

objList.forEach(x => {
    if (x.Genre == Gen) {
        temp.push(x.title);
    }
})
console.log(temp);

Output:
[ 'Edge of Tommorow', 'LalaLand' ]

you can also store objects in the temp array.

A: Thinking you are expecting the output like:: (Method movieList1)

*

*for inputGenre=Tactical output will be DarkForce,LalaLand

*for inputGenre=Adventure output will be Edge of Tommorow,DarkForce

document.getElementById("txtGenre").addEventListener("keyup",searchMovies)

function searchMovies(){
let inputGenre=document.getElementById("txtGenre").value;
 const objList = [{
       title:'Edge of Tommorow',
       Genre: 'Adventure',
 },
 {
    title:'DarkForce',
    Genre: 'Tactical, Adventure',
 },
 {
    title:'LalaLand',
    Genre:'Romantic,Tactical'

 }];

let filterdData =objList.filter(r=>r.Genre.includes(inputGenre));

console.log(filterdData);
document.getElementById("result").innerHTML=filterdData.map(r=>r.Genre).join(",");
}
#result{
background-color:green;
}
Genre input: <input type="text" id="txtGenre" onClick="searchMovies"/>

Output Movies List:

A: There reason you are getting only one movie name is, you are re-writing the HTML again with the latest movie that matched the criteria each time forEach runs. You need to adjust your variables and how you assign your result to HTML.
Lets keep ans out of the loop, so it doesn't get overwrittern. And write to html at the end, after you have filtered all per your input.
var ans = [];
objList.forEach((ele,index) => {
 if(ele.Genre=='Adventure' && x==ele.Genre) {
    ans.push(ele.title);
 } else if(ele.Genre=='Tactical' && x==ele.Genre) {
    ans.push(ele.title);
 } else if(ele.Genre=='Romantic' && x==ele.Genre) {
    ans.push(ele.title);
 }
 // We dont need this
 // else if(x=='') {
 //    document.getElementById('here').innerHTML='';
 // }
 });
document.getElementById('here').innerHTML = ans.join(', ');

At last, you join the answer using the in-built array function.
Now if you notice, your if statements are pretty much the same except for the hardcoded genre. So you could further refactor it.
var ans = [];
var genre = 'Adventure'; // assign your genre from input box here.
objList.forEach((ele,index) => {
  if (ele.Genre == genre && x==ele.Genre) {
    ans.push(ele.title);
  }
});
document.getElementById('here').innerHTML = ans.join(', ');

Now you would have a single if statement which is easy to understand and modify.


text:
Q: Entity Framework, Computed Entity Field Is it possible to include a computed field in an EF entity? Example, lets say I have a shop selling products, and the products are grouped into categories.
When the list of categories is displayed for editing to the administrator of the shop I wish to list the number of products in each category as part of the list.
In NHibernate I would use a formula e.g.
<property name="Products" formula="dbo.Category_NumProducts(id)" />

I can't work out if something similar is possible for EF. I know I could make a category view and map this to a second entity but that seems wrong as its almost a complete duplication.
EDIT: If this isn't possible in EF, then what is the best way to accomplish this?

A: Unfortunately if your Category table doesn't have this as computed column you will not be able to map it without creating second entity - it leads to database view, defining query in EDMX or perhaps Query view in EDMX (but Query view may not work because you require aggregate function to be computed).
Edit:
IMHO the simplest solution (and also the best) is simply creating a ViewModel (some non mapped class) and use projection in Linq query:
var query = from c in context.Categories
            where ...
            select new CategoryView {
                Id = c.Id,
                Name = c.Name,
                ...
                Products = c.Products.Count()
            };


text:
Q: Qt - How to add multiple QGroupBox to a QTabWidget? I'm going to create multiple tabs with multiple group box inside each tab like below.
 _______ ______
|              |             |
|  Tab1    |  Tab2   |
|              |______|_________________
|
|    Group Box 1
|   ------------------------------------
|
|
|    Group Box 2
|   ------------------------------------
How can I do this with QTabWidget and QGroupBox?
Edit
The code that I use for one group box in tab widget are:
QGroupbox * testGB = new QGroupbox("Group Box 1");
...
// create a test layout and add some widget to it
...
testGB.setLayout(testLayout);

QTabWidget * tab = new QTabWidget this;
tab->addTab(testGB, tr("Tab1"));

But I don't know how to append another group box to Tab1

A: Maybe here's something useful for you.
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QVBoxLayout* lay=new QVBoxLayout;
    ui->centralWidget->setLayout(lay);
    QTabWidget* tab = new QTabWidget(this);
    lay->addWidget(tab);

    QWidget* w1=new QWidget(this);
    QVBoxLayout* lay1=new QVBoxLayout;
    lay1->setSizeConstraint(QLayout::SetMaximumSize);
    w1->setLayout(lay1);
    tab->addTab(w1,"tab1");
    QGroupBox* gb1=new QGroupBox("Group 1-1");
    gb1->setMaximumSize(250,100);
    gb1->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred);
    lay1->addWidget(gb1);
    QGroupBox* gb2=new QGroupBox("Group 1-2");
    gb2->setMaximumSize(250,100);
    gb2->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred);
    lay1->addWidget(gb2);

    QWidget* w2=new QWidget(this);
    QVBoxLayout* lay2=new QVBoxLayout;
    lay2->setSizeConstraint(QLayout::SetMaximumSize);
    w2->setLayout(lay2);
    tab->addTab(w2,"tab2");
    QGroupBox* gb3=new QGroupBox("Group 2-1");
    gb3->setMaximumSize(250,100);
    gb3->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
    lay2->addWidget(gb3);
    QGroupBox* gb4=new QGroupBox("Group 2-2");
    gb4->setMaximumSize(250,100);
    gb4->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
    lay2->addWidget(gb4);
}


text:
Q: Protecting Code in an Excel Workbook? I want to produce an Excel workbook that will contain proprietary formulas and other intellectual property. I will most likely produce this workbook in Visual Studio 2010 with C#.
How protected is the code within these projects? Do the same problems with reflection in C# still apply to these workbook projects? If so, are there obfuscation tools specifically for these types of workbooks?
To add to this question - what about good 'ole VBA? Is there a way to protect that code too if we were to go the VBA route?

A: If you Save the workbook with a password to open as an XLSB (Note this NOT Protect Workbook Structure etc) the workbook is encrypted with reasonably secure encryption (stronger in Excel 2013). But the user has to supply a password to open it, which is not suitable for some useage scenarios.
All other forms of Excel protection are relatively weak.Securing code in Excel is best done using a C++ XLL. Next best is a VB6 DLL (but this is now a dead technology and won't work in 64-bit Excel)  Next best is obfuscated .NET, but you really need to be using the kind of .NET XLL interface provided by Addin Express or XL DNA to avoid the poor performance characteristics of .NET Interop and VSTO.

A: As other answers have suggested, VBA security in Excel 2003 (.xls) is flawed; a password is only a little annoyance, most often than not for the developper himself. IMHO you're absolutely better off with VSTO, even if VBA security in Excel 2007+ (.xlsx) is much better, not to mention the VBA IDE which hasn't seen improvements in centuries (although no so true with the right VBE add-in...).
A solution could be to write the sensible code in a separate library which your VSTO project calls; instead of intricate formulas you could expose functions which would appear as "black boxes" (i.e. an abstraction of the formula's functionality); how it's implemented is just not available to anyone without the source code), and without the dll the workbook couldn't be calculated (would be #NAME? all over the place).
For example, instead of =some proprietary formula returning a Smurf, users would see =Smurf(SomeTableColumnName, SomeRangeName, SomeRangeReference, SomeCellReference). Of course this comes at a performance cost, so I would only do this for stuff that's really important to protect.
I think a user that manages to extract the proprietary formulas from such an on-the-side library, deserves to leave with them - between that and Alt+F11, there's quite a step; the proprietary code is as "protected" as any other .net assembly is.
UPDATE
Still without using any 3rd-party libraries, if the proprietary code does not need Excel interoperability, a perhaps better solution could be to create the function in VBA (i.e. leave the Excel interop part within Excel) and only pass primitive types (VBA Integer => .net Int16; VBA Long => .net Int32, strings, etc.) to a COM-visible library which doesn't even need to use Excel interop; it will be COM interop instead of Excel interop and the performance hit would be significantly reduced, though still present (it remains .net managed code "talking" to unmanaged COM).
The VBA code's responsibility would be to read and write to/from the worksheets, and the COM-visible library's role would be to implement the calculations to be made out of the values passed by the VBA code; of course the VBA code would be easily accessible to the user (Alt+F11), but again they couldn't access the actual calculation implementation. And then the VBA code could be password-protected, and the calculation results without the DLL would be either 0's or #VALUE!, depending on how the VBA code is implemented.
The key is to leave Excel-specifics in Excel and have the .net library pick up where it can without referencing Excel interop assemblies - for example, the VBA function would take a cell reference, grab its value (perhaps validate it) and pass it to the .net assembly, which would return another primitive type that VBA would return to Excel.
Another plus is that the library code with the proprietary calculations could be reused, if you ever were to "convert" the Excel workbook into, say, a Web application.

A: For future reference: here are 2 new innovative products to help solve your exact problem:
1) https://HiveLink.io: - Using HiveLink you can create a "lightweight" version of your spreadsheet, which you give to your users but it doesn't contain any of your sensitive VBA or calculation formulas. You strip out the intellectual property from the lightweight spreadsheet, and send invitations for your users to download this spreadsheet. When your users enter their input data, HiveLink delivers the data to your original spreadsheet to process the data and then returns the results back to the user automatically.
The good thing about this approach is that it isn't possible to reverse engineer with .NET reflection, or even assembly code - because you completely remove the code from their computer. This is the safest option, and great if your model suits the input/output roundtrip design - not so great if you require client-side interactive code that happens instantly. If you do require fast client-side interactive code, typically this is less sensitive, and you can use workbook protection, or even compile the basic code using something like DoneEx Excel Compiler, and have protection using a combination of Excel Compiler and HiveLink.
2) http://FCell.io: This allows you to build .NET code directly into the spreadsheet. It even comes with a code editor window in the spreadsheet, kinda like replacing the existing VBA code editor with a .NET code editor. The object model in the code editor is a little less comprehensive than the normal one, but you can also create Task Panes and embed them into the workbook for distribution so that your users don't even need to install anything! I'm not sure how safe your code is being embedded into the workbook, but I'm 100% sure people can get to your code if it's important enough to them.
Further comments Re Mat's Mug helpful response:
Re: Performance cost - actually you might notice significant performance gains by implementing things in .NET, especially if you harness multi-threading, which Excel doesn't do at all with UDFs or macros. I've seen gains of 100x re-writing some of my clients' code in .NET libraries (for heavy processing calculations). You might also find it much easier to maintain and improve .NET code than VBA. I have done a lot of conversion of VBA code and functionality to .NET code and have never had a noticeable performance issue with it when done properly.
Re: Users deserving to get access by reflecting .NET libraries?? - I totally disagree with this. It is extremely easy to get access to .NET code using reflection, maybe even easier than cracking Excel's weak passwords. If you really have sensitive calculations you want to protect then it's best to either use something like HiveLink to completely remove the possibility of reverse engineering, or to use obfuscation to make it much harder/extremely annoying. For obfuscation I use CryptoObfuscator($) and Dotfuscator($$$). I wouldn't share my clients' sensitive model VBA code in .NET libraries for excel without this. I also sometimes use CryptoLicensing to allow them to control who can access their DLL functionality by creating licenses for each user.
Re: Leaving VBA code responsible for writing/reading to/from the worksheet - I'm also highly against this. I would recommend leaving as little code in VBA as possible and doing a high level call to .NET, leaving the reading/writing to the .NET plugin. Use named ranged in your worksheet to identify your inputs/outputs and data locations, and then define those named ranges as constants in your .NET library. In your library you can very easily read from ranges and write to ranges. It is much cleaner and easier to maintain this way.
When building any extension library for Excel where you want to call external functionality from VBA - you have to make your library COM Visible. There are a few ways to do this: I highly recommend avoiding having to register your library with the windows COM list using regsvr32 - avoid it at all costs!
The best way to register your library is to load it using ExcelDna, which allows you to load your DLL dynamically every time you launch Excel, without having to permanently define each class with a COM interface in the registry (nightmare when you update versions). You end up creating an XLL file, which can have the DLL packed inside - and you can tell Excel to load the XLL each time it launches by putting a key in the registry. The benefit is that this doesn't require you to store the whole COM interface in the registry, so it is very easy to manage new versions.
Therefore, your VBA code might be something like:
Sub Button_Click()
    Call ThisWorkbook.EnsureLibraryInitialized
    Call ThisWorkbook.MyLibrary.ReadRangesAndWriteResults(someInputParam)
End Sub

Note that VBA would look for this method ReadRangesAndWriteResults at run time. If you expose the method for compile time in VBA then you'd have to register its COM interface signature in the registry - worth avoiding at all costs!!!
ThisWorkbook module:
Public MyLibrary as Object

public sub Workbook_Open()
    EnsureLibraryInitialized
End Sub

public Sub EnsureLibraryInitialized()
    Dim addin As COMAddIn
    If MyLibrary is Nothing Then
        For Each addin In Application.COMAddIns
            If InStr(addin.Description, "MyLibrary.COMHelper") Then
                If addin.object Is Nothing Then
                    'complain it can't connect to library, tell user to reinstall it
                Else
                    Set MyLibrary = addin.object
                Exit For
            End If
        Next
    End if
End Sub

Re: Excel Interop and .NET libraries - Good points Mat's Mug, this can be a nightmare when using the normal Microsoft.Office.Interop.Excel. Because you are accessing native code from a managed .NET environment you have to make sure your .NET COM wrapper objects get cleaned up properly or you will get hanging/zombie processes of Excel even after you close Excel and it looks like it has disappeared/closed (look in Task Manager, they might still be there!)
The best way I've found to handle this is to use NetOffice, which is basically a clone of the Excel interop model but created to safely manage all of these problems for you. Best to also be aware of good safe handling of COM objects, eg here and here.
Good luck!


text:
Q: Auto-login user to TTY on boot, and then auto-run command within GNU screen Ubuntu 14.04.5 LTS
Desired functionality:
Remote Ubuntu server boots and automatically starts an ongoing process as a specified user. I can then log in remotely at a later time and view the past and current screen output of the ongoing process.
Current plan:
Automated steps:

*

*User "ubuntu" is logged in automatically to a terminal (TTY) on boot:
"sudo nano /etc/init/tty1.conf"

Change: exec /sbin/getty -8 38400 tty1

To: exec /sbin/getty --autologin ubuntu -8 38400 tty1

*User "ubuntu" runs GNU screen:
screen -d -m -S screenname

*User "ubuntu" runs the ongoing process within GNU screen:
screen -S screenname -p 0 -X stuff "command^M"

Manual steps at later time:

*I log in remotely as user "ubuntu" in another terminal (TTY).

*I re-attach to the GNU screen session started in step 2:
screen -r

*I am able to view past and current output of the process started in step 3.

Questions:

*

*Is this the most effective way to achieve the desired outcome?

*How can the commands in step 2 & 3 be automated?

*How can the commands in step 2 & 3 not activate when I log in manually in step 4?

A: Answers (to my own questions)

*

*Is this the most effective way to achieve the desired outcome?
I am still unsure if the solutions below are the most effective, but I can confirm that it at least works on the stated version on Ubuntu.

*How can the commands in step 2 & 3 be automated?

*How can the commands in step 2 & 3 not activate when I log in manually in step 4?
Step one
I put the following at the bottom of the .profile file in the user directory of the user being automatically logged in during step 1 above (/home/ubuntu/.profile):
pgrep processname || /home/ubuntu/processscript.sh

When the user is automatically logged in, this command will execute automatically because it is in .profile. The first part of the command (before the "||" checks if 'processname' is already running. If not, it will execute the second part of the command (after the "||") i.e. "processscript.sh" ... If 'processname' is already running, it won't.
This check was necessary as the process I wanted to run could not have multiple instances running at the same time. In addition, it solves the problem of process running a second time when I log in manually later.

Step two
Create a shell script file called "processscript.sh" with the following contents:
#!/bin/bash
screen -d -m -S screenname &&
screen -S screenname -p 0 -X stuff "/home/ubuntu/command.sh^M"

Ensure "processscript.sh" is in the /home/ubuntu directory, and that it is executable with the command:
chmod 744 processscript.sh

The above shell script creates a screen instance with the name "screenname", and if completed successfully, it stuffs the commandline of that screen instance with the command "command.sh" with a carriage return (which is what the "^M" at the end does).
Step three
In the previous step, I encountered some problems when stuffing a command with attributes to the screen commandline (I think some character escaping was required). To resolve this simply, I added the full command with attributes to a shell script and used that instead. Therefore, create another shell script (as above) called "command.sh" and add the full command in there.


text:
Q: Cypress: Error: Getting ESOCKETTIMEDOUT when using cy.visit() Brand new project. I am simply trying to access adobe.com but getting a ESOCKETTIMEDOUT error. Given this is a new project, I doubt anything is wrong with the code. I am on MACOS 12.6.1 Monterey with no firewall on. Any settings/changes I need to make?
CypressError
cy.visit() failed trying to load:

https://www.adobe.com/

We attempted to make an http request to this URL but the request failed without a response.

We received this error at the network level:

> Error: ESOCKETTIMEDOUT

Common situations why this would fail:
- you don't have internet access
- you forgot to run / boot your web server
- your web server isn't accessible
- you have weird network configuration settings on your computer
cypress/e2e/spec.cy.js:3:8
  1 | describe('empty spec', () => {
  2 |   it('passes', () => {
> 3 |     cy.visit('https://www.adobe.com')
    |        ^
  4 |   })
  5 | })

A: It was answered here: Cypress, cy.visit() failed trying to load ESOCKETTIMEDOUT
Just add the object { headers: { "Accept-Encoding": "gzip, deflate" } } as the second argument of cy.visit (but no need to modify Cypress config file in my case)


text:
Q: RDS Postgres Free Storage Space is fluctuating from 200GB to 0 hourly As you can see, of the 500GB, we are using ~300GB and thus there is about 200GB that should be free. However, since updating from Postgres 9.4 to 9.5, we are seeing this crazy fluctuation in free storage. It is using the default parameter group as well.
Is there any way to bring it back to stable? It seems to be causing some queries to fail, too.
Engine version: 9.5.21
Instance class: db.t2.large
CPU: 2
RAM: 8 GB
Storage: 500 GiB

Some more stats:


text:
Q: How to implement lead nurture in Marketing Cloud & avoid duplicates? We are migrating from Salesforce Pardot to Marketing Cloud . Currently in Pardot they have lead nurture form where a user sign ups in form and when they qualify , signed up user get converted as lead .
I do not want to create a lead on smart capture form submission (where i can check if lead exists or not using   RetrieveSalesforceObjects  & CreateSalesforceObject  ) instead I want to create Lead only if they nurture & Qualify as a lead . Because not all records who signs up the form are leads since some are scam as well.
How to implement this scenario in Marketing cloud ?
We are re-building the Pardot forms(newsletter & other campaign forms)  in Marketing Cloud cloud pages & when customer signs up in the form , send them an email  . When the customer qualifies as lead based on some criteria, create a lead record and sync it up in salesforce ?
So I have created a smart capture form and sending email to them .
The problem is occurring when I try to create a lead record if it gets qualified
For the same email address 2 records are getting added to contacts .

*

*When user A (nto@gmail.com) signs up via smart form and email needs to sent, so record is getting added to all subscribers with subscriber key

*When the user A (nto@gmail.com) is qualified  & created as a lead in salesforce, lead record is getting synced into Marketing Cloud with same email address resulting in duplicates.

So for same email address 2 records are added into marketing cloud
| SubscriberKey | EmailAddress |
| nto@gmail.com | nto@gmail.com|
| 005F0000NXAAa2| nto@gmail.com|
How can I overcome this issue ?


text:
Q: Audio via USB instead of Analog with Pulseaudio Using a Mac mini Mid 2011 running Catalina and a Dell Inspiron Mini 1012 running Raspbian (Debian 4.9), I currently have a 3.5mm cable connecting Mac headphone port to dell mic port. Dell equalizes the sound using Qpaeq/Pulseaudio and then out to speakers. Having some quality issues so I want to run digital instead of analog. I want to use a Usb cable and run all the audio digitally from Mac to Dell instead of 3.5. What terminal commands do I need to do to the dell to set up a USB audio device and have it be recognized by the Mac as a possible output device?
Inspired from this article https://www.cnet.com/how-to/make-the-most-out-of-your-computers-usb-audio-port/


text:
Q: Smooth curved line between 3 points in plot I have 3 data points on the x axis and 3 on the y axis:
x = [1,3,5]
y=[0,5,0]

I would like a curved line that starts at (1,0), goes to the highest point at (3,5) and then finishes at (5,0)
I think I need to use interpolation, but unsure how. If I use spline from scipy like this:
import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals)
p.line(xvals, y_smooth)

bk.show(p)

I get the highest point before (3,5) and it looks unbalanced:

A: The issue is due to that spline with no extra argument is of order 3. That means that you do not have points/equations enough to get a spline curve (which manifests itself as a warning of an ill-conditioned matrix). You need to apply a spline of lower order, such as a cubic spline, which is of order 2:
import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals, order=2) # This fixes your immediate problem
p.line(xvals, y_smooth)

bk.show(p)

In addition, spline is deprecated in SciPy, so you should preferably not use it, even if it is possible. A better solution is to use the CubicSpline class:
import bokeh.plotting as bk
from scipy.interpolate import CubicSpline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
spl = CubicSpline(x, y) # First generate spline function
y_smooth = spl(xvals) # then evalute for your interpolated points
p.line(xvals, y_smooth)

bk.show(p)

Just to show the difference (using pyplot):

As can be seen, the CubicSpline is identical to the spline of order=2

A: use pchip_interpolate():
import numpy as np
from scipy import interpolate

x = [1,3,5]
y=[0,5,0]

x2 = np.linspace(x[0], x[-1], 100)
y2 = interpolate.pchip_interpolate(x, y, x2)
pl.plot(x2, y2)
pl.plot(x, y, "o")

the result:

A: You can use quadratic interpolation. This is possible by making use of scipy.interpolate.interp1d.
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import numpy as np

x = [1, 3, 5]
y = [0, 5, 0]

f = interp1d(x, y, kind='quadratic')

x_interpol = np.linspace(1, 5, 1000)
y_interpol = f(x_interpol)

plt.plot(x_interpol, y_interpol)
plt.show()

Check the documentation for more details.


text:
Q: MySQL delete records after crash Almost after each server crash, few last database records are deleted. How could I fix or workaround this?
My distro is Ubuntu Server 9.10 and database MySql 5.1.37

A: You may want to change the type of Storage Engine you are using.  Typically the default MyISAM engine works great for indexing while the InnoDB works great for foreign key constraints.  These constraints can help you remove data from multiple tables when your initial query only appears to run against a single table.  It almost sounds like you were running a transaction using a InnoDB Engine.  Choose your database and then run the following to find out:
mysql> SHOW TABLE STATUS \G

You should be able to recover you records if you log them some where.  Logging certainly puts a load on your system but if they exist you'll probably find them here (you should log while your building out anyway):
/var/log/mysql

You can change your settings here:
/etc/mysql/my.cnf

Don't forget to reboot after making changes.  If you don't have logs try crashing your system intentionally after you do start logging.  You may see a similar transaction occur during your intentional crash that will give you some more clues.


text:
Q: SQL Union with fixed number of rows as result This is a simple representation of my student table.

Student
Year
Class

1
2010
A

2
2010
A

3
2010
C

4
2010
B

5
2011
B

6
2012
B

I want to compose a random group of 5 students.
In the group there will be 2 students of year 2010 and 3 students of group B. These values are user specified.
A simple union doesn't always work, because of the duplicate values. Sometimes there are 4 students, sometimes there are 5 students. I always want 5 records.
SELECT * FROM (SELECT TOP 2 * FROM [Student] WHERE YEAR = 2010 ORDER BY NEWID()) A
UNION
SELECT * FROM (SELECT TOP 3 * FROM [Student] WHERE Class = 'B' ORDER BY NEWID()) B

Is this possible with a SQL query?


text:
Q: How can I make refresh a Textbox from another form? C# I'm trying to update a Textbox from another form with this code:
private void Button2_Click(object sender, EventArgs e)
{
    Variables.revenu += Variables.LAIR * 30;
    Cartel_Form.Textbox_Revenu.Text = Variables.revenu.ToString();
}

But I get this error:

An object reference is required for the non-static field, method or property 'Cartel.Form.Textbox_Revenu'

Here is the content of the Textbox in the first form:
Textbox_Revenu.Text = Variables.revenu.ToString();

In the same form I can refresh/modify the Textbox but not in another form. The textbox modifier is set on public.

A: Here is an example using events where the child form contains the events while the main form listens for these events. Both forms have one TextBox and one NumericUpDown control. Or as @jimi mentioned use bindings.
Main form
using System;
using System.Windows.Forms;

namespace PassingDataBetweenFormsSimple
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowChildButton_Click(object sender, EventArgs e)
        {
            ChildForm childForm = new ChildForm();

            childForm.PassingData   += ChildFormOnPassingData;
            childForm.PassingNumber += ChildFormOnPassingNumber;

            try
            {
                childForm.ShowDialog();
            }
            finally
            {
                childForm.Dispose();
            }

        }

        private void ChildFormOnPassingNumber(int value)
        {
            numericUpDown1.Value = numericUpDown1.Value + value;
        }

        private void ChildFormOnPassingData(string text)
        {
            FirstNameTextBox.Text = string.IsNullOrWhiteSpace(text) ?
                "(empty)" :
                text;
        }
    }
}

Child form
using System;
using System.Windows.Forms;

namespace PassingDataBetweenFormsSimple
{
    public partial class ChildForm : Form
    {
        public delegate void OnPassingText(string text);
        public event OnPassingText PassingData;

        public delegate void OnPassingNumber(int value);
        public event OnPassingNumber PassingNumber;
        public ChildForm()
        {
            InitializeComponent();
        }

        private void PassDataButton_Click(object sender, EventArgs e)
        {
            PassingData?.Invoke(FirstNameTextBox.Text);
            PassingNumber?.Invoke((int)numericUpDown1.Value);
        }
    }
}


text:
Q: Advantage of accepting the axiom of choice What is the advantage of accepting the axiom of choice over other axioms (for e.g. axiom of determinacy)?
It seems that there is no clear reason to prefer over other axioms..
Thanks for help.

A: One high level (non-mathematical) reason for accepting the Axiom of Choice over, say, the Axiom of Determinacy is that the Axiom of Choice is somehow more "basic."  At some level it is more natural to think that all Cartesian products of nonempty sets are nonempty.  It doesn't quite seem as natural to think that the game $G_A$ is determined for all $A \subseteq \omega^\omega$.
At least, I think that most mathematicians have come to grips with the idea that there are badly behaved subsets of $\mathbb{R}$: there are sets which are not Lebesgue measurable; there are sets which do not have the Baire property; etc.  Why shouldn't there be sets of reals whose associated game is undetermined?
Of course, 100 years ago (or thereabouts) some mathematicians were up in arms over the possibility of well-ordering $\mathbb{R}$, and Zermelo's theorem was considered by some as a great argument against Choice.  That is to say, attitudes may change.

A: Well, there is quite the long list:

*

*Every set can be well ordered, so every two cardinalities are comparable.

*Continuity by $\epsilon$-$\delta$ is equivalent to continuity via sequences.

*There are free ultrafilters.

*Countable unions of countable sets are countable; similarly cardinal arithmetic become definable for infinite summations and products.

*Hahn-Banach theorem.

*Product of compact spaces is compact.

*Second countable implies Lindelof.

*Every vector space has a basis.

*Every unital ring admits a maximal ideal.

*Every set can be given a group structure.

The list goes on and on and on. In short, however, the main reason is that mathematics has grown to accept the axiom of choice and its consequences.
It really depends on what you want to do in mathematics, if you don't do set theory you're likely to benefit more from the axiom of choice than other axioms. If you are a set theorist (or planning on becoming one) then there will be places where the axiom of choice works naturally for your advantage and others where you will know to drop it and adopt other axioms instead.
Edit: Some of the implications above do not require the entire power of the axiom of choice. Indeed some of them follow by "mere" countable choice (choice for countable families) and other follow from weaker assertions like the Ultrafilter Lemma.
Furthermore, in some cases it is also possible to do things "by hand" and prove existence of ultrafilters, ideals, basis, etc. Most of classical analysis can get away with relatively weak principles like Dependent Choice, however it can require a bit more if you want to talk about $\ell^\infty$ kind of spaces (for example, without the axiom of choice it is possible for $\ell^1$ to be reflexive).
It is also important to notice that the universe can behave as though you have the full axiom of choice for sets which are so big that you will never go beyond their size - but after that thing breaks down badly, so while the axiom of choice is negated in a very strong way the universe that most mathematician like to think about has the axiom of choice in full.
Edit II: Having a few minutes to spare, I thought I should give my two cents why people prefer it (except for the fact they got used to it by now). One of the greatest set theorists of our time once told me during a break from a class he gave that a good axiomatic system is one that you use without noting.
For example, the axiom of extensionality makes a lot of sense because we want two sets to be equal exactly when they have the same elements. So does the axiom of power set.
The axiom of choice is very natural in the sense that it allows us to extend "finite definitions" to infinite ones (a good example is that every vector space has a basis, we can write one down for finite dimensional spaces, but we cannot "write it" for every infinite dimensional space). In this sense we are very accustomed to its gentle grace and willing to accept the few peculiarities like the Banach-Tarski paradox, or a well ordering of the real numbers.
This is why some of the mathematicians who were opposed to the axiom of choice (Lebesgue, Borel) actually used weak versions of it. You just don't notice that it's there.

Further reading on the site:

*

*Algebraic closure for $\mathbb{Q}$ or $\mathbb{F}_p$ without Choice?

*Is there a non-trivial example of a $\mathbb Q-$endomorphism of $\mathbb R$?

*Does every set have a group structure?

*A question about cardinal arithmetics without the Axiom of Choice

*axiom of choice: cardinality of general disjoint union

*Cardinality of an infinite union of finite sets

*Axiom of choice and automorphisms of vector spaces

*Axiom of choice - to use or not to use

*Motivating implications of the axiom of choice?

A: A practical reason is that certain mathematical theorems are known to be equivalent to the axiom of choice. In particular, the fact that every vector space has a basis and the theorem of Tikhonov that arbitrary products of compact spaces are compact require the axiom of choice.
More importantly, th axiom of choice is equivalent to th arbitrary product of nonempty sets being nonempty. This seems to be a consequence of our intuitive notion of set. So even though w seldom use the full axiom of choice, it seems to be part of the way of thining about sets.

A: It allows the use of nonprincipal ultrafilters, which are needed for nonstandard analysis.  (This doesn't actually need the full strength of AC, but you can't do it in ZF.)

A: Another reason which might not be quite so accessible to you yet is that (a statement equivalent to) the axiom of choice is used to prove that every $R$-module admits an embedding into an injective $R$-module, which allows us to have a theory of sheaf cohomology in algebraic geometry. Sheaf cohomology is something which lots of people care about- not having choice around would present major problems for almost all of them.


text:
Q: How do I make a while loop of 2 conditons and stop at true condition I want to create a while loop that request the user input for yes or no, if the user enter anything else it will loop until the user enters either yes or no
echo "Do you wish to save these settings?"
read response
while [ "$response" != "yes" ] | [ "$response != "no" ]
do
   echo "Please enter yes or no only"
   echo "Do you wish to save these settings?"
   read response
done

when i tried entering yes it still continues to loop but when i enter no it exits the loop

A: In shell, the | (or pipe) operator is used to filter the output of the command on the left using the command on the right.
For example, the following line of shell:
seq 1 3 | tac
...will result in the lines produced by the command on the left...
1
2
3

...to be filtered by the command on the left (which will emit the lines in reverse order).  The output will be:
3
2
1

You're after an operator that performs a boolean operation on the exit statuses of two commands.  Since you're looking to continue the loop as long as the response is neither yes or no, the conjunction operator (&&) is what you're after:
echo "Do you wish to save these settings?"
read response
while [ "$response" != "yes" ] && [ "$response" != "no" ]
do
   echo "Please enter yes or no only"
   echo "Do you wish to save these settings?"
   read response
done

If the bash shell will always be available wherever you're running your script, this could be improved further by using [[ ... ]] instead of [ ... ].  Besides a potential performance benefit, another advantage of using [[ is that the requirements on strict quoting are relaxed:
echo "Do you wish to save these settings?"
read response
while [[ $response != yes ]] && [[ $response != no ]]
do
   echo "Please enter yes or no only"
   echo "Do you wish to save these settings?"
   read response
done

A further improvement comes from the knowledge that [[ supports && to conjoin two boolean expressions:
echo "Do you wish to save these settings?"
read response
while [[ $response != yes && $response != no ]]
do
   echo "Please enter yes or no only"
   echo "Do you wish to save these settings?"
   read response
done

A: Just while true the whole thing until satisfied:
while true
do
    echo "Do you wish to save these settings?"
    read response
    if [[ "$response" = "yes" ]] || [[ "$response" = "no" ]]
    then
        break
    fi
    echo "Please enter yes or no only"
done


text:
Q: JavaScript destructure object into other object set default value I am destructuring the value of an object from an array. If array is empty, error happens. How to make default value, if array is empty?
Error happens if array, which I am destructuring is empty:

"TypeError","message":"Cannot destructure property payments of 'undefined' or 'null'."

Code of destructuring (await (...).toArray() is returning array [ { payments: @integer } ]):
    ({
        [0]: { payments: users.finances.payments = 0 },
    } = await (
        await payments_collection.aggregate([
            {
                $group: {
                    _id: null,
                    payments: { $sum: '$coins' },
                },
            },
        ])
    ).toArray());

A: @adiga, thanks for your answer.
I replaced { [0]: { payments: users.finances.payments = 0 } } with [{ payments: users.finances.payments = 0 } = {}]
New working code:
    [{ payments: users.finances.payments = 0 } = {}] = await (
        await payments_collection.aggregate([
            {
                $group: {
                    _id: null,
                    payments: { $sum: '$coins' },
                },
            },
        ])
    ).toArray();


text:
Q: How to construct full URL from Wikipedia [[File:...]] tag in wikimedia markup? What logic does Wikipedia use to generate the full URL for images in articles, given the [[File:...]] tag in the wikimedia markup, or the infobox |image=... line?
The url seems to always start with http://upload.wikimedia.org/wikipedia/commons/, followed by two url segments that do not seem to be predictable, plus the image name which can be predicted from the tag.
For example,
[[File:Michael Jordan UNC Jersey cropped.jpg|thumb|left|Michael Jordan's jersey in the rafters of The [[Dean Smith Center]]]]

yields:
http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Michael_Jordan_UNC_Jersey_cropped.jpg/220px-Michael_Jordan_UNC_Jersey_cropped.jpg

Is there any way to programatically determine the /6/6a part of the url, or is this a lookup on a Wikipedia server?
Another example, in the Infobox:
|image = Jordan Lipofsky.jpg

yields:
http://upload.wikimedia.org/wikipedia/commons/b/b3/Jordan_Lipofsky.jpg

Can the /b/b3 portion of the URL be predicted?
Thanks!

A: Turns out it's generated from an MD5 hash. Something like the below in Scala will work -- although I'm not sure how to predict whether it's in /commons or in /en.
import org.apache.commons.codec.digest.DigestUtils
def getImageUrl(fileName: String, rootUrl: String): String = {

    val messageDigest = DigestUtils.md5Hex(fileName.replace(" ", "_"))
    val md5 = messageDigest

    val hash1 = md5.substring(0, 1)
    val hash2 = md5.substring(0, 2)

    rootUrl + hash1 + "/" + hash2 + "/" + fileName

}

Careful about leading zeros, as discussed here:
Does wikipedia use different methods to compute the hash part of an image path?
http://lists.wikimedia.org/pipermail/mediawiki-api/2011-December/thread.html#2446


text:
Q: Ubuntu 18.04 keyboard + sound issues I have a laptop with Ubuntu 18.04 LTS installed.
Working properly for a while (random amount of time), the keyboard gets BLOCKED with no response to any key.
Also, this is accompanied by youtube video lagging (frames start to repeat themselves).
Everything else continues to work normally.
Thanks in advance.


text:
Q: Displaying selected data from Google Calendar on web page? I appreciate there have been several questions of this nature, but none seems to address my particular (simple!) need.
I have an Apps Script function that happily accesses a public Google calendar and extracts the events for today, and I can list these on the console quite happily.
What I now want to do is to put these events on an HTML web page.  The events can change often during the day, so people want to be able to see the latest data when they load my web page.  It seemed like a simple matter, but the more I look into it, the more confused I get!
Is there an easy way to do this, or am I going to have to get involved with Google APIs etc?
Thanks.
Perhaps I should add that I know I could just embed the calendar in the page, but all the user wants to know is "Is the facility open at the moment/later today" and not have to manipulate a Google calendar.

A: You can do some tweaking to the embed view, like showing a single day only. Here's an example:
https://calendar.google.com/calendar/u/0/embed?showNav=0&showPrint=0&showCalendars=0&mode=DAY&src=en.usa%23holiday@group.v.calendar.google.com
That said, I can understand not wanting to use iframes. The good news is that if you're already using Apps Script, you're already using the Calendar API.
The only thing new you need to do is enable the API create your own API key. Follow the instructions to:

*

*Enable the Calendar API

*Create an API key
I've simplified the quickstart example to work without OAuth (which is the majority of the complexity). You don't need to care about authorization for a public calendar.
<!DOCTYPE html>

    <title>Google Calendar API Quickstart</title>
    <meta charset="utf-8" />

Google Calendar API

See also Google Calendar API Reference Docs


text:
Q: evaluate function in column with cell relative reference vba I need to write in column 24 the result of an IF formula that includes reference to relative cell. I think the fatest way is using Evluate function, but I didn't understand how to write each cell relative reference in the formula.
This is my code
Set Rng1 = Sheets("Leaders").Cells(12, 19)

g = Evaluate("IF(OR(" & Rng1.Offset(, -3).Address(False, False) & "=""x""," & Rng1.Offset(, -5).Address(False, False) & "=""1:1 matching"")," & Rng1.Offset(, 3).Address(False, False) & "*" & Rng1.Offset(, 4).Address(False, False) & ")")

Sheets("Leaders").Range(Cells(12, 24), Cells(lastRow1, 24)) = Evaluate(g)

the result is zero in all cell of column 24

A: Use the below code.
Sheets("Leaders").Range(Cells(12, 24), Cells(lastRow1, 24)) = "=IF(OR(RC[-8]=""x"",RC[-10]=""1:1 matching""),RC[-2]*RC[-1])"


text:
Q: How to share location on Facebook along with message using https://graph.facebook.com/me/feed Is it possible to use iOS SLRequest and graph API "https://graph.facebook.com/me/feed" ,..for posting a message with the location on Facebook wall ?
I have implemented SLRequest as below,
                        SLRequest *feedRequest = [SLRequest
                                               requestForServiceType:SLServiceTypeFacebook
                                               requestMethod:SLRequestMethodPOST
                                               URL:https://graph.facebook.com/me/feed
                                               parameters:@{@"message": @"text message with location",@"link":@"www.google.com",@"place":@"Road No 19, Mumbai"}];

with                                       ACFacebookPermissionsKey: @[@"publish_stream",
                                                                  @"publish_actions"],
returns 500 status error.
Thanks.

A: The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server.
Use this to integrate in your code to share location
https://developers.facebook.com/docs/ios/placepicker-ui-control/
Use this method to post feed:-
-(IBAction)postFBMessage:(id)sender
{
    // Create the URL to the end point
    NSURL *postURL = [NSURL URLWithString:@"https://graph.facebook.com/me/feed"];

    NSString *link = @"http://developer.apple.com/library/ios/#documentation/Social/Reference/Social_Framework/_index.html%23//apple_ref/doc/uid/TP40012233";
    NSString *message = @"Testing Social Framework";
    NSString *picture = @"http://www.stuarticus.com/wp-content/uploads/2012/08/SDKsmall.png";
    NSString *name = @"Social Framework";
    NSString *caption = @"Reference Documentation";
    NSString *description = @"The Social framework lets you integrate your app with supported social networking services. On iOS and OS X, this framework provides a template for creating HTTP requests. On iOS only, the Social framework provides a generalized interface for posting requests on behalf of the user.";

    NSDictionary *postDict = @{
    @"link": link,
    @"message" : message,
    @"picture" : picture,
    @"name" : name,
    @"caption" : caption,
    @"description" : description
    };

    SLRequest *postToMyWall = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:postURL parameters:postDict];

    FacebookAccountManager* sharedManager = [FacebookAccountManager sharedAccount];
    [postToMyWall setAccount:sharedManager.facebookAccount];

    [postToMyWall performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
    {
        if (error) {
            // If there is an error we populate the error string with error
            _errorString = [NSString stringWithFormat:@"%@", [error localizedDescription]];

            // We then perform the UI update on the main thread. All UI updates must be completed on the main thread.
            [self performSelectorOnMainThread:@selector(updateErrorString) withObject:nil waitUntilDone:NO];
        }

        else
        {
            NSLog(@"Post successful");
            NSString *dataString = [[NSString alloc] initWithData:responseData encoding:NSStringEncodingConversionAllowLossy];
            NSLog(@"Response Data: %@", dataString);
        }
     }];
}


text:
Q: Which name is better for Virtual Host files on Nginx and Apache? My main site is accessed by the address www.example.com, so should by my nginx virtual host file named as www.example.com and not example.com to avoid searches  of the server_name variable www in others blocks of virtual host files?
The same thing apply to apache?, www.example.com.conf and not example.com.conf
This make sense or both do not count www. in file names by default?

A:
... to avoid searches of the server_name variable www in others blocks of virtual host files

The name of the file is (almost) inconsequential to the httpd server. When the system starts the contents of the conf files are read into and cached in memory. Any searches are performed against this cache at the speed of memory.

... so should by my nginx virtual host file named as www.example.com and not example.com

Use whichever makes most sense to you. Personally I use the primary name to name the conf files.

A: Configuration files are loaded in filename order and parsed internally so after the load at startup are accessed through a hash, so it doesn't really make a lot of difference in my experience. I would tend to keep VirtualHosts in a domain together so would name the virtual hosts for the domain.


text:
Q: Tabular multicolumn cell boundaries Consider the code:
\documentclass{article}
\begin{document}
    \begin{table}
        \begin{tabular}{|c|c|c|}
            \hline
            1  & 2  & 3\tabularnewline
            \hline
            4  & \multicolumn{2}{c}{5}  \tabularnewline
            \hline
        \end{tabular}
    \end{table}
\end{document}

It produces the table:

How do I "close" the cell (add the right boundary as in the line above)?

A: You need to tell multicolumn to use those vertical lines.

\documentclass{article}
\begin{document}
    \begin{table}
        \begin{tabular}{|c|c|c|}
            \hline
            1  & 2  & 3\\\hline
            4  & \multicolumn{2}{c|}{5}\\\hline
        \end{tabular}
    \end{table}
\end{document}


text:
Q: Encrypt a String in another String using a key String, compile issue I need 2 simple encryption and decryption methods to encrypt a String a in an ecrypted String b using another String key as Encryption and Decryption key.
I have found this code that seems doing what I need
public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;

    DesEncrypter(SecretKey key) {
        try {
            ecipher = Cipher.getInstance("DES");
            dcipher = Cipher.getInstance("DES");
            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);

        } catch (javax.crypto.NoSuchPaddingException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch (java.security.InvalidKeyException e) {
        }
    }

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Unfortunately need a fix to works,
I get an error in
sun.misc.BASE64Encoder()

and in
sun.misc.BASE64Decoder()

that ask me to create a base64 encoder and decoder in sun.misc package
How to fix?

A: sun.misc.BASE64Encoder and sun.misc.BASE64Decoder do not exist in the Android Java implementation. They are internal only in Oracle's JDK, although you do have access, they are not guaranteed to be there.
You can use the android.util.Base64 class to encode and decode base 64 in Android.
To encode, change:
return new sun.misc.BASE64Encoder().encode(enc);

to:
return android.util.Base64.encodeToString(enc, android.util.Base64.DEFAULT);

To decode, change:
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

to:
byte[] dec = android.util.Base64.decode(str, android.util.Base64.DEFAULT);


text:
Q: How to remove copies of one object under the same variable name Here is my code to start off:
numTrumps=100

  local function startGame()
    myTrump=display.newImageRect("tp.png",25,25)
     myTrump.x=Random(50,_W-50)
     myTrump.y=(_H+10)
     physics.addBody(myTrump,"dynamic",{density=.1,friction=0,bounce=.9,radius=9})

    function myTrump:touch(event)

    if(timeLeft~=false) then

        if (playerReady==true) then
            if(event.phase=="ended") then
            removeTrumps(self)
        end

    end
end
end
        myTrump:addEventListener("touch",myTrump)

trumps=trumps+1

if(trumps==numTrumps) then
    gameTimer=timer.performWithDelay(1000,countDown,totalTime)
else

    playerReady=false
end
end

  local gameTimer=timer.performWithDelay(20,startGame,numTrumps)

local function Restart(event)
    if "began"==event.phase then

if(timeLeft~=false) then

    timer.cancel(gameTimer)
     gameTimer1=timer.performWithDelay( 20, ByeTrump, 96)

    end

end
        if "moved"==event.phase then

end
            if "ended"==event.phase then

            composer.gotoScene("restarttest")

            end
        end

function ByeTrump()
    display.remove(myTrump)
end

So basically the startGame function is repeated 100 times since numTrumps=100 so each time a new image of the same object (myTrump) is created. Once i restart i want to remove the copies of that object so i made a function (ByeTrump) in which one of the myTrump's are removed, and i repeated that 96 times by making another gametimer in restart function. I made 96 disappear not 100 for testing purposes but in my game you have 20 seconds to touch as many of the 100 myTrumps possible and upon touching they are gone.Once 20 seconds is up you can no longer touch them so you have to restart.
So my problem is when i click restart only one of the myTrump's disappear not the remaining 99 (i am not touching any of the myTrumps in the 20 seconds for testing purposes).So when the new 100 myTrumps come after restarting they collide with the ones from the last round even though the last ones aren't visible anymore its like they are invisible a=but still colliding with the new ones.

A: By storing all the Trumps (lol) in the same variable you're creating each object and then, the next step, removing the connection you had with it by linking the connection with another object, so the first object is still there, but you can't reach it anymore.
Probably a single call to collectgarbage() should work (not sure though) because what the garbage collector does is eliminating any object you don't have any connection with anymore, but I'm not sure if it will work with your type of objects, so here's the standard way to do it.
If you don't want to replace the connection with the first object with a second object you need both an high number of different variables (trump1, trump2... trump100) or, better yet, a single data structure that can hold more than one variable.
That is, tables.
So you should initialize that table:
allTrumps = {}

And then, in the startGame function, instead of storing the new object in myTrump, you add a new field to the table which will hold that object:
allTrumps[#allTrumps + 1] = display.newImageRect(...)

What are you doing is checking the lenght of your table (or the number of objects in it) and storing an object in the next position.
When you want to remove the trumps, you can start from the first or from the last trump you added. We'll start from the last for semplicity.
function ByeTrump()
    display.remove(allTrumps[#allTrumps])

end

This will remove the last trump you created, so the table will contain one less object, the size will decrease by one, and you can already call the function again to remove another trump.


text:
Q: How can I access the new javascript keyword from scala.js? I am porting a JavaScript library to Scalajs. The JS Objects are created with the new keyword on the JavaScript side, so this is what I do in most cases.
trait Point extends js.Object {
  def normalize(length: Double): Point = js.native
}

This seems to work well for methods, however, this doesn't work for constructors.
@JSName("paper.Point")
object PointNative extends js.Object {
  def apply(props: RectProps): Rectangle = js.native
}

The above code does not work. It passes type checks and compiles, but at runtime it returns undefined.
If I modified PointNative like this then all is good.
import js.Dynamic.{ global => g, newInstance => jsnew }
object PointNative {
  def apply(props: RectProps): Rectangle = jsnew(g.paper.Point)(props).asInstanceOf[Point]
}

Is there a way to use @JSName and js.native with the new keyword?
Thanks!

A: Since, in the JavaScript API, paper.Point needs to be instantiated with the new keyword, you need to define PointNative as a class:
@JSName("paper.Point")
class PointNative(props: PointProps) extends js.Object {
  ...
}

which allows to instantiate it with
new PointNative(props)

just like you would have done in JavaScript.
If you also want to be able to instantiate it with just
PointNative(props)

then you need to define an additional, non-js.Object companion with an apply() method:
object PointNative {
  def apply(props: PointProps): PointNative = new PointNative(props)
}

Note that, if you need the companion PointNative to be a js.Object (because you also want to define static methods of paper.Point in it), then you can pimp apply() on it with an implicit class instead:
implicit class PointNativeCompanionOps(val self: PointNative.type) extends AnyVal {
  def apply(props: PointProps): PointNative = new PointNative(props)
}


text:
Q: how to have multiple inputs on left side of row and one on the right in foundation 5
How do I move the City, State and Zipcode inputs up where they should be?  I have been messing around with the rows and the end, pull, push and offset classes but i guess i haven't found the right combination.  Any help will be great.  Thanks!
My Modal HTML:
Customers

Customers

              <form>

                  Business Name
                    <input type="text" placeholder="Enter Business Name" />

                  Contact Name
                    <input type="text" placeholder="Enter Contact Name" />

                  Business Phone
                    <input type="email" placeholder="Enter Business Phone Number" />

                  Contact Phone
                    <input type="text" placeholder="Enter Contact Phone Number" />

                  Address 1
                    <input type="text" placeholder="Enter Address" />

                  Contact Email
                    <input type="text" placeholder="Enter Contact Email" />

                  Address 2
                    <input type="text" placeholder="Enter Address" />

                  Notes
                    <textarea placeholder="Enter Optional Notes" rows="10"></textarea>

                  City
                    <input type="text" placeholder="Enter City" />

                  State
                    <select>
                      <option value="AL">Alabama</option>
                        <option value="AK">Alaska</option>
                        <option value="AZ">Arizona</option>
                        <option value="AR">Arkansas</option>
                        <option value="CA">California</option>
                        <option value="CO">Colorado</option>
                        <option value="CT">Connecticut</option>
                        <option value="DE">Delaware</option>
                        <option value="FL">Florida</option>
                        <option value="GA">Georgia</option>
                        <option value="HI">Hawaii</option>
                        <option value="ID">Idaho</option>
                        <option value="IL">Illinois</option>
                        <option value="IN">Indiana</option>
                        <option value="IA">Iowa</option>
                        <option value="KS">Kansas</option>
                        <option value="KY">Kentucky</option>
                        <option value="LA">Louisiana</option>
                        <option value="ME">Maine</option>
                        <option value="MD">Maryland</option>
                        <option value="MA">Massachusetts</option>
                        <option value="MI">Michigan</option>
                        <option value="MN">Minnesota</option>
                        <option value="MS">Mississippi</option>
                        <option value="MO">Missouri</option>
                        <option value="MT">Montana</option>
                        <option value="NE">Nebraska</option>
                        <option value="NV">Nevada</option>
                        <option value="NH">New Hampshire</option>
                        <option value="NJ">New Jersey</option>
                        <option value="NM">New Mexico</option>
                        <option value="NY">New York</option>
                        <option value="NC">North Carolina</option>
                        <option value="ND">North Dakota</option>
                        <option value="OH">Ohio</option>
                        <option value="OK">Oklahoma</option>
                        <option value="OR">Oregon</option>
                        <option value="PA">Pennsylvania</option>
                        <option value="RI">Rhode Island</option>
                        <option value="SC">South Carolina</option>
                        <option value="SD">South Dakota</option>
                        <option value="TN">Tennessee</option>
                        <option value="TX">Texas</option>
                        <option value="UT">Utah</option>
                        <option value="VT">Vermont</option>
                        <option value="VA">Virginia</option>
                        <option value="WA">Washington</option>
                        <option value="WV">West Virginia</option>
                        <option value="WI">Wisconsin</option>
                        <option value="WY">Wyoming</option>
                    </select>

                  Zipcode
                    <input type="text" placeholder="Enter zipcode">

              <input type="submit" class="add-btn button right small" value="Add">
              ×
            </form>

A: One solution would be to create giant columns. So the entire left side is one column and the entire right side is one column.
(Heads up don't blindly copy and paste, I removed some fields to save time.)
To elaborate a little you are creating a dynamically sized row for both "notes" and "address". You need to split them up into different containers so they don't share the same height. I find I need to visualize this every once and awhile and to do so you can open your page in chrome and right click and go to inspect element, then when you highlight over the code you can see what rows and columns contain what elements with nifty little colored boxes.
    Customers

Customers

        <form>

                            Business Name
                                <input type="text" placeholder="Enter Business Name" />

                            City
                                <input type="text" placeholder="Enter Business Name" />

                            State
                                <input type="text" placeholder="Enter Business Name" />

                            Zip
                                <input type="text" placeholder="Enter Business Name" />

                            Contact Name
                                <input type="text" placeholder="Enter Contact Name" />

                            Notes
                                <textarea placeholder="Enter Optional Notes" rows="10"></textarea>

        </form>


text:
Q: Use more than one file in a Go program I wish to learn how to logically split my code in a Go package into multiple files, and crucially, the syntax necessary to use that split/separate file in another file of the same package.
I have created a go project in this form
-test
    -bin
    -pkg
    -src
        -main
            main.go
            test.go

and attempted to run go build main and go build main.go test.go, but I have always got an error.
test.go contains only this code
package main
import "fmt"
func do(b string) {
    fmt.Println(b)
}

I want to be able to call do("x") in main.go.
Right now all that is in main.go is
package main
func main() {
    test.do("x")
}

I do not know what to do to get this to work.  Many answers seem to suggest moving test.go into a directory "test".  I am hoping Go does not require me to make a directory for every piece of code I write, but maybe I would be "fighting the system".  Many answers have pointed me to a website telling me to make the above directory structure, and to use go install to compile my binaries, but that does not work.
I just want to know how to use functions in package/x.go inside package/y.go, even if they are in the same package.  There has to be a way to do this, otherwise I will have either a bunch of unnecessary packages or hard to understand monolithic files.
I know there are many similar questions, but in my searching I haven't been able to find an actual example of the code in two files in the same package that reference each other.

A: test.go has to be in the same package if is in the same directory. the package is thus main for both of the files and being in the same package you can just call do("x") .
Additionally you can build the entire package like this without specifying the single files.
export GOPATH="<path to>/test"

go build main

A: Just use:
do

instead of:
test.do


text:
Q: Retrieving Alternating Values I have a column with two values in my database, I want to retrieve the two values alternately, for example I have:
name   itemcode
----------
 A       1
 B       2
 C       2
 D       2
 E       1
 F       1

I want to display them as:
name itemcode
----------
A      1
B      2
E      1
C      2
F      1
D      2

A: Here's a solution for SQL Server. This does work if you have itemcode 3, 4, etc. and not just 1 and 2.
CREATE TABLE [dbo].[Test]
(
    name char(1) NOT NULL,
    itemcode tinyint NOT NULL
);

INSERT INTO [dbo].[Test](name, itemcode)
    VALUES ('A', 1), ('B', 2), ('C', 2), ('D', 2), ('E', 1), ('F', 1);

SELECT
    t.name,
    t.itemcode
    FROM
    (
        SELECT
            name,
            itemcode,
            ROW_NUMBER() OVER(PARTITION BY itemcode ORDER BY name) AS RowNum
            FROM [dbo].[Test]
    ) t
    ORDER BY
        t.RowNum,
        t.itemcode;


text:
Q: How discard empty HTML form inputs from $_FILES array I have a HTML form with multiple file inputs
<input type='file' id='images' name='images[]'>

I use implode() to covert the $images array into comma separated string and insert it into my DB , then when calling I use explode() to recall single images.
the problem is : empty input fields are still submitted to the database , so when exploded, I get empty array values
how can I get rid of these empty array values ? maybe even before using implode function ?
I'm thinking of running a foreach loop throw the $_FILES['images'] array and  discarding empty values from it and rebuilding a new array .. but is any easier method available ?
thanks

A: Use array_filter. It is a function which iterates over an array with another function specified as an argument. But if you don't pass this argument, the array_filter will simply get rid of the values equal fo FALSE.
$images = implode(',', array_filter($_FILES['images']));

A: $images = array_filter($_POST['images']);
But I would rethink the database design.  You probably shouldn't be storing lists like that.


text:
Q: Null pointer exception reports in C2DMBaseReceiver class (from marketplace) I have C2DM implemented in my app, I see a decent number of crash reports in the marketplace caused by a null pointer exception in the C2DMBaseReceiver class. This class is from the chrometophone project, which is referenced in the C2DM guide (http://code.google.com/android/c2dm/):
http://code.google.com/p/chrometophone/source/browse/trunk/android/c2dm/com/google/android/c2dm/C2DMBaseReceiver.java
The npe happens in onHandleIntent(), mWakeLock is sometimes null:
// From C2DMBaseReceiver.java:
@Override
public final void onHandleIntent(Intent intent) {
    try {
        Context context = getApplicationContext();
        if (intent.getAction().equals(REGISTRATION_CALLBACK_INTENT)) {
            handleRegistration(context, intent);
        } else if (intent.getAction().equals(C2DM_INTENT)) {
            onMessage(context, intent);
        } else if (intent.getAction().equals(C2DM_RETRY)) {
            C2DMessaging.register(context, senderId);
        }
    } finally {
        //  Release the power lock, so phone can get back to sleep.
        // The lock is reference counted by default, so multiple
        // messages are ok.

        // If the onMessage() needs to spawn a thread or do something else,
        // it should use it's own lock.
        //
        //
        //
        // NULL POINTER EXCEPTION REPORTS HERE
        mWakeLock.release();
        //
        //
        //
    }
}

The fix is easy enough, just check for mWakeLock != null before accessing it. But I wonder if anyone else has seen this, if the docs should be updated with this check? Or maybe this is a bigger problem, if the author expected mWakeLock to always be initialized?
Thanks

I put a null check in that line, just moved the error a bit:
java.lang.RuntimeException: WakeLock under-locked C2DM_LIB
  at android.os.PowerManager$WakeLock.release(PowerManager.java:304)
  at android.os.PowerManager$WakeLock.release(PowerManager.java:279)
  at com.google.android.c2dm.C2DMBaseReceiver.onHandleIntent(C2DMBaseReceiver.java:122)
  at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:123)
  at android.os.HandlerThread.run(HandlerThread.java:60)

Still no idea how to fix this.

A: According to Mark Murphy, who helped develop this code, there are scenarios where this error will occur, even if your code is entirely correct. See this Google Groups thread for his explanation - either the lock wasn't acquired to start with or was acquired in a different process.
If you get this exception persistently then you likely have a defect. Check (using diagnostics) to see if the same process is acquiring the wake lock as the one that is releasing it.

A: There is a new class in the support library, WakefulBroadcastReceiver , that helps with the hand off of a wake lock between broadcaster and receiver.
The new GCM implementation instructions specify its use: http://developer.android.com/google/gcm/client.html


text:
Q: C++ FIR noise filter I'm digging up some info about filtering the noise out of my IQ data samples in C++.
I have learned  that this can be done by using a simple filter which calculates the average of last few data samples and applies it to the current sample.
Do you have any further experience with this kind of filtering or do you recommend using some existing FIR filtering library?
Thanks for your comments!

A: Unfortunately, it is not as simple as "just get some library and it will do all the work for you"; digital filters is a quite complicated subject.

*

*It is easy to apply digital filter to your data only if your measurements come at fixed time intervals (known as "sample rate" in digital filters). Otherwise (if time intervals vary), it is not trivial to apply digital filters (and I suspect you might need FFT to do it, but I might be wrong here).

*Digital filters (both IIR and FIR) are interesting in that as soon as you know coefficients, you don't really need a library, it is easy to write it yourself (see, for example, first picture here: https://en.wikipedia.org/wiki/Finite_impulse_response : looks simple, right?); it is finding coefficients which is tricky.

*As a prerequisite to find out coefficients, you need to understand quite a lot about filters: you need to know what kind of filter you need (if it is after demodulation - you'll likely need low-pass, otherwise see comment by MSalters below), you need to understand what "corner frequency" is, and you need to realize how to map those frequencies to your samples (for example, you can say that your samples are coming once per second - or at any other rate, but this choice will affect your desired "corner frequency"). As soon as you've got this understanding of "what you need in terms of digital filters" - finding coefficients is quite easy, you can do it either in MatLab, or using online calculator, look for "digital filter calculator" in Google.


text:
Q: Is Azure Search as a service going to be deprecated While evaluating Azure Search for possible implementation I discovered that the MSDN forum specific to Azure Search was only recently closed down. They advise that questions regarding Search be instead asked here on Stack Overflow.
This strikes me as a bit unusual, so my question is this: Is the fact that Azure Search is no longer a first-class citizen on MSDN indicative of a potential deprecation of this service from Azure?
Thank you

A: Not at all :) You may want to use "Azure Cognitive Search" in your searches however, as this is the branding going forward. The team also generally prefers to standardize on answering questions on SO.


text:
Q: Reuse node removed from DOM I've been struggling with this issue for the last couple of hours now and have decided to come to stackoverflow for this.
I want to clear all of the elements in the body tag, except 1 (this includes it's children).
So what I thought I'd do is.
1. Store the element in a variable.
2. Clear the body tag.
3. Re-add the stored element.
However, the developer console gives me the following error.
Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.

What is it that I'm doing wrong?
Also, I'm not using jQuery or any other framework, so native JavaScript would be appreciated.
var myBody = null;

var myNode = document.getElementsByTagName("body")[0];
while(myNode.lastChild) {
if(myNode.lastChild.id !== "c_container") {
    myNode.removeChild(myNode.lastChild);
}else{
    myBody = myNode.removeChild(myNode.lastChild);
}
}

myNode.appendChild(myBody);

HTML only the parts which matter to the subject:

A: You could just get the element you want to save by id. Then clear the body by setting its content to "" and then appending the saved element. No need to loop and remove nodes individually.
var ele = document.getElementById("c_container");
document.body.innerHTML = "";
document.body.appendChild(ele);

jSFiddle

A: The reason your code worked when I tried it in jsfiddle but not for you is that your "c_container" element is inside an element that your code will remove. The string of node children is just the level of the DOM tree immediately beneath the starting point (the body, in your case).  Your loop will only go for one iteration, removing that wrapper
 element. It'll never see your "c_container" because it's not a direct child of the  tag.


text:
Q: Error when accessing an Excel workbook from within a parallel loop I am using MATLAB to write to an Excel file with Macros in them, and then reevaluate the file and extract the Macro results using xlsread. The code works fine with only one worker. However, if I use parfor and use a second worker, MATLAB gives the error message as below. To be rigorous, I have created a second Excel file for the second worker and use t = getCurrentTask(); t.ID; to instruct the workers to work on their arranged excel file.

Error using xlswrite (line 226)
Invoke Error, Dispatch Exception:
  Source: Microsoft Excel
  Description: Microsoft Excel cannot access the file
  'C:\Users-----\D0481000'. There are several
  possible reasons:
  • The file name or path does not exist.
  • The file is being used by another program.
  • The workbook you are trying to save has the same name as a currently open workbook.
  Help File: xlmain11.chm
  Help Context ID: 0
Error in extractFromExcelExpress (line 249)
     xlswrite(filename,writtenIn,sheet,'B23');

This happens randomly. I did try to change the folder of the excel files and it starts to work for hours but ultimately stops. I did clear all the add-ins in Excel and I did put the corresponding folder to the excel trust locations.

*

*The Excel version: 2016

*The MATLAB version: R2017a

A: This sounds like a typical race condition issue caused by multiple processes requiring exclusive access to the same file. The basic idea is that one process still hasn't closed the file when another tries to open it, and you only get errors sometimes because these issues don't always occur (see also: Heisenbug).
Here are several suggestions regarding what you can do (in decreasing order of what makes sense to me):

*

*Try redesigning the code such that only one process ever accesses (read OR write) the file at a time. This is called a "critical section". The easiest way to achieve this in MATLAB is by having the xlswrite code outside the parfor. If you're having a hard time implementing this while keeping the parfor, simply save all intermediate result to a workspace variable, and write it to disk when the computations are done.

*You might be able to share the ActiveX object between the processes (I've never tried this, and can't say for sure that it's possible), using the same approach as in xlswrite1. Essentially it doesn't try to open and close the file between writes, so the situation where one process still hasn't closed it where another tries to open it cannot happen.

*Find a way to use the Workbook.MultiUserEditing property. This is possibly related to the previous suggestion.

*Use the fastest storage available. You can use a RAM drive, and put your Excel file there, so that you could at least avoid any slowness caused by using a network drive, an HDD, or even an SSD.

*If all else fails, surround the xlswrite statements with a while true, try, xlswrite(...); break; catch, pause(0.01); end, end. This will slow the code down but at least it will finish eventually.


text:
Q: How does editor \ preview for Windows Phone work in Visual Studio works? How is the image of the Page's XAML gets generated?
Is it running a virtual machine and it's grabbing a snapshot?
Does it send the XAML?
Any details of that would be welcome.

A:
How is the image of the Page's XAML gets generated?

Visual studio renders the XAML using platform's reference DLLs + compiled binaries of your app.

Is it running a virtual machine and it's grabbing a snapshot?

Nope, it all works in the same visual studio process.


text:
Q: Setting CPU affinity to a process - C - Linux Not the best in C programming, here is my first trial to port a program from python to C.
Credits to Alnitak for the program below
#include<sched.h>

void task_set(int pid) {
        int result;
        cpu_set_t  mask;
        CPU_ZERO(&mask);
        CPU_SET(pid, &mask);
        result = sched_setaffinity(0, sizeof(mask), &mask);
        printf ("%d\n",result);
}

void main()
{ //excuse me for the static
task_set(1400);
}

To compile I did this..
gcc -D_GNU_SOURCE -o test test.c

However, when I try to go back and check where the program is running using the following script:
def which_core(pid):
        f = file(os.path.join('/proc', str(fpid), 'stat'), 'rb')
        val = f.read()
        f.close()
        return int(val.split(' ')[-6])
print 'core_id',which_core(1400)

It gives me the following output:
core_id 32997376

It is quite confusing there... what is the mistake?

A: OK.
This is the stupidest thing that one can ever do!
    CPU_SET(pid, &mask);

    CPU_SET(coreid, &mask);

changing the pid to the coreid will do it.
The other mistake was here:
    result = sched_setaffinity(pid, sizeof(mask), &mask);

A: You're probably looking for field 39 (counting from 1)

processor %d (since Linux 2.2.8) CPU number last executed on.

(from man proc)
(edit: looks like -6 = 39 after all, sorry for not noticing that :-P )

A: Parsing the /proc/[pid]/stat files is a bit tricky, because you can have embedded spaces and parentheses in the file name. These are not escaped in any way.
To see the very real effects, run
cp /bin/cat ') fake (' && './) fake (' < /proc/self/stat && rm -f ') fake ('

The correct procedure is to take everything up to but not including the first occurrence of " (" as pid, the process ID. Everything up to but not including the last occurrence of ") " is comm, the filename of the process executable. (None of the other fields are string-type, so you should not see any parentheses elsewhere in the file.) All the following fields are separated by spaces, and are listed in man 5 proc, under /proc/[pid]/stat. The processor is the 37th field following comm, or 39th field overall. (On Ubuntu 3.8.0-25-generic on x86-64, the field is 14th counting backwards from the end, not sixth -- but that is subject to change, as new fields can always be added to the end.)
If you limit yourself to Linux 2.6.26 and later (including all 3.x.y versions and later), then you could just look at the Cpus_allowed_list: line in /proc/[pid]/status instead. It's easier to parse, and tells which cores the kernel will allow the process to run, not just which CPU the process last ran on (which the processor field in /proc/[pid]/stat describes).
Hope this helps.


text:
Q: dataframe to save csv: not accumulating the records only saving the last dataframe group records dataframe question in web scraping data group
example:the first loop-eg:5 records, second loop-eg:3 records
when I did my below code, the csv file was saved the second loop group without stacking from the first loop group records. please advise me.
df=[]
for i in range(1,3,1):
    state=driver.find_element(By.XPATH, "//select[@name='state']")
    stateDD=Select(state)
    stateDD.select_by_index(i)
    time.sleep(3)
    print(f'Getting page, {i}')

    soup = BeautifulSoup(driver.page_source,'lxml')

    data=[]
    for card in soup.select('#resultscontainer > ul > li > div.repcontent'):
        state = i
        company = card.select_one('h3.company_title').text
        #print(company)
        address = card.select_one('div.address').text
        address2 = card.select_one('div.address2').text
        try:
            phone = card.select('span')[0].text
        except IndexError:
            phone = ""
        try:
            fax = card.select('span')[1].text
        except IndexError:
            fax = ""
        data.append({
            'state': state,
            'company':company,
            'address':address,
            'address2':address2,
            'phone':phone,
            'fax':fax
            })

    #print(data)

        df = pd.DataFrame(data)
        #print(df.head())
        df.to_csv('D:/92Python/Output/gastite.csv', index=False)
driver.close


text:
Q: How do I split arguments with Ruby and Thor? I've been learning Ruby and using Thor in a self-project and I would like to know, how do I split arguments using Thor. For example:
scaffold Post name:string title:string content:text

I would like to know how to split name:string, title:string and content:text into an object array with "name" and "type".

A: Consider you have a file scaffold.rb with following contents:
array = ARGV.map { |column_string| column_string.split(":").first }
puts array.inspect # or 'p array'

Then, if we run ruby scaffold.rb name:string title:string content:text, you will get
["name", "title", "content"]

If our code was p ARGV, then output will be ["name:string", "title:string", "content:text"]. So, we will get whatever we pass after, ruby scaffold.rb as an array split by space in ARGV variable inside the code. We can manipulate this array as we wish, inside the code.
Disclaimer: I dont know Thor, but wanted to show how this is done in Ruby

A: My recommendation would be to use whatever Rails uses so you're not reinventing the wheel. I dug around a little in the generator source and found that rails is using a GeneratedAttribute class to convert the arguments to objects.
From the generator named_base source you'll see they are splitting the arguments on ':' and passing those to Rails::Generators::GeneratedAttribute:
def parse_attributes! #:nodoc:
  self.attributes = (attributes || []).map do |key_value|
    name, type = key_value.split(':')
    Rails::Generators::GeneratedAttribute.new(name, type)
  end
end

You don't have to use the GeneratedAttribute class, but it's there if you want it.

A: "your:string:here".split(":") => ["your", "string", "here"]


text:
Q: Get selectedIndex from a dropdown list on submit This is my first web page ever and I can't seem to find the correct way to get the selected index from a dropdown list. I don't need the selected index until the user presses the submit button.  I've been testing everything I've found on the subject, but nothing is working.
I don't want the drop-down box to reset when the selection is made, which is what happens if I use postback=true or any selected index changed events.  And, I still get an index of 0.
When I test, the selected index is always zero.
This runs on page load:
 ddlBudgetLineItem.DataSource = budget.BudgetLineItems;
 ddlBudgetLineItem.DataTextField = "Name";
 ddlBudgetLineItem.DataValueField = "BudgetLineItemID";
 ddlBudgetLineItem.DataBind();

This is the drop-down list:
<asp:DropDownList ID="ddlBudgetLineItem" runat="server">
            </asp:DropDownList>

Here is the code that needs the index:
protected void submitPayment()
    {
        string amountValue = txtAmount.Text.ToString();

        float amount = float.Parse(amountValue);

        Payment payment = new Payment()
        {
            Amount = amount,
            Payee = txtPayee.Text,
            BudgetLineItem = budget.BudgetLineItems[ddlBudgetLineItem.SelectedIndex],
            Memo = txtMemo.Text,
            PaymentDate = DateTime.Parse(txtPaymentDate.Text),
            ExtraUserInfo = info
        };

        provider.AddPayment(payment);
    }

Any assistance is appreciated.

A: it seems to be a life cycle issue, this is happening because everytime  (on a postback or not) the page is loaded, your dropdown is rebuilt (caused by ddlBudgetLineItem.DataBind()), concluding that on a postback your ddl will get index=0 forever.
how can you solve this:
1: Override the page databind method and put your code before call base.databind(); (inside the method)
2: on your load event you just have to call databind (if not is postback), it prevent to rebuild your object states everytime your page is loaded.(cause of your lost information).
3: take a look on a page lifecycle it will help you to prevent future issues like that.


text:
Q: Confused refreshing Angular custom directive / communicating between adjacent directives I am two weeks into Angular. I have watched several Pluralsite videos and read several post and this has resulted in great progress but also some confusion. I want to notify one directive of some change in another directive. Then refresh the directive. In other words it needs to go back to the server with the selection from the first and pull the appropriate data.
I have read about eventing and things like $watch() but then I have seen others say to avoid watch and to use $emit and $on. I have even seen one article say to use transclusion.
I have access to Pluralsight and other resources. I will self educate if someone could just point my nose in the right direction.
My directive markup html:

    <dashboard-main-nav></dashboard-main-nav>

  <dash-select ng-show="vm.isDashSelectionVisible">Selections</dash-select>

My app declaration: NOTE I know I need to get the parm from scope but not sure how...
(function ()
 {
    "use-strict";
    ...snip controller setup etc..

    .directive("dashboardMainNav", function () {
        return {
            restrict: "E",
            templateUrl: "/Navigation/GetDashItems",
            scope: true
        }
    })
     .directive("dashSelect", function () {
         return {
             restrict: "E",
             templateUrl: "/Navigation/GetDashSelections/:" + $scope.??,
             scope: true
         }
     });
})();

routingController:
(function () {
    ...snip...
    function routingController($http, $scope) {
        var vm = this;
        var isDashSelectionVisible = false;
        var dashSelectionId = 0;

        $scope.LetterSearch= function (dashSelId) {
            vm.isDashSelectionVisible = true;
            vm.dashSelectionId = dashSelId;
            alert("Letters Clicked: " + dashSelId);
        }
    }
})();

Rendered HTML:
<dashboard-main-nav>
    ....snip....
   Letters
</dashboard-main-nav>

..... snip.....

<dash-select>
   Numbers
</dash-select>

I am not showing the $routeProvider config that wires up the routingController as that works fine. I just need to get that custom directive  to grab the parm from scope..refresh then update the dom.
Thank You for your patience and knowledge sharing.