Thursday, October 31, 2019

Asynchronous Javascript Variable Overwrite



The code has an issue that the variable gets over written when the asynchronous function is called. How can it be fixed?



Code:



for (x in files) {

asynchronousFunction(var1, var2, function(){

console.log(x.someVaraible);
});

}


Now the issue is that when the callback function in the asynchronousFunction is called the x.files variable has been updated to the next varaible in the json array files. I want that the variable should contain the previous value.



The number of variables in the callback function can not be changes, so variable name can not be sent in the call back function.


Answer




The problem wtih using 'local' variables in javascript is that your variables actually have function scope, rather than block scope - like java and c# etc has



One way to get around this is using let which has block scope, but only firefox supports this currently.



So this code would work in firefox only :



for (var x in files) {
// This variable has BLOCK scope
let file = files[x];
asynchronousFunction(var1, var2, function(){

console.log(file.someVaraible);
});
}


For other browsers, the alternative is to use closures



for (var x in files) {
var file = files[x];
asynchronousFunction(var1, var2, (function(file){

return function() {
console.log(file.someVaraible);
};
})(file);
}


Another way you could do this is using map/forEach, assuming that the datatype of files is an array.



files.forEach(function(file) {

asynchronousFunction(var1, var2, function(){
console.log(file.someVaraible);
});
});


If it's not an array, then you can always use this technique



 [].forEach.call(files, function(file) {
asynchronousFunction(var1, var2, function(){

console.log(file.someVaraible);
});
});


The fuller way of writing this is of course



Array.prototype.forEach.call(files, function(file) {
// As before



But I feel [].forEach is nicer on the eyes


Java Scanner Class

I am writing a program that should close the console if the user input the String "end'.
The program always performs the else loop even if the user inputs "end". I'm wondering why the program is not getting into the if part of the loop and shutting down.



Scanner scan = new Scanner(System.in);
while(true)
{
String num = scan.nextLine();


if(num == "end")
{
System.exit(0);
}
else
{
System.out.println("hi");
}
}

How can I create a two dimensional array in JavaScript?



I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.





  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)


  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)



Answer





var items = [
[1, 2],

[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);





character - Why was there no hint of the Joker? - Movies & TV




In Dark Knight Rises, we see a bit of history of what has happened to Gotham in the past 8 years.



Batman in seclusion, criminals being locked up for being part of organized crime, and Gordon's guilt from what happened with Dent.



However, there seems to be absolutely no mention of the Joker at all during the movie, not even a hint at what happened to him after being apprehended. In comparison, Crane has been seen across all three movies and given some sort of wrap-up.



Granted, it is a tad hard to film anything new with the death of the actor.



But is there any reason Nolan gave on why he wouldn't at least give us a visual hint at the Joker being locked up (example being a pan across a door reading EXTREMELY DANGEROUS) or him escaping into hiding (example: Gordon saying to a fellow officer that "The Madman still got away")?


Answer




As per this link:




Director Christopher Nolan decided against referencing Heath Ledger's The Joker character in the new Batman film, insisting acknowledging the "real-life tragedy" of the late star was "inappropriate"....
He explains, "We're not addressing The Joker at all. That is something I felt very strongly about in terms of my relationship with Heath and the experience I went through with him on The Dark Knight. I didn't want to in any way try and account for a real-life tragedy. That seemed inappropriate to me. We just have a new set of characters and a continuation of Bruce Wayne's story, not involving The Joker."



passwords - Windows 7 unable to log in

I have a laptop that is running Windows 7 (had it for a couple of years).


Recently, I turned it on, and was presented with the Windows log in screen as usual. However, despite entering my password correctly (I have checked several times), I am unable to log in to Windows- a message is displayed telling me that my password is incorrect... even though I know that it's not.


I had a quick Google about this, and it seems that it's not an uncommon problem with Windows, however, all of the solutions I've found seem to indicate that I will need to reinstall Windows.


There are some files on the laptop that I do not want to lose, so I was wondering if anyone knows if it's possible to 'bypass' the Windows log in, and access the hard drive some other way?


I know that this should theoretically be possible, but have no idea how to do it- can anyone tell me?


Thanks in advance!

java - Incompatible types. Required: short, Found: int





I just can't understand the difference between this:



short d = 0;

//some code
node.accessible = d + 1;



and this



short d = 0
//same code here
node.accessible = d;
node.accessible += 1;




the second thing is working, but the 1st one is't inteliji showes "incompatiable types" error.



p.s. node class:



public class Node {
int n;
short accessible;
Node(int n){
this.n = n;
this.accessible = -1;

}
}

Answer



In the first version :



node.accessible = d + 1;


d + 1 produces a int as summing an int and a short produces an int.
The JLS states indeed that (look at the last case, emphasis is mine) :





5.6.2. Binary Numeric Promotion



When an operator applies binary numeric promotion to a pair of
operands, each of which must denote a value that is convertible to a
numeric type, the following rules apply, in order:




  1. If any operand is of a reference type, it is subjected to unboxing

    conversion (§5.1.8).


  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:




    • If either operand is of type double, the other is converted to double.


    • Otherwise, if either operand is of type float, the other is converted
      to float.


    • Otherwise, if either operand is of type long, the other is converted
      to long.


    • Otherwise, both operands are converted to type int.







But you cannot assign a int to the accessible field that is a short without explicit cast as int has a broader range than short.






While in the second version, a Compound Assignment Operators is used (+=):




node.accessible += 1;


As a consequence, in your case the result of the operation is converted to short : the type of the left-hand variable as the JLS states :




15.26.2. Compound Assignment Operators



A compound assignment expression of the form E1 op= E2 is equivalent
to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1

is Evaluations only once.




And more specifically in your case :




Otherwise, the result of the binary operation is converted to the type
of the left-hand variable, subjected to value set conversion (§5.1.13)
to the appropriate standard value set (not an extended-exponent value
set), and the result of the conversion is stored into the variable.




Where is the "Enable UEV" setting in Windows 10 Group Policy?



I cannot locate the GPO setting for enabling UEV for Windows 10 1607+. I would like to enable this setting so the default UEV service is enabled on our deployments.




  • We have the latest admx files from MS for UEV (UserExperienceVirtualization.admx 25/04/2017)

  • I am using the Win10 RSAT tools on a Win10 LTSB (don't ask) deployment.

  • I can see the "Enable UEV" settings through local group policy on the PC.




When navigating to the appropriate GPO area (Computer Configuration > Administrative Templates > Windows Components > Microsoft User Experience Virtualization), the "Enable UEV" settings does not exist.



I have researched the MS documentation which doesn't explain why it would be missing. Other sites do not seem to reference this issu, all sites simply say that the setting should be set and assume that it is available. It seems I meet all criteria I can find to have access to this setting, but clearly I must be missing something.


Answer



I eventually found the information required: https://social.technet.microsoft.com/wiki/contents/articles/35333.ue-v-important-changes-in-ue-v-functionality-after-the-windows-10-anniversary-update.aspx




The Group Policy ADMX for UE-V is included in Windows 10 Anniversary update. You can find the file in C:\Windows\PolicyDefinitions\UserExperienceVirtualization.admx. See Configuring UE-V with Group Policy Objects Jump for more details.




The Anniversary Update introduces support for Microsoft Office 2016 templates, as well as a new value named EnableUEV.




So it would seem the ADMX templates provided with MDOP appear to be more for Windows versions lower than 1607 (read Win 7/8). Therefore, as above, for 1607+, you need to copy the ADMX file from Windows 10 itself to have full GPO settings available.


'credits' tag wiki - Movies & TV



The listing at the beginning or ending of a film/tv show that displays all people involved in producing the project.




The listing at the beginning or ending of a film/tv show that displays all people involved in producing the project.




Wikipedia Page: Closing Credits

php - How can I escape single quotes in this scenario?

I have a page which makes a jquery call to an api to receive multiple wikipedia urls. I then

extract the article names from the url (i.e. get science from http://en.wikipedia.org/science etc), add single quotes (') to each one, string them together and finally send them to a php page, which makes a mysql select * from MyTable where title in('name1','name2','name3','name4') call. The problem arises when the article name already has a single quote in it (i.e. "Hick's law"), as it breaks the where in single quotes. Here's the code I'm using:



$.getJSON('http://ajax.googleapis.com/ajax/services/search/web?q=keyword site:en.wikipedia.org&rsz=8&v=1.0&callback=?',
function (r) {
var urls1="";
$.each(r.responseData.results, function(i, item) {
var thisurl = (i==0) ? "'" + item.url.substring(item.url.lastIndexOf('/') + 1) + "'" : ",'" + item.url.substring(item.url.lastIndexOf('/') + 1) + "'";
urls1 += thisurl.replace(/_/g,'%20');

});});

$('#quotes').html($('
').load('pr.php?s='+urls1 +' #quotes', function() {}


I'm adding the single quotes to the article names so the string should be all ready to go for the mysql where in.



So to recap, the steps are as follows:




  1. Make an api call and get multiple Wikipedia urls,

  2. get the article name from each url,


  3. add them to the urls1 string while replacing underscores with spaces

  4. send the urls1 string via ajax to the pr.php page.

  5. In pr.php I do the following: "SELECT * FROM MyTable WHERE title in".$_GET['s']



I tried doing mysql_real_escape_string($_GET['s']) but that didn't work.



I'm now trying to escape any single quotes inside the article names so the where in doesn't break, but it's not working. I tried changing the above to



var thisurl=(i==0) ? "'"+item.url.substring(item.url.lastIndexOf('/') + 1).replace(/'/g, "\'")+"'":",'"+item.url.substring(item.url.lastIndexOf('/') + 1).replace(/'/g, "\'")+"'";



But it didn't work. Any ideas?



TIA!

RegEx to exclude a specific string constant

Can regular expression be utilized to match any string except a specific string constant let us say "ABC" ? Is this possible to exclude just one specific string constant? Thanks your help in advance.

java - The Use of Multiple JFrames: Good or Bad Practice?




I'm developing an application which displays images, and plays sounds from a database. I'm trying to decide whether or not to use a separate JFrame to add images to the database from the GUI.




I'm just wondering whether it is good practice to use multiple JFrame windows?


Answer




I'm just wondering whether it is good practice to use multiple JFrames?




Bad (bad, bad) practice.




  • User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..


  • A nightmare to code and maintain:


    • A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.

    • A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.








There are any number of ways of displaying many elements in one GUI, e.g.:




  • CardLayout (short demo.). Good for:


    1. Showing wizard like dialogs.

    2. Displaying list, tree etc. selections for items that have an associated component.

    3. Flipping between no component and visible component.



  • JInternalFrame/JDesktopPane typically used for an MDI.

  • JTabbedPane for groups of components.

  • JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.

  • JLayeredPane far many well ..layered components.

  • JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.

  • As items in a JList (simple example below).

  • As nodes in a JTree.

  • Nested layouts.




But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.



Many images



In this case where the multiple elements are images, it would be better to use either of the following instead:




  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.

  2. A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).





path - Git in Visual Studio 2013 stops working abruptly


Yesterday, I went home with Git working perfectly well inside Visual Studio 2013. I could 'Compare with unmodified' for a source file, I would see the version control status of my source files, and all the goodies of Git inside Visual Studio. I shut down my computer when I left work yesterday.


However, when I came to work this morning, as soon as I launched VS, I got this strange message from Git Version control saying,


'Path 'C:\' doesn't point at a valid Git repository or workdir.'

I proceeded to opening my project which is under Git version control, and strangely, Git did not recognize my project - None of the source files seemed to be added to version control, all the options such as to compare with unmodified version of a file were missing, it was as though the project was never under Git version control.


So, I did a system restore, and that got things working again. Now, when I launch Visual Studio, I get the following message from Git Version control


Opening repository: C:\Workspace\Dev\

This path is the path for where my source code is situated.


Can you please think of what could be messing up Git-Visual Studio integration so abruptly?


P.S. I am on VS 2013, so I did not install any external Git extensions, I am using the one that comes with VS 2013. This exact same problem has happened twice now. On both occsassions, I had to do a system restore to get things working back again.


Answer



Go to Team Explorer, then Connect to Team projects, choose anyone of the projects, and restart VS


Group columns into multiple rows and Group_concate like MySQL in SQL Server



I’ve been looking for a way to show one column in multiple rows, one cell. The content of it separated by comma’s.



For example, in stead of:





ProjectID Name count
-------------------------------------
2 Technical Services 31
1 Security Services 32
7 Technical Services 32


I would like the result of my query to look like this:





Name Label
---------------------------
Technical Services 31,2
Technical Services 32,7
Security Services 32,1


I also want the result of my query to look like this: (like Group_Concate in MySQL)





Name Label
-------------------------------
Security Services 32,1
Technical Services 31,2: 32,7

Answer



Try this:



SELECT  Name, 
CAST(count AS VARCHAR(10)) + ',' + CAST(ProjectID AS VARCHAR(10))

AS Label FROM table1


Result




NAME LABEL
----------------------------
Security Services 32,1
Technical Services 32,7

Technical Services 31,2




If you want to group by Name (Something like Group_Concate in MySQL) there is no any method for it in SQL Server. It's just a logic behind it.
So try this:



SELECT  * FROM    (
SELECT DISTINCT Name
FROM table1

) table2
CROSS APPLY
(SELECT CASE ROW_NUMBER()
OVER(ORDER BY ProjectId)
WHEN 1 THEN '' ELSE ': ' END +
(CAST(table3.count AS VARCHAR(10)) + ','
+ CAST(table3.ProjectID AS VARCHAR(10)) )
FROM table1 table3
WHERE table3.Name = table2.Name
ORDER BY ProjectID

FOR XML PATH ('')
) table3(Label)


So the result will be




NAME LABEL
--------------------------------
Security Services 32,1

Technical Services 31,2: 32,7



C# Converting Each Char to Byte Array

I am stuck with converting textbox string value to byte array.

For ex;



Textbox1.text="ABC";
converting to byte array as
byte[] array1;
array1[0]=65;
array1[1]=66;
array1[2]=67;



Then I want to write all array1 to Textbox2 as



Textbox2=656667


Shortly, Input is "ABC" Ouput is "656667".
I am working with below codes it gives error at



int value = Int32.Parse(arrText[i], System.Globalization.NumberStyles.Number);



sample code



string text = textBox1.Text + " ";// .Text + " ";
text.Trim();
string[] arrText = text.Split(' ');
byte[] data = new byte[arrText.Length];
for (int i = 0; i < arrText.Length; i++)
{
if (arrText[i] != "")

{
int value = Int32.Parse(arrText[i],
System.Globalization.NumberStyles.Number); //gives error
data[i] = (byte)Convert.ToByte(value);
}
}

for (int i = 0; i < arrText.Length; i++)
{
textBox2.Text += data[i].ToString();

}

Swift Beta performance: sorting arrays



I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:



let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0.. x[i] = random()
}
// start clock here
let y = sort(x)
// stop clock here


In C++, a similar operation takes 0.06s on my computer.



In Python, it takes 0.6s (no tricks, just y = sorted(x) for a list of integers).



In Swift it takes 6s if I compile it with the following command:



xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`


And it takes as much as 88s if I compile it with the following command:



xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`


Timings in Xcode with "Release" vs. "Debug" builds are similar.



What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.






Edit: weather noticed that changing -O3 to -Ofast makes this code run almost as fast as the C++ version! However, -Ofast changes the semantics of the language a lot — in my testing, it disabled the checks for integer overflows and array indexing overflows. For example, with -Ofast the following Swift code runs silently without crashing (and prints out some garbage):



let n = 10000000
print(n*n*n*n*n)
let x = [Int](repeating: 10, count: n)
print(x[n])


So -Ofast is not what we want; the whole point of Swift is that we have the safety nets in place. Of course, the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases, the slowdown is by a factor much less than 2. And in Clang and GCC we have got -ftrapv for checking (signed) integer overflows, and it is not that slow, either.



Hence the question: how can we get reasonable performance in Swift without losing the safety nets?






Edit 2: I did some more benchmarking, with very simple loops along the lines of



for i in 0..    x[i] = x[i] ^ 12345678
}


(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also "harmless" in the sense that it should not require any checks related to integer overflows.)



Again, there was a huge difference in the performance between -O3 and -Ofast. So I had a look at the assembly code:




  • With -Ofast I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.


  • With -O3 I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of "callq _swift_retain" and another 13 invocations of "callq _swift_release". That is, 26 subroutine calls in the inner loop!







Edit 3: In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:



let n = 10000
var x = [Int](repeating: 1, count: n)
for i in 0.. for j in 0.. x[i] = x[j]
}
}


There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by a factor almost 500 in comparison with -Ofast:




  • C++ -O3: 0.05 s

  • C++ -O0: 0.4 s

  • Java: 0.2 s

  • Python with PyPy: 0.5 s

  • Python: 12 s

  • Swift -Ofast: 0.05 s

  • Swift -O3: 23 s

  • Swift -O0: 443 s



(If you are concerned that the compiler might optimize out the pointless loops entirely, you can change it to e.g. x[i] ^= x[j], and add a print statement that outputs x[0]. This does not change anything; the timings will be very similar.)



And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be much slower than unoptimized Swift. Something seems to be seriously broken with Swift and array indexing.






Edit 4: These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.



For sorting, I now have the following timings:




  • clang++ -O3: 0.06 s

  • swiftc -Ofast: 0.1 s

  • swiftc -O: 0.1 s

  • swiftc: 4 s



For nested loops:




  • clang++ -O3: 0.06 s

  • swiftc -Ofast: 0.3 s

  • swiftc -O: 0.4 s

  • swiftc: 540 s



It seems that there is no reason anymore to use the unsafe -Ofast (a.k.a. -Ounchecked); plain -O produces equally good code.


Answer



tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].






Here is an in-place quicksort in Swift Beta:



func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}


And the same in C:



void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}


Both work:



var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]

quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))

// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]


Both are called in the same program as written.



var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}

let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();

let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();


This converts the absolute times to seconds:



static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;

mach_timebase_info_data_t timebase_info;

uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}

double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}


Here is a summary of the compiler's optimazation levels:



[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.


Time in seconds with [-Onone] for n=10_000:



Swift:            0.895296452
C: 0.001223848


Here is Swift's builtin sort() for n=10_000:



Swift_builtin:    0.77865783


Here is [-O] for n=10_000:



Swift:            0.045478346
C: 0.000784666
Swift_builtin: 0.032513488


As you can see, Swift's performance improved by a factor of 20.



As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:



Swift:            0.000706745
C: 0.000742374
Swift_builtin: 0.000603576


And for n=1_000_000:



Swift:            0.107111846
C: 0.114957179
Swift_sort: 0.092688548


For comparison, this is with [-Onone] for n=1_000_000:



Swift:            142.659763258
C: 0.162065333
Swift_sort: 114.095478272


So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.



It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:




A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.




They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.



BETA 3 UPDATE:



n=10_000 with [-O]:



Swift:            0.019697268
C: 0.000718064
Swift_sort: 0.002094721


Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.



FINAL UPDATE:



[-Onone]:



Swift:   0.678056695
C: 0.000973914


[-O]:



Swift:   0.001158492
C: 0.001192406


[-Ounchecked]:



Swift:   0.000827764
C: 0.001078914

How to include a PHP file inside WordPress php template?



This is the code I have inside php tags:



include('/wp-content/custom-php/numberedSteps.php'); 


And I get this error:




Warning: include(/wp-content/custom-php/numberedSteps.php): failed to open stream:



No such file or directory in /home/user/public_html/website.com/wp-content/themes/flatsome/woocommerce/archive-product.php on line 85



Warning: include(): Failed opening '/wp-content/custom-php/numberedSteps.php' for inclusion (include_path='.:/usr/local/php56/pear') in /home/user/public_html/website.com/wp-content/themes/flatsome/woocommerce/archive-product.php on line 85




How can this error be fixed?


Answer



try getting the root path first



for PHP >= 5.3.0 try



include(__DIR__.'/wp-content/custom-php/numberedSteps.php');


For PHP < 5.3.0 try



include(dirname(__FILE__).'/wp-content/custom-php/numberedSteps.php');

regex - Regular expression to extract text between square brackets



Simple regex question. I have a string on the following format:



this is a [sample] string with [some] special words. [another one]



What is the regular expression to extract the words within the square brackets, ie.



sample
some
another one


Note: In my use case, brackets cannot be nested.


Answer



You can use the following regex globally:




\[(.*?)\]


Explanation:




  • \[ : [ is a meta char and needs to be escaped if you want to match it literally.

  • (.*?) : match everything in a non-greedy way and capture it.

  • \] : ] is a meta char and needs to be escaped if you want to match it literally.



javascript - Both call and apply produce the same result for String.prototype.toUppercase when passing an array

I usually see that we should use an array in apply method and array of arguments in call method:




If I do the following (call method would return undefined):



var namelist = {
f:'first name',
l:'last name'
}
function func(a,b){
console.log(this[a]+' '+this[b])
}


func.call(namelist,['f','l'])
//undefined undefined

func.apply(namelist,['f','l'])
//first name last name


But, look here both call and apply method works:




String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C'
String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'


Why the call method is working?



If I do use like this:



String.prototype.toUpperCase.call('a','b','c')
//this would return 'A' only.

macos - Copy files from external hard drive that Disk Utility can't repair

I have a 2 Tb WD MyPassport Ultra external hard drive containing lots of important data, and a Macbook Pro running OS X 10.9.5. The harddrive fell while pulling down lots of data via wget, and now seems to be corrupted. I tried ejecting the drive (had to Force Eject because it thinks it's in use elsewhere) and rebooting my computer, but that didn't solve the problem. Here's the Disk Utility log:



2016-05-08 21:51:00 -0400: Verify and Repair volume “disk1s3”



2016-05-08 21:51:00 -0400: Starting repair tool:



2016-05-08 21:51:00 -0400: Checking file system




2016-05-08 21:51:39 -0400: Volume repair complete.



2016-05-08 21:51:39 -0400: Updating boot support partitions for the volume as required.



2016-05-08 21:51:52 -0400: Error: Disk Utility can’t repair this disk. Back up as many of your files as possible, reformat the disk, and restore your backed-up files.
2016-05-08 21:51:52 -0400:



2016-05-08 21:51:52 -0400: Disk Utility stopped repairing “disk1s3”: Disk Utility can’t repair this disk. Back up as many of your files as possible, reformat the disk, and restore your backed-up files.




Fine, I need to backup my files. The problem is that I can't copy any of the files on the disk -- when I try with cp on the command line, or with copy/paste in Finder, I get



Input/output error



and it creates a 0byte file with the name of whatever I was trying to copy. How can I safely copy the hard drive data somewhere so that I can reformat the disk?? Please give options other than buying some expensive data recovery software if at all possible.

Round number up in JavaScript

I have the following number




0.135


I'd like to round it to 2 decimal places, I'm using...



(newCostDiff/2).toFixed(2)


only this returns




0.13


Can anyvody advise me on how to do this?

Wednesday, October 30, 2019

html - How to mark-up phone numbers?



I want to mark up a phone number as callable link in an HTML document. I have read the microformats approach, and I know, that the tel: scheme would be standard, but is quite literally nowhere implemented.



Skype defines, as far as I know, skype: and callto:, the latter having gained some popularity. I assume, that other companies have either other schemes or jump on the callto: train.




What would be a best practice to mark-up a phone number, so that as many people as possible with VoIP software can just click on a link to get a call?



Bonus question: Does anyone know about complications with emergency numbers such as 911 in US or 110 in Germany?



Cheers,



Update: Microsoft NetMeeting takes callto: schemes under WinXP. This question suggests, that Microsoft Office Communicator will handle tel: schemes but not callto: ones. Great, Redmond!



Update 2: Two and a half years later now. It seems to boil down to what you want to do with the number. In mobile context, tel: is the way to go. Targeting desktops it's up to you, if you think your users are more Skype people (callto:) or will more likely have something like Google Voice (tel:) installed. My personal opinion is, when in doubt use tel: (in line with @Sidnicious' answer).




Update 3: User @rybo111 noted, that Skype in Chrome has meanwhile jumped on the tel: bandwagon. I cannot verify this, because no machine with both at hand, but if it's true, it means we have finally a winner here:



                                        tel:

Answer



The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.



callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.



Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .




Example:





javascript - How to decide when to use Node.js?




I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.js is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like Bitly - takes some content, archives it.




From all the homework I have been doing in the last few days, I obtained the following information. Node.js




  • is a command-line tool that can be run as a regular web server and lets one run JavaScript programs

  • utilizes the great V8 JavaScript engine

  • is very good when you need to do several things at the same time

  • is event-based so all the wonderful Ajax-like stuff can be done on the server side

  • lets us share code between the browser and the backend

  • lets us talk with MySQL




Some of the sources that I have come across are:





Considering that Node.js can be run almost out-of-the-box on Amazon's EC2 instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like PHP, Python and Ruby. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?


Answer



You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.




This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.



It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachine and twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.



I look forward to reading other answers here, this is a fantastic question.



It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor framework makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.



Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.


Android - android.view.InflateException: Binary XML file line #8: Error inflating class fragment



I am developing an app using a NavigationDrawer i.e. DrawerLayout and navigating to different Fragments. When I call a Map_Fragment_Page the application crashes, but not the first time. For the first time it displays the Map properly but after that when I navigate different fragments and again come to Map_Fragment_Page then it crashes giving an error android.view.InflateException: Binary XML file line #8: Error inflating class fragment




I tried so many different solutions and I also also searched on Google but still not getting the required solution. The problem is not yet fixed.



howtoreach.xml




xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">


android:id="@+id/howtoreach_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>




HowToReach.java




    package com.demo.map.howtoreach;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import android.support.v4.app.Fragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.demo.map.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


public class HowToReach extends Fragment
{
public static final String TAG = "fragment_5";
ProgressDialog dialog;

GoogleMap googleMap;
Marker marker;

LocationManager locationManager;

Location location;
Criteria criteria;
String provider;

double latitude, longitude;

public HowToReach(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

final View v = inflater.inflate(R.layout.howtoreach, container, false);

dialog = ProgressDialog.show(getActivity(),"","Loading",true,false);

int secondsDelayed = 4;
new Handler().postDelayed(new Runnable()
{
public void run()

{
dialog.dismiss();
}
}, secondsDelayed * 1000);

try
{
// Loading map

if (googleMap == null)

{
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.howtoreach_map)).getMap();

googleMap.setMyLocationEnabled(true);

locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);


latitude = location.getLatitude();
longitude = location.getLongitude();

// create marker
marker = googleMap.addMarker(new MarkerOptions().position(
new LatLng(latitude, longitude)).title("You are Here"));
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
marker.showInfoWindow();

CameraPosition cameraPosition = new CameraPosition.Builder().target(

new LatLng(latitude, longitude)).zoom(15).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Polyline line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude), new LatLng(18.520897,73.772396))
.width(2).color(Color.RED).geodesic(true));

marker = googleMap.addMarker(new MarkerOptions().position(
new LatLng(18.520897, 73.772396)).title("DSK Ranwara Road"));

marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

// check if map is created successfully or not
if (googleMap == null)
{
Toast.makeText(getActivity(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}

}

catch (Exception e)
{
e.printStackTrace();
}

return v;

}
}


Answer



Yes.. I want Map inside a Fragment.


You should use a MapView



http://developer.android.com/reference/com/google/android/gms/maps/MapView.html



public class HowToReach  extends Fragment {
MapView mapView;

GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, container, false);
// Gets the MapView from the XML layout and creates it

try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("Address Map", "Could not initialize google play", e);

}

switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) )
{
case ConnectionResult.SUCCESS:
Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView) v.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
if(mapView!=null)

{
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
}
break;
case ConnectionResult.SERVICE_MISSING:
Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();

break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
break;
default: Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
}





// Updates the location and zoom of the MapView

return v;
}

@Override
public void onResume() {
mapView.onResume();
super.onResume();
}

@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}

}


fragment2.xml




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


android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map" />




Update:




https://developers.google.com/android/reference/com/google/android/gms/maps/MapView#public-constructors


getMap() is deprecated. Use getMapAsync(OnMapReadyCallback) instead. The callback method provides you with a GoogleMap instance guaranteed to be non-null and ready to be used.


Can't see drop down list in Excel VBA

I've created a very simple drop down list in excel. It holds a sequence of integers loaded from a cell range (years). I need to read the selected value in vba. However I can't even seem to find the control!



I've tried



CboYear

Sheet2.CboYear
Worksheets("SheetName").CboYear


etc. etc.



From everywhere in VBA this control just doesn't exist. All the tutorials I find seem to assume that using just the control name will work.



I've tried the code in the sheet itself, the workbook, and a module, no luck.

c++ - How did this person code "Hello World" with Microsoft Paint?

I have just seen this within the past few days and cannot figure out how it works. The video I talk about is here:





It's the top rated answer from this question: Why was this program rejected by three compilers?



How is this bitmap able to show a C++ program for "Hello World"?

sql - How to list the tables in a SQLite database file that was opened with ATTACH?



What SQL can be used to list the tables, and the rows within those tables in a SQLite database file - once I have attached it with the ATTACH command on the SQLite 3 command line tool?


Answer



The .tables, and .schema "helper" functions don't look into ATTACHed databases: they just query the SQLITE_MASTER table for the "main" database. Consequently, if you used



ATTACH some_file.db AS my_db;


then you need to do



SELECT name FROM my_db.sqlite_master WHERE type='table';


Note that temporary tables don't show up with .tables either: you have to list sqlite_temp_master for that:



SELECT name FROM sqlite_temp_master WHERE type='table';

Typing characters with ANSI keyboard lacking the key these characters are located on

Many keyboard layouts in Europe are based on the ISO keyboard layout which looks like this.


enter image description here


In my language the <, > are located on the key next to left shift like this:


Note the less than/greater than key next to left shift!


The problem is that I am using an keyboard with ANSI mechanical layout. The ANSI mechanical layout does not have this key.


Notice the key right of left shift is missing


Notice that key next to left shift previously used for < and > is missing.


Is there any way to enter less than < and greater than > characters on this ANSI keyboard using an French AZERTY layout? Maybe through a AltGr combination?

python - How do I sort a dictionary by value?




I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.



I can sort on the keys, but how can I sort based on the values?




Note: I have read question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.


Answer



Python 3.6+



x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}


Older Python




It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.



For instance,



import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))



sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.



And for those wishing to sort on keys instead of values:



import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))


In Python3 since unpacking is not allowed [1] we can use




x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])


If you want the output as a dict, you can use collections.OrderedDict:



import collections

sorted_dict = collections.OrderedDict(sorted_x)


laptop - Adaptive brightness won't turn off

TL;DR: I’ve tried everything to disable adaptive brightness with no luck. Brightness changes according to what’s on screen.



Recently I bought a Dell Inspiron 3542, built on the Intel i7-4510U with Intel HD4400 graphics and also an nVidia 840M. The laptop is running Win 8.1.



My problem is that, when the laptop is running on battery, I can’t disable adaptive brightness, no matter what I try.




  • I have disabled adaptive brightness in the windows control panel, under advanced power plan settings.

  • I have disabled adaptive brightness in Intel’s graphics control panel. Ditto for nVidia.


  • I have disabled the Sensor Monitoring Service under windows services.

  • I’ve even tried uninstalling Intel’s and nVidia’s drivers.



When the laptop is plugged in, there’s no adaptive brightness. When the laptop runs on batteries, adaptive brightness kicks in.



I should note here that the screen brightness changes according to what is displayed on the screen, and not according to lighting conditions.



Of course the laptop’s drivers are updated to their latest versions. Even the BIOS is updated to the latest version.




I thought this would be a Windows problem, so I tried running Linux. Still the same. The screen will dynamically adjust its brightness. So it’s not a Windows issue. Maybe it’s the Intel driver exhibiting the same behavior on both OSes? (long shot)



Could it be the laptop screen has dynamic brightness built-in? Is there even such a thing for laptop screens? The screen is the LP156WHB-TPA1, made by LG Display Co. I’ve checked on the internet but can’t find any info on such a feature, if it exists.



Any help/ideas/suggestions with this issue will be most appreciated!



Thank you.

Undefined index: command in C:wamp64wwwWSMshopproducts.php on line 5

if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){

$pid=$_REQUEST['productid'];
addtocart($pid,1);
header("location:shoppingcart.php");
exit();
}


Notice: Undefined index: command in C:\wamp64\www\WSMshop\products.php on line 5
and that's the error, i do what i know can fix it, but nothing happen. Please help me. im still newbie in this. TIA

Autohotkey - toggle keys

I want to achieve this



  1. press "a" > output "a"

  2. press "a" again > output "b"

  3. press "a" again > output "a"

  4. press "a" again > output "b"

  5. keep repeating these...


Below script does what I want, but with little issue.
When I press and hold "a", it output "abababab"......
But I need it to act like keep outputing the current character until I release the key and activate the toggling.


i.e. press and hold "a" > output "aaaaaaaa"... > release "a" > stop outputing and toggle to "b"


Anyone know how can I achieve that? Thanks in advance!


Toggle:=0
$a::
Toggle:=!Toggle
if(Toggle=1) {
send, a
} else {
send, b
}
return

'resident-evil' tag wiki - Movies & TV



Resident Evil is a sci-fi/horror zombie franchise based on a Capcom video game. Use this tag for both the 2002 movie and the franchise as a whole.




Resident Evil is a sci-fi/horror zombie franchise based on a 1996 Capcom video game. First released in 2002, it was the beginning of a series of live action and animated Resident Evil films that feature characters from the video game in a post-apocalyptic battle against the evil Umbrella Corporation and the T-virus the company developed.




The film series is comprised of six movies so far:

Tuesday, October 29, 2019

vba - Excel Looping through rows and copy cell values to another worksheet

I am facing some difficulty in achieving the desired result for my macro.



Intention:



I have a list of data in sheets(input).column A (the number of rows that has value will vary and hence I created a loop that will run the macro until the activecell is blank).



My macro starts from Range(A2) and stretches all the way down column A, it stops only when it hits a blank row




Desired result for the macro will be to start copying the cell value in sheet(input).Range(A2) paste it to sheet(mywork).Range(B2:B6).



For example, if "Peter" was the value in cell sheet(input),range(A2) then when the marco runs and paste the value into sheet(mywork) range(B2:B6). ie range B2:B6 will reflect "Peter"



Then the macros loop back to sheet(input) & copy the next cell value and paste it to range(B7:B10)



Example: "Dave" was the value in sheet(input) Range(A3), then "Dave" will be paste into the next 4 rows in sheet(mywork).Range(B7:B10). B7:B10 will reflect "Dave"



Again repeating the same process goes back to sheet(input) this time range(A4), copys the value goes to sheet(mywork) and paste it into B11:B15.




Basically the process repeats....



The macro ends the when the activecell in sheet(input) column A is empty.



Sub playmacro()
Dim xxx As Long, yyy As Long
ThisWorkbook.Sheets("Input").Range("A2").Activate
Do While ActiveCell.Value <> ""
DoEvents
ActiveCell.Copy

For xxx = 2 To 350 Step 4
yyy = xxx + 3
Worksheets("mywork").Activate
With ActiveSheet
.Range(Cells(xxx, 2), Cells(yyy, 2)).PasteSpecial xlPasteValues
End With
Next xxx
ThisWorkbook.Sheets("Input").Select
ActiveCell.Offset(1, 0).Activate
Loop

Application.ScreenUpdating = True
End Sub

linux - How can I print two small files on the same page with a2ps?

I'm using Ubuntu Linux 12.0.4.1 LTS and I like the auto-formatting that a2ps does. I just want to print several small files using as few pages as possible.
Example: a2ps file1.c file2.c file3.c file4.c
These will print out (depending on printer settings) on their four separate pages, or on opposite sides of two two-sided pages, like this:


--- page 1---


side 1: file1.c text blank column


side 2: file2.c text blank column


--- page 2 ---


side 1: file3.c text blank column


side 2: file4.c text blank column


I want to have them all on one sheet of paper:


--- page 1 ---


side 1: file1.c text file2.c text


side 2: file3.c text file4.c text

windows - Boot error after upgrading to W10, tried to fix it with a W7 disc, think I screwed up


I recently upgraded my father's laptop from Windows 7 to Windows 10. A few days later he tells me Windows won't start.


I get a "The Windows Boot Configuration Data file is missing required information" screen.


Since I only had the original Windows 7 installation disc, I tried to repair the boot with it. Did the usual bootrec commands (fixboot, fixmbr, rebuildbcd) and got the same error again. Booted from the disc again and it listed both Windows 10 and Windows 7 as available systems, and bootrec /rebuildbcd now returns 0 available operating systems.


How can I fix this now?


Answer



I recommend reinstalling windows 10, you should be able to create a installation disk by using the Media creation tool directly from the windows website Here. If you simply reinstall over it you shouldn't lose any data on your computer. I hope this helps.


javascript - jQuery - dynamically generated children dont trigger click




my code:



$(".test1").children().click(function(){
$(".test2").append('something');

});

$(".test2").children().on('click', function(){
alert("done");
});


the span with "something" should be the last child of test2 after clicking children of test1.
is my append done right? is the click event on test2 done correctly?




thx!


Answer



this works:



$(".test1").children().click(function(){
$(".test2").append(' something');
});

$(".test2").on('click', 'span', function(){
alert("done");

});


live demo


error LNK2001: unresolved external symbol (C++)

Say I have this function called DoThis(const char *abc) in a file called one.cpp. So when I attempt to call this function from another function in a different source file (two.cpp), I get the error: error LNK2001: unresolved external symbol (C++), even though I used #include "one.h" What would I do to fix this?

java - "Unfortunately app has stopped working " Android Studio





Please i am trying to change my launcher Activity to an authentication Activity i just developed using twitter digits, i already made the necessary adjustment in my android manifest and java code but noticed that the app keeps crashing each time i attempt to launch,the name of the authentication Activity is AboutAcivity.java, during the debugging session, i observed from my android monitor console that this line highlighted in blue at com.close.close.AboutActivity.onCreate(AboutActivity.java:34)

always point to setContentView(R.layout.activity_about); i have inspected that layout and find nothing wrong, i guess i need a third eye to help crush this annoying bug, Note, i already reviewed other staackoverflow questions but the solution there did not work for me. Thank you.



here is my manifest:





package="com.close.close"
android:versionCode="1"
android:versionName="1.0">

android:minSdkVersion="16"
android:targetSdkVersion="19"/>







android:name="android.permission.CAMERA"
android:required="true"/>







android:allowBackup="true"
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:theme="@style/CustomActionBarTheme">

android:name=".MessageService"
android:enabled="true"/>

android:name=".AboutActivity"
android:label="@string/app_name">








android:name="io.fabric.ApiKey"
android:value="34308698bb3cbc96444f2ff10ad1ae167d75d8e9"/>









android:name=".ChatActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_chat"
android:launchMode="singleTop">


android:name=".ViewImageActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_view_image"
android:parentActivityName=".ChatActivity"
android:theme="@style/FullscreenTheme">

android:name=".RecordAudioActivity"

android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_record_audio"
android:parentActivityName=".ChatActivity">

android:name=".PlayVideoActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_play_video">


android:name=".FilePickerActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_file_picker"
android:parentActivityName=".ChatActivity">

android:name=".WebViewActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_web_view"
android:parentActivityName=".ChatActivity">











android:name=".DrawingActivity"
android:label="@string/title_activity_drawing">







Here is the AboutActivity code




import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.digits.sdk.android.AuthCallback;
import com.digits.sdk.android.Digits;

import com.digits.sdk.android.DigitsAuthButton;
import com.digits.sdk.android.DigitsException;
import com.digits.sdk.android.DigitsSession;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterCore;

import io.fabric.sdk.android.Fabric;

public class AboutActivity extends AppCompatActivity {







@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new Digits.Builder().build());

setContentView(R.layout.activity_about);





DigitsAuthButton digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);

digitsButton.setCallback(new AuthCallback() {
@Override

public void success(DigitsSession session, String phoneNumber) {
// TODO: associate the session userID with your user model
Toast.makeText(getApplicationContext(), "Authentication successful for "
+ phoneNumber, Toast.LENGTH_LONG).show();

Intent intent=new Intent(AboutActivity.this,Profile_info.class); // redirecting to LoginActivity.
startActivity(intent);

}


@Override
public void failure(DigitsException exception) {
Log.d("Digits", "Sign in with Digits failure", exception);
}
});



}
}



Here is my log cat



java.lang.RuntimeException: Unable to start activity ComponentInfo{com.close.close/com.close.close.AboutActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2348)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5348)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)

at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.close.close.AboutActivity.onCreate(AboutActivity.java:34)
at android.app.Activity.performCreate(Activity.java:6012)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 

at android.app.ActivityThread.main(ActivityThread.java:5348) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372)


Here is my activity_about.xml




xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FD579D"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.close.close.AboutActivity"
android:orientation="horizontal">



android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="28dp"
android:gravity="center_horizontal"
android:text="@string/welcome"
android:textColor="#FFFFFF"

android:textSize="37sp"/>

android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:gravity="center_horizontal"
android:text="@string/to"

android:textColor="#FFFFFF"
android:textSize="37sp"/>

android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="128dp"
android:gravity="center_horizontal"

android:text="@string/close"
android:textColor="#FFFFFF"
android:textSize="37sp"/>
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="189dp"
android:gravity="center_horizontal"

android:text="@string/about"
android:textColor="#FFFFFF"
android:textSize="18sp"/>

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="50dp"
android:weightSum="1"

android:layout_marginStart="164dp"
android:layout_below="@+id/textView4"
android:layout_alignParentStart="true">





android:id="@+id/auth_button"

android:layout_width="148dp"
android:layout_height="48dp"
android:background="@drawable/dgts__digits_btn"
android:orientation="vertical"
android:layout_marginTop="54dp"
android:layout_below="@+id/textView4"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>





Answer



Change this



public class AboutActivity extends AppCompatActivity {


to this




public class AboutActivity extends Activity {

r faq - How to make a great R reproducible example





When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on Stack Overflow, a reproducible example is often asked and always helpful.



What are your tips for creating an excellent example? How do you paste data structures from in a text format? What other information should you include?



Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc.?



How does one make a great reproducible example?



Answer



A minimal reproducible example consists of the following items:




  • a minimal dataset, necessary to demonstrate the problem

  • the minimal runnable code necessary to reproduce the error, which can be run on the given dataset

  • the necessary information on the used packages, R version, and system it is run on.

  • in the case of random processes, a seed (set by set.seed()) for reproducibility1




For examples of good minimal reproducible examples, see the help files of the function you are using. In general, all the code given there fulfills the requirements of a minimal reproducible example: data is provided, minimal code is provided, and everything is runnable. Also look at questions on with lots of upvotes.



Producing a minimal dataset



For most cases, this can be easily done by just providing a vector/data frame with some values. Or you can use one of the built-in datasets, which are provided with most packages.
A comprehensive list of built-in datasets can be seen with library(help = "datasets"). There is a short description to every dataset and more information can be obtained for example with ?mtcars where 'mtcars' is one of the datasets in the list. Other packages might contain additional datasets.



Making a vector is easy. Sometimes it is necessary to add some randomness to it, and there are a whole number of functions to make that. sample() can randomize a vector, or give a random vector with only a few values. letters is a useful vector containing the alphabet. This can be used for making factors.



A few examples :





  • random values : x <- rnorm(10) for normal distribution, x <- runif(10) for uniform distribution, ...

  • a permutation of some values : x <- sample(1:10) for vector 1:10 in random order.

  • a random factor : x <- sample(letters[1:4], 20, replace = TRUE)



For matrices, one can use matrix(), eg :



matrix(1:10, ncol = 2)



Making data frames can be done using data.frame(). One should pay attention to name the entries in the data frame, and to not make it overly complicated.



An example :



set.seed(1)
Data <- data.frame(
X = sample(1:10),
Y = sample(c("yes", "no"), 10, replace = TRUE)
)



For some questions, specific formats can be needed. For these, one can use any of the provided as.someType functions : as.factor, as.Date, as.xts, ... These in combination with the vector and/or data frame tricks.



Copy your data



If you have some data that would be too difficult to construct using these tips, then you can always make a subset of your original data, using head(), subset() or the indices. Then use dput() to give us something that can be put in R immediately :



> dput(iris[1:4, ]) # first four rows of the iris data set
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,

3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")


If your data frame has a factor with many levels, the dput output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the the subset of your data. To solve this issue, you can use the droplevels() function. Notice below how species is a factor with only one level:



> dput(droplevels(iris[1:4, ]))

structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = "setosa",
class = "factor")), .Names = c("Sepal.Length", "Sepal.Width",
"Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")


When using dput, you may also want to include only relevant columns:




> dput(mtcars[1:3, c(2, 5, 6)]) # first three rows of columns 2, 5, and 6
structure(list(cyl = c(6, 6, 4), drat = c(3.9, 3.9, 3.85), wt = c(2.62,
2.875, 2.32)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710"
), class = "data.frame")


One other caveat for dput is that it will not work for keyed data.table objects or for grouped tbl_df (class grouped_df) from dplyr. In these cases you can convert back to a regular data frame before sharing, dput(as.data.frame(my_data)).



Worst case scenario, you can give a text representation that can be read in using the text parameter of read.table :




zz <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa"

Data <- read.table(text=zz, header = TRUE)



Producing minimal code



This should be the easy part but often isn't. What you should not do, is:




  • add all kind of data conversions. Make sure the provided data is already in the correct format (unless that is the problem of course)

  • copy-paste a whole function/chunk of code that gives an error. First, try to locate which lines exactly result in the error. More often than not you'll find out what the problem is yourself.




What you should do, is:




  • add which packages should be used if you use any (using library())

  • if you open connections or create files, add some code to close them or delete the files (using unlink())

  • if you change options, make sure the code contains a statement to revert them back to the original ones. (eg op <- par(mfrow=c(1,2)) ...some code... par(op) )

  • test run your code in a new, empty R session to make sure the code is runnable. People should be able to just copy-paste your data and your code in the console and get exactly the same as you have.



Give extra information




In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of sessionInfo() can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible also the necessary information on the setup.



If you are running R in R Studio using rstudioapi::versionInfo() can be helpful to report your RStudio version.



If you have a problem with a specific package you may want to provide the version of the package by giving the output of packageVersion("name of the package").






1 Note: The output of set.seed() differs between R >3.6.0 and previous versions. Do specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the RNGversion()-function before set.seed() (e.g.: RNGversion("3.5.2")).



hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...