Tuesday 31 December 2019

linux - In shell, split a portion of a string with dot as delimiter




I am new to shell scripting, can you please help with below requirement, thanks.



$AU_NAME=AU_MSM3-3.7-00.01.02.03
#separate the string after last "-", with "." as delimiter
#that is, separate "00.01.02.03" and print/save as below.
major=00
minor=01
micro=02
build=03

Answer



First, note that you don't use $ when assigning to a parameter in the shell. Your first line should be just this:



AU_NAME=AU_MSM3-3.7-00.01.02.03


Once you have that, then you can do something like this:



IFS=. read major minor micro build <${AU_NAME##*-}
EOF


where the ##*- strips off everything from the beginning of the string through the last '-', leaving just "00.01.02.03", and the IFS (Internal Field Separator) variable tells the shell where to break the string into fields.



In bash, zsh, and ksh93+, you can get that onto one line by shortening the here-document to a here-string:



IFS=. read major minor micro build <<<"${AU_NAME##*-}"


More generally, in those same shells (or any other shell that has arrays), you can split into an arbitrarily-sized array instead of distinct variables. This works in the given shells:



IFS=. components=(${AU_NAME##*-})


In older versions of ksh you can do this:



IFS=. set -A components ${AU_NAME##*-}


That gets you this equivalence (except in zsh, which by default numbers the elements 1-4 instead of 0-3):



major=${components[0]}
minor=${components[1]}
micro=${components[2]}
build=${components[3]}

javascript - Safely turning a JSON string into an object



Given a string of JSON data, how can I safely turn that string into a JavaScript object?




Obviously I can do this unsafely with something like:



var obj = eval("(" + json + ')');


but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.


Answer



JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.


c++ - Double free or corruption after queue::push



#include 
using namespace std;

class Test{
int *myArray;


public:
Test(){
myArray = new int[10];
}

~Test(){
delete[] myArray;
}


};


int main(){
queue q
Test t;
q.push(t);
}



After I run this, I get a runtime error "double free or corruption". If I get rid of the destructor content (the delete) it works fine. What's wrong?


Answer



Let's talk about copying objects in C++.



Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.



Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.



When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.




Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.



How do I fix it?



The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:



Test(const Test& other){
myArray = new int[10];
memcpy( myArray, other.myArray, 10 );
}



Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.



We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:



Test& operator= (const Test& other){
if (this != &other) {
memcpy( myArray, other.myArray, 10 );
}

return *this;
}


The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.


c# - .NET String.Format() to add commas in thousands place for a number



I want to add a comma in the thousands place for a number. String.Format()?


Answer



String.Format("{0:n}", 1234);  // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876

c++ - Fastest inline-assembly spinlock




I'm writing a multithreaded application in c++, where performance is critical. I need to use a lot of locking while copying small structures between threads, for this I have chosen to use spinlocks.



I have done some research and speed testing on this and I found that most implementations are roughly equally fast:




  • Microsofts CRITICAL_SECTION, with SpinCount set to 1000, scores about 140 time units

  • Implementing this algorithm with Microsofts InterlockedCompareExchange scores about 95 time units

  • Ive also tried to use some inline assembly with __asm {} using something like this code and it scores about 70 time units, but I am not sure that a proper memory barrier has been created.




Edit: The times given here are the time it takes for 2 threads to lock and unlock the spinlock 1,000,000 times.



I know this isn't a lot of difference but as a spinlock is a heavily used object, one would think that programmers would have agreed on the fastest possible way to make a spinlock. Googling it leads to many different approaches however. I would think this aforementioned method would be the fastest if implemented using inline assembly and using the instruction CMPXCHG8B instead of comparing 32bit registers. Furthermore memory barriers must be taken into account, this could be done by LOCK CMPXHG8B (I think?), which guarantees "exclusive rights" to the shared memory between cores. At last [some suggests] that for busy waits should be accompanied by NOP:REP that would enable Hyper-threading processors to switch to another thread, but I am not sure whether this is true or not?



From my performance-test of different spinlocks, it is seen that there is not much difference, but for purely academic purpose I would like to know which one is fastest. However as I have extremely limited experience in the assembly-language and with memory barriers, I would be happy if someone could write the assembly code for the last example I provided with LOCK CMPXCHG8B and proper memory barriers in the following template:



__asm
{
spin_lock:

;locking code.
spin_unlock:
;unlocking code.
}

Answer



Just look here:
x86 spinlock using cmpxchg



And thanks to Cory Nelson




__asm{
spin_lock:
xorl %ecx, %ecx
incl %ecx
spin_lock_retry:
xorl %eax, %eax
lock; cmpxchgl %ecx, (lock_addr)
jnz spin_lock_retry
ret


spin_unlock:
movl $0 (lock_addr)
ret
}


And another source says:
http://www.geoffchappell.com/studies/windows/km/cpu/cx8.htm




       lock    cmpxchg8b qword ptr [esi]
is replaceable with the following sequence

try:
lock bts dword ptr [edi],0
jnb acquired
wait:
test dword ptr [edi],1
je try
pause ; if available

jmp wait

acquired:
cmp eax,[esi]
jne fail
cmp edx,[esi+4]
je exchange

fail:
mov eax,[esi]

mov edx,[esi+4]
jmp done

exchange:
mov [esi],ebx
mov [esi+4],ecx

done:
mov byte ptr [edi],0



And here is a discussion about lock-free vs lock implementations:
http://newsgroups.derkeiler.com/Archive/Comp/comp.programming.threads/2011-10/msg00009.html


c++ - When do we need to define destructors?




I read that destructors need to be defined when we have pointer members and when we define a base class, but I am not sure if I completely understand. One of the things I am not sure about is whether or not defining a default constructor is useless or not, since we are always given a default constructor by default. Also, I am not sure if we need to define default constructor to implement the RAII principle (do we just need to put resource allocation in a constructor and not define any destructor?).



class A
{


public:
~Account()
{
delete [] brandname;
delete b;

//do we need to define it?

};


something(){} =0; //virtual function (reason #1: base class)

private:
char *brandname; //c-style string, which is a pointer member (reason #2: has a pointer member)
B* b; //instance of class B, which is a pointer member (reason #2)
vector vec; //what about this?




}

class B: public A
{
public something()
{
cout << "nothing" << endl;
}

//in all other cases we don't need to define the destructor, nor declare it?

}

Answer



The rule of Three and The Rule of Zero



The good ol' way of handling resources was with the Rule of Three (now Rule of Five due to move semantic), but recently another rule is taking over: the Rule of Zero.



The idea, but you should really read the article, is that resource management should be left to other specific classes.



On this regard the standard library provides a nice set of tools like: std::vector, std::string, std::unique_ptr and std::shared_ptr, effectively removing the need for custom destructors, move/copy constructors, move/copy assignment and default constructors.




How to apply it to your code



In your code you have a lot of different resources, and this makes for a great example.



The string



If you notice brandname is effectively a "dynamic string", the standard library not only saves you from C-style string, but automatically manages the memory of the string with std::string.



The dynamically allocated B




The second resource appears to be a dynamically allocated B. If you are dynamically allocating for other reasons other than "I want an optional member" you should definitely use std::unique_ptr that will take care of the resource (deallocating when appropriate) automatically. On the other hand, if you want it to be an optional member you can use std::optional instead.



The collection of Bs



The last resource is just an array of Bs. That is easily managed with an std::vector. The standard library allows you to choose from a variety of different containers for your different needs; Just to mention some of them: std::deque, std::list and std::array.



Conclusion



To add all the suggestions up, you would end up with:




class A {
private:
std::string brandname;
std::unique_ptr b;
std::vector vec;
public:
virtual void something(){} = 0;
};



Which is both safe and readable.


mysql - move_uploaded_file / No such file or directory in PHP




i have a problem with the move_uploaded_file function this is the problem:




Warning: move_uploaded_file(/imagenes/Icon.png) [function.move-uploaded-file]: failed to >open stream: No such file or directory in /home/decc98/public_html/php/insert.php on line 6



Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpIBBh5U' >to '/imagenes/Icon.png' in /home/decc98/public_html/php/insert.php on line 6



Insercion exitosa





Other stuff, i speak spanish so part of my code is in spanish... Anyways, my code is:



        include "conexion.php";
$ruta = "/imagenes";
$archivo = $_FILES['imagen']['tmp_name'];
$nombreArchivo = $_FILES['imagen']['name'];
move_uploaded_file($archivo,$ruta."/".$nombreArchivo);
$ruta=$ruta."/".$nombreArchivo;
$texto = $_POST['descripcion'];

$id = rand(1,200);
$insertar = mysql_query("INSERT INTO tablaUno VALUES('".$id."','".$ruta."','".$texto."')");
if ($insertar) {
echo "Inserción exitosa";
}else{
echo "Fallo en la inserción";
}

?>



Please if anyone can help me I would appreciate it!


Answer



You need to use a relative path instead of an absolute path.



For example:



$ruta = "imagenes";



leaving out the / at the beginning of your folder name, if you're using your script from the root.



Or, something like:



$ruta = "../imagenes";


depending on the script execution's location.



Note: Using / is mostly used for an (server) absolute path, something to the affect of:




/var/user/user123/public_html/imagenes

Java equivalent of Python "join" method for array?

How can I do this Python trick in Java?



>>> l = [1,2,3,4,5]
>>> print ' '.join(l)
1 2 3 4 5


This doesn't apply to Strings only. I am using generics and need to print any kind of value in the Array.

java - Why is char[] preferred over String for passwords?



In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.



Why does String pose a threat to security when it comes to passwords?
It feels inconvenient to use char[].


Answer



Strings are immutable. That means once you've created the String, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in.




With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.



So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.



As noted in the comments, it's possible that arrays being moved by the garbage collector will leave stray copies of the data in memory. I believe this is implementation-specific - the garbage collector may clear all memory as it goes, to avoid this sort of thing. Even if it does, there's still the time during which the char[] contains the actual characters as an attack window.


A concise explanation of nil v. empty v. blank in Ruby on Rails




I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here's the closest I've come:




  • blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.


  • nil? objects are instances of NilClass.


  • empty? objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.




Is there anything missing, or a tighter comparison that can be made?



Answer



.nil? can be used on any object and is true if the object is nil.



.empty? can be used on strings, arrays and hashes and returns true if:




  • String length == 0

  • Array length == 0

  • Hash length == 0




Running .empty? on something that is nil will throw a NoMethodError.



That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.



nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true

5.blank? == false
0.blank? == false


.blank? also evaluates true on strings which are non-empty but contain only whitespace:



"  ".blank? == true
" ".empty? == false



Rails also provides .present?, which returns the negation of .blank?.



Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:



[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true

php - Detecting potential SQL injection attacks, as well as other security issues



We all know it is nearly impossible to produce a large website without one or two flaws. As such I've written a small monitor that checks Apache access logs for potential SQL injection attacks (amongst other things), and it's working very well. I get an alert whenever someone attempts an attack, and I've had so few false positives that the default action is now to dump them into an iptables drop list. It's even helped me identify a few (non-security) bugs and remove them.



Here's my rules (case insensitive):



PathInjection = \./\.\./(bin|boot|data|dev|etc|home|lib|lib64|media|mnt|opt|proc|root|sbin|selinux|srv|sys|tmp|usr|var)/


Havij = 0x31303235343830303536

r3dm0v3 = 0x7233646D3076335F68766A5F696E6A656374696F6E

LogicBypass = '.*?(\bor|\band|\bxor|\|\||\&\&).*?--

UnionSelect = union[^a-z-_]+((all|distinct)[^a-z-_]+)?select[^a-z-_]


What I'd like to know is, how would you bypass these checks and still produce a valid injection? Can you think of a way to improve them without introducing false positives?




A few notes:




  • Case sensitivity is switched off.

  • I'm using MySQL.

  • The Havij and r3dm0v3 entries are used as a catch-all to prevent use of those automation tools.

  • I'm checking both raw and urldecoded strings.

  • I'm not looking for answers like "make more secure code instead".

  • I'm not looking for a different way to do this, just a way to improve my current logic.




EDIT:
Ok, so people seem to have misunderstood my intent. That's probably my fault, since I didn't fully explain. This is being requested as a tacked-on feature to a monitoring product, and is designed to offer minimal security monitoring. As part of our dialog with the client and our documentation, we're emphasising that this is not a catch-all, nor is it a replacement for proper security infrastructure (e.g. an IDS and firewall). It's simply an informational service to help provide basic threat detection and produce statistics about the number of potential attacks. I'm not trying to write an IDS or firewall. If it were up to me, I'd leave the feature out and tell them to go install a full suite of security infrastructure with its own monitoring systems, but this isn't my call. The current situation is that I've been testing the system on my own site. Right now, I'm just looking for a way to improve the regex strings to make this more effective. Hopefully this clears things up a little.


Answer



You're talking about writing an IDS. Unless your product is an IDS, just get and install one. Snort is well-known and has a free version.




I'm not looking for a different way to do this, just a way to improve my current logic.





Sometimes when it comes to security, the wrong approach simply is. How would I mess with your current logic? Unicode or hex encoding.


Java comparison with == of two strings is false?

String parts is String[6]:





["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]


But when I compare parts[0] with "231":



"231" == parts[0]



the above result is false,



I'm confused, so could anybody tell me why?

jquery - How to insert an item into an array at a specific index (JavaScript)?

Answer


Answer




I am looking for a JavaScript array insert method, in the style of:



arr.insert(index, item)


Preferably in jQuery, but any JavaScript implementation will do at this point.


Answer



What you want is the splice function on the native array object.




arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).



In this example we will create an array and add an element to it into index 2:





var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";

arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());





Unable to free const pointers in C




How can I free a const char*? I allocated new memory using malloc, and when I'm trying to free it I always receive the error "incompatible pointer type"



The code that causes this is something like:



char* name="Arnold";
const char* str=(const char*)malloc(strlen(name)+1);

free(str); // error here


Answer



Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer; free takes a void*, not a const void*:



free((char*)str);

plot explanation - How did Sherlock survive the fall? - Movies & TV

In Sherlock, BBC Series, Season 2 Episode 3 - The Reichenbach Fall, how did Sherlock survive the fall? I've read some theories online regarding this, but in this interview, Steven Moffat says "There is a clue everybody's missed". He also says "Yes. We had to have Holmes dying in Watson's arms – and get away with that, which we have."



So how? Does anybody know yet?

Monday 30 December 2019

Regex - Match attribute in a HTML code




I have problem with matching the html attributes (in a various html tags) with regex. To do so, I use the pattern:



myAttr=\"([^']*)\"


HTML snippet:







it selects text from the myAttr the end /> but I need to select the myAttr="..." ("http://example.com")


Answer



You have an apostrophe (') inside your character class but you wanted a quote (").



myAttr=\"([^"]*)\"


That said, you really shouldn't be parsing HTML with regexes. (Sorry to link to that answer again. There are other answers to that question that are more of the "if you know what you are doing..." variety. But it is good to be aware of.)




Note that even if you limit your regexing to just attributes you have a lot to consider:




  • Be careful not to match inside of comments.

  • Be careful not to match inside of CDATA sections.

  • What if attributes are bracketed with single quotes instead of double quotes?

  • What if attributes have no quotes at all?



This is why pre-built, serious parsers are generally called for.



css3 - CSS select the first child from elements with particular attribute



Lets say that we have the following code:















How would you go about selecting the first child that has attribute equal to 3? I was thinking that perhaps this could do the job:



element[bla="3"]:first-child


...but it did not work


Answer



The :first-child pseudo-class only looks at the first child node, so if the first child isn't an element[bla="3"], then nothing is selected.




There isn't a similar filter pseudo-class for attributes. An easy way around this is to select every one then exclude what comes after the first (this trick is explained here and here):



element[bla="3"] {
}

element[bla="3"] ~ element[bla="3"] {
/* Reverse the above rule */
}



This, of course, only works for applying styles; if you want to pick out that element for purposes other than styling (since your markup appears to be arbitrary XML rather than HTML), you'll have to use something else like document.querySelector():



var firstChildWithAttr = document.querySelector('element[bla="3"]');


Or an XPath expression:



//element[@bla='3'][1]

oop - How to create a static field in javascript class




I can define a class in JavaScript like this:



var appender = function (elements, func) {
this.Prop = something;
staticProp = something_else;
};


Am I right? Well then, how can I create a static field in this class? And how can I access that field inside the class? I mean I want a field that be shared between all instances from the class.




var ap1 = new appender();
var ap2 = new appender();
ap1.Prop = something1;
ap2.Prop = something2;
var t = ap1.Prop == ap2.Prop; // true
ap1.staticProp = something_static;
var s = ap2.staticProp = something_static; // I want to this returns true. how can I?

Answer




This is not answered so easily. It won't behave like a static var you know from other languages such as Java etc.



What you can do is append it to the function, like such:



appender.staticProp = 3


That means that within the function you have to reference it using the Function name:



var Person = function(name) {

this.name = name;

this.say = function() {
console.log( Person.staticVar );
}
}

Person.staticVar = 3;



So it allows you to append variables that are somewhat static. But you can only reference them as shown above.


How to trim off last character in an Array - jQuery



so today I have an Array with several strings in them, all ending with , example: jazz, latin, trance,




I need to remove the , off the last element in the Array. Searching Stackoverflow I found several answers and tried the code below, but no luck so far :(



// How I'm generating my Array (from checked checkboxes in a Modal)
role_Actor = [];
$('.simplemodal-data input:checked').each(function() {
role_Actor.push($(this).val());
});

// roleArray = my Array

var lastEl = roleArray.pop();
lastEl.substring(0, lastEl.length - 1);
roleArray.push($.trim(lastEl));


// My function that displays my strings on the page
$.each(roleArray, function(index, item) {
$('.'+rowName+' p').append(item+', ');
});


// Example of the Array:
Adult Animated, Behind the Scenes, Documentary,


Thanks for taking a look!






Thanks @Claire Anthony! for the fix!!!


Answer




You forgot to assign lastEl before putting it back in to roleArray:



lastEl = lastEl.substring(0, lastEl.length - 1);



As the comments suggest, and as you're just using this for display purposes, you should remove the commas from the elements in roleArray and use the join method, like so:



var roleArray = ['latin', 'jazz', 'trance'];
$('#example').append(roleArray.join(', '));

r - How to choose variable to display in tooltip when using ggplotly?



I have a simple data frame:



seq <- 1:10

name <- c(paste0("company",1:10))
value <- c(250,125,50,40,40,30,20,20,10,10)
d <- data.frame(seq,name,value)


And I want to plot it this way:



require(ggplot2)
ggplot(data = d,aes(x=seq,y=value))+geom_line() + geom_point()



Now I want to use plotly, mostly to be able, when mousing over a point, to get other information than the value, such as the company name. I try this :



require(plotly)
ggplotly()


which get me a tooltip, but with only seq and value. I tried the option tooltip= but it's specified you can use the only variable describe in the aesthetic, and I don't use the name in my aes.



Any solution? I saw I am not the first with this problem, but I haven't found answer working with ggplotly.



Answer



You don't need to modify the plotly object as suggested by @royr2. Just add label = name as third aesthetic



ggplot(data = d, aes(x = seq, y = value, label = name)) + geom_line() + geom_point()


and the tooltip will display name in addition to seq and value.



The ggplotly help file says about tooltip parameter:





The default, "all", means show all the aesthetic mappings (including the unofficial "text" aesthetic).




So you can use the label aesthetic as long as you don't want to use it for geom_text.



BTW: I've also tried text instead of label



ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line() + geom_point()



but then ggplot2 complained




geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?




and plotted only points. I had to add a dummy group to geom_line to remove the issue:



ggplot(data = d, aes(x = seq, y = value, text = name)) + geom_line(group = 1) + geom_point()



(But note if you put the dummy group as fourth aesthetic inside aes() it will appear by default also in the tooltip.)



However, I find the unofficial text aesthetic can become useful alongside label if you want to have different strings plotted by geom_text and shown in the tooltip.



Edit to answer a question in comments:
The tooltip parameter to ggplotly() can be used to control the appearance. ggplotly(tooltip = NULL) will suppress tooltips at all. ggplotly(tooltip = c("label")) selects the aesthetics to include in the tooltip.


python - Sorting in pandas for large datasets

I would like to sort my data by a given column, specifically p-values. However, the issue is that I am not able to load my entire data into memory. Thus, the following doesn't work or rather works for only small datasets.



data = data.sort(columns=["P_VALUE"], ascending=True, axis=0)


Is there a quick way to sort my data by a given column that only takes chunks into account and doesn't require loading entire datasets in memory?

android - "Unfortunately My First App has stopped working




I have just downloaded and started using the android SDK and have followed their instructions on creating "my first app" which says "Hello World." I have not changed anything in the code. I am running a Nexus 7 emulator (only one that doesn't crash every time I run it). When I run the app, on the emulator it says "Unfortunately my first app has stopped working."



Here is the logcat:



05-16 13:05:48.742: W/dalvikvm(1066): VFY: unable to resolve static field 1559 (ActionBarWindow) in Landroid/support/v7/appcompat/R$styleable;
05-16 13:05:48.742: D/dalvikvm(1066): VFY: replacing opcode 0x62 at 0x0004
05-16 13:05:48.752: D/AndroidRuntime(1066): Shutting down VM
05-16 13:05:48.752: W/dalvikvm(1066): threadid=1: thread exiting with uncaught exception (group=0xb2ac5ba8)
05-16 13:05:48.812: E/AndroidRuntime(1066): FATAL EXCEPTION: main

05-16 13:05:48.812: E/AndroidRuntime(1066): Process: com.example.myfirstapp, PID: 1066
05-16 13:05:48.812: E/AndroidRuntime(1066): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:107)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:58)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
05-16 13:05:48.812: E/AndroidRuntime(1066): at com.example.myfirstapp.MainActivity.onCreate(MainActivity.java:18)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.Activity.performCreate(Activity.java:5231)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.os.Handler.dispatchMessage(Handler.java:102)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.os.Looper.loop(Looper.java:136)
05-16 13:05:48.812: E/AndroidRuntime(1066): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-16 13:05:48.812: E/AndroidRuntime(1066): at java.lang.reflect.Method.invokeNative(Native Method)
05-16 13:05:48.812: E/AndroidRuntime(1066): at java.lang.reflect.Method.invoke(Method.java:515)
05-16 13:05:48.812: E/AndroidRuntime(1066): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-16 13:05:48.812: E/AndroidRuntime(1066): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-16 13:05:48.812: E/AndroidRuntime(1066): at dalvik.system.NativeStart.main(Native Method)

05-16 13:05:51.822: I/Process(1066): Sending signal. PID: 1066 SIG: 9


Any thoughts? Again, this is the default code upon creating a new app, so I'm not sure why it wouldn't work... Thanks for the help


Answer



This is how I solved this problem:




  1. Import support library as a project from
    "sdk/extras/android/support/v7/appcompat".


  2. Reference library in your project (for Eclipse, "Properties -
    Android - Add").

  3. Build projects (for Eclipse, "Projects - Build All"). Make sure, you
    have "android.support.v7.appcompat" in your main project gen folder.

  4. If it doesn't worked - clean and rebuild project.



and if you have the jar file already in libs folder then first Delete the jar from the libs folder and then do the above steps..



Ensure that your in yout Manifest.xml your activity has the correct theme




    android:name="***.*****.******"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light"
>


Hope it helps..


Regex Group in Perl: how to capture elements into array from regex group that matches unknown number of/multiple/variable occurrences from a string?



In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?



For example, for a string:



var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello



to process this with code:



$string = "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";

my @array = $string =~

for ( my $i = 0; $i < scalar( @array ); $i++ )
{
print $i.": ".$array[$i]."\n";

}


I would like to see as output:



0: var1=100
1: var2=90
2: var5=hello
3: var3="a, b, c"
4: var7=test

5: var3=hello


What would I use as a regex?



The commonality between things I want to match here is an assignment string pattern, so something like:



my @array = $string =~ m/(\w+=[\w\"\,\s]+)*/;



Where the * indicates one or more occurrences matching the group.



(I discounted using a split() as some matches contain spaces within themselves (i.e. var3...) and would therefore not give desired results.)



With the above regex, I only get:



0: var1=100 var2


Is it possible in a regex? Or addition code required?




Looked at existing answers already, when searching for "perl regex multiple group" but not enough clues:




Answer



my $string = "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";

while($string =~ /(?:^|\s+)(\S+)\s*=\s*("[^"]*"|\S*)/g) {
print "<$1> => <$2>\n";
}



Prints:



 => <100>
=> <90>
=>
=> <"a, b, c">
=>
=>



Explanation:



Last piece first: the g flag at the end means that you can apply the regex to the string multiple times. The second time it will continue matching where the last match ended in the string.



Now for the regex: (?:^|\s+) matches either the beginning of the string or a group of one or more spaces. This is needed so when the regex is applied next time, we will skip the spaces between the key/value pairs. The ?: means that the parentheses content won't be captured as group (we don't need the spaces, only key and value). \S+ matches the variable name. Then we skip any amount of spaces and an equal sign in between. Finally, ("[^"]*"|\S*)/ matches either two quotes with any amount of characters in between, or any amount of non-space characters for the value. Note that the quote matching is pretty fragile and won't handle escpaped quotes properly, e.g. "\"quoted\"" would result in "\".



EDIT:




Since you really want to get the whole assignment, and not the single keys/values, here's a one-liner that extracts those:



my @list = $string =~ /(?:^|\s+)((?:\S+)\s*=\s*(?:"[^"]*"|\S*))/g;

Check if a value exists in an array in Ruby



I have a value 'Dog' and an array ['Cat', 'Dog', 'Bird'].




How do I check if it exists in the array without looping through it? Is there a simple way of checking if the value exists, nothing more?


Answer



You're looking for include?:



>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

python - How do I regex match with grouping with unknown number of groups



I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:



... 
VALUE 100 234 568 9233 119
...
VALUE 101 124 9223 4329 1559
...



I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.e., I want it to return ('100','234','568','9233','119'). The problem is that I do not know in advance how many numbers there will be.



I tried to use this as a regex:



VALUE (?:(\d+)\s)+


This matches the line, but it only captures the last value, so I just get ('119',).


Answer




What you're looking for is a parser, instead of a regular expression match. In your case, I would consider using a very simple parser, split():



s = "VALUE 100 234 568 9233 119"
a = s.split()
if a[0] == "VALUE":
print [int(x) for x in a[1:]]


You can use a regular expression to see whether your input line matches your expected format (using the regex in your question), then you can run the above code without having to check for "VALUE" and knowing that the int(x) conversion will always succeed since you've already confirmed that the following character groups are all digits.


php - Trying to pass value to ISSET condition but getting error



I have created a PHP script and if use the script its always going to else condition and I am not sure why its not going to else condition.




     require_once  'db_functions.php';
$db = new DB_Functions();
$response = array();

$phone="1234";
$name="Test";
$birthdate="1994-01-01";
$address="123 M";


if(isset($_POST['phone']) &&
isset($_POST['name']) &&
isset($_POST['birthdate']) &&
isset($_POST['address']))


{
echo "Hello World 1";

$phone = $_POST['phone'];

$name = $_POST['name'];
$birthdate = $_POST['birthdate'];
$address = $_POST['address'];

echo "Hello World 2";

}

else{


echo "Hello";
$response["error_msg"] = "Required parameter
(phone,name,birthdate,address) is missing!";
echo json_encode($response);
}
?>


Output:




_msg":"Required parameter (phone,name,birthdate,address) is missing!"}



If the value is passed then it should go to if condition instead of else condition.



Options Tried



Tried Below options but I am getting empty value:



$test=$_POST['phone'];
echo "Hey......".$test;




echo isset($_POST['phone']);



URL USED
https://www.aaa.ccc/php/register.php?phone=232&name=test&birthdate=1954-04-04&address=232


Answer



You are passing the parameters in the url using the GET method, not POST, so you need:



    require_once  'db_functions.php';

$db = new DB_Functions();
$response = array();

$phone="1234";
$name="Test";
$birthdate="1994-01-01";
$address="123 M";

if(isset($_GET['phone']) &&
isset($_GET['name']) &&

isset($_GET['birthdate']) &&
isset($_GET['address']))


{
echo "Hello World 1";

$phone = $_GET['phone'];
$name = $_GET['name'];
$birthdate = $_GET['birthdate'];

$address = $_GET['address'];

echo "Hello World 2";

}

else{

echo "Hello";
$response["error_msg"] = "Required parameter

(phone,name,birthdate,address) is missing!";
echo json_encode($response);
}
?>

php - How to parse this table and extract data from it?

I have the following table: http://www.nbs.rs/kursnaListaModul/srednjiKurs.faces?lang=lat



It is a currency exchange list and I need to extract some data from it. On left side of the table are currency ID numbers. Would it be possible to extract data from specified rows based on their IDs?



For example, from the table above, I want to extract currencies with IDs 978, 203, and 348.



Output should be:





  • EUR 104,2182

  • CZK 4,2747

  • HUF 38,7919



By looking at similar examples here, I came up with this: http://pastebin.com/hFZs1H7C



I need somehow to detect IDs and the print proper values... I'm noob when it comes to programming and I need your help.




$data = file_get_contents('http://www.nbs.rs/kursnaListaModul/srednjiKurs.faces?lang=lat');

$dom = new domDocument;

@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');

$rows = $tables->item(1)->getElementsByTagName('tr');


foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
foreach ($cols as $col) {

echo $col;

}
}


?>

javascript - Function receives only first element of String array




Dear fellow programmers




I'm dealing with a atrange issues I've been trying to debug for the last two hours. I'm writing a web front end that receives commands from a server that are executed using the window.apply function. A triggerEvents function is used to handle all the different command and passes the arguments sent from the server to the appropriate function (see below code).



function triggerEvents(commands){
for (var index = 0; index < commands.length; index++){
var command = commands[index];
console.debug("execute");
console.debug(command);
console.debug(command.arguments);
window[command.function].apply(null, command.arguments)

}


}



In general that works pretty well, however, one particular function (next code listing) is passed an array of strings but for some reason, only the first element is available in the function.



function updateAvailableBlocks(args) {
availableBlocks = []
for(i=0; i < args.length; i++) {

availableBlocks[i] = args[i];
}


}



Now, when I inspect the debugger I can confirm that I do receive an array of Strings from the server and that that particular array is passed to window.apply as expected.



Debugger view inside triggerEvents()




But when I step into the execution of the function, I am only able to see the first element.



Debugger view inside upateActiveBlocks()



I made sure that all caches are deleted and that Im not using outdated code, but I can't think of something that would cause this. I'd be very grateful for your sharp minds on this.



Thanks in advance!


Answer



Use .call instead of .apply. Apply spreads the arguments of passed array as if they were passed one by one. So if your function doesn't expect variable numbers of arguments and you are not handling them properly then it simply won't work as you would expect.






function foo(arg) {
console.log(arg);
}

const arr = ['a', 'b', 'c'];
foo.apply(null, arr);
foo.call(null, arr);






Or you could use the rest operator with apply to achieve the same effect.





function foo(...arg) {
console.log(arg);
}


const arr = ['a', 'b', 'c'];
foo.apply(null, arr);




angular - How to use chain calls Promise?



Now in .then section I all another promise http request:



.then(result => { this.service().then(data => {}); });


Is it a correct way to use chained promises?


Answer



Almost! You need to return the promise in the function, either like this:



.then(result => { return this.service().then(data => {}); });


or like this:



.then(result => this.service().then(data => {}));

php - Creating custom helper class?



I have followed
What is the best practice to create a custom helper function in php Laravel 5?



This question two answers help me to create custom static class in laravel 5.1 .now my question is whether that class is secured or not ? because it is a static class .
Thank you in advance.


Answer



Using static method in your helper class has nothing to do with securing your application.




The question is why do we even use helper class/methods and what are helper class/methods:



Laravel has many helper methods which helps you to minimize writing to much code for common tasks:



This helper class file is located here:



vendor\laravel\framework\src\Illuminate\Foundation\helpers.php



These are some of the helper methods that comes with Laravel out-of-box:




abort - Throw an HttpException with the given data.



if (!function_exists('abort')) {
/**
* Throw an HttpException with the given data.
*
* @param int $code
* @param string $message
* @param array $headers
* @return void

*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
function abort($code, $message = '', array $headers = [])
{
return app()->abort($code, $message, $headers);
}
}



asset - Generate an asset path for the application.



if (!function_exists('asset')) {
/**
* Generate an asset path for the application.
*
* @param string $path
* @param bool $secure
* @return string

*/
function asset($path, $secure = null)
{
return app('url')->asset($path, $secure);
}
}


and lots more...




So you wish to have your own Helper method, maybe because its not currently available in Laravel Helpers.



To avoid overriding Laravel helper methods, Its better you put your own helper methods in a class file:



Example: My helper class for Dates which I can reuse in my applications, might look like this:



namespace App\Helpers;

class DateHelper {


public static function dateFormat1($date) {
if ($date) {
$dt = new DateTime($date);

return $dt->format("m/d/y"); // 10/27/2014
}
}
}



then you could use it like so:



{{dateHelper::dateFormat1($user->created_at)}}



If we don't wish to use a class, we could have done this:



//helper method for date
function dateFormat1($date) {
if ($date) {
$dt = new DateTime($date);


return $dt->format("m/d/y"); // 10/27/2014
}
}


and use it like this:



{{ dateFormat1($user->created_at) }}




However, what if later releases of Laravel decides to have a hepler with same name dateFormat1 then there will be a collision or overrides.



Hence its better to put you helper methods in classes.


c# - How to take async result in getter?

I have a method in repository with this implementation which returns a Task


Task> GetAllAppsRequestAsync();

I write the getter which call this async method


public IList ApplicationsList
{
get
{
IList applicationDTO = _appService.GetAllAppsRequestAsync();
if (applicationDTO != null)
{
applicationList = mapper.DefaultContext.Mapper.Map>(applicationDTO);
}
return applicationList;
}
set => Set(ref applicationList, value);
}


_appService.GetAllAppsRequestAsync(); - return task, and proble that getter doesn't have async



I try to write delegate, i take the problem when i map the models.


I try to find something but whatever I do, I take deathlock or don't wait my task with result.(try getAwaiter, wait,some example with wrapping) and doesn't know what to do?


forget i try to it by this


public static void RunSync(Func func)
{
AsyncHelper._myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}

but doesn't take the result, before project will finish


Node


I should use the property because it binding with with my itemControl in wpr xaml page.


Edit


private async Task> TakeAppListAsync()
{
IList applicationDTO = await _appService.GetAllAppsRequestAsync();
if (applicationDTO != null)
{
applicationList = mapper.DefaultContext.Mapper.Map>(applicationDTO);
}
return applicationList;
}

php - Trying to get property of non-object MySQLi result

Got a bit of PHP code I'm struggling with - had a search around Google etc. and tried everything mentioned, but for some reason I'm having trouble solving it.



The problem is:



I have some code that is querying a database for the presence of a particular user.



The code (it's a method inside a class)




global $mysqli;
// Query specified database for value
$q = 'SELECT id FROM ' . $database . ' WHERE username = \'' . $username . '\'';
$r = $mysqli->query($q);
var_dump($r);
if ($r->num_rows) {
// If row found username exists so return false
return false;

}
...
?>


I've var dumped the result of the query ($r) and got this:



object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }



This is correct, there should only be 1 row as above.



I do get this error linking to the line saying if ($r->num_rows) {



Notice: Trying to get property of non-object in FILE on line LINE



but I don't know why since the object is valid (as above) and it should be working fine. From what I can tell it seems to be going through alright, I'm just wondering why there's an error. I'm sure it's something simple but I'd appreciate any help.

Sunday 29 December 2019

android dialog box not running

this is my code in which the app is running just fine but the dialog box is not opening the button is clickable but no action is being performed



@Override
public void onClick(View view){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(appointmentpage.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_otp,null);
final EditText mOTP = (EditText) mView.findViewById(R.id.enterOTP);

final Button mVerify = (Button) mView.findViewById(R.id.verify);

mVerify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mOTP.getText().toString().isEmpty())
{
mVerify.setOnClickListener(new View.OnClickListener(){

@Override

public void onClick(View view) {
AlertDialog.Builder mBuilder1 = new AlertDialog.Builder(appointmentpage.this);
View mView1 = getLayoutInflater().inflate(R.layout.confirmation_final,null);



}
});
}
else{

Toast.makeText(appointmentpage.this,
"Enter OTP",
Toast.LENGTH_SHORT).show();
}
}

javascript - jQuery document.createElement equivalent?



I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.




var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);



I would like to know if there is a better way to do this using jQuery. I've been experimenting with:



var odv = $.create("div");
$.append(odv);
// And many more


But I'm not sure if this is any better.


Answer




here's your example in "one" line.



this.$OuterDiv = $('
')
.hide()
.append($('
')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;






Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("

") vs $("
")
vs $(document.createElement('div')) as a way of creating new elements, and which is "best".



I put together a small benchmark, and here's roughly the results of repeating the above options 100,000 times:



jQuery 1.4, 1.5, 1.6



               Chrome 11  Firefox 4   IE9

440ms 640ms 460ms
420ms 650ms 480ms
createElement 100ms 180ms 300ms


jQuery 1.3



                Chrome 11
770ms
3800ms

createElement 100ms


jQuery 1.2



                Chrome 11
3500ms
3500ms
createElement 100ms



I think it's no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.



Update 2



Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!



http://jsben.ch/#/ARUtz


c++ - Why is "using namespace std;" considered bad practice?



I've been told by others that writing using namespace std; in code is wrong, and that I should use std::cout and std::cin directly instead.



Why is using namespace std; considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Does it impact performance?


Answer



This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:



using namespace foo;
using namespace bar;



Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.



If you had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.


c# - "using" statement locations within namespace declarations


Possible Duplicate:
Should Usings be inside or outside the namespace







I'm supporting some code that, unusually, has all its using statements contained within the namespace declaration. It makes me a bit uncomfortable but I have no idea if this should be anything to be concerned about or not. I can't think of an immediate problem other than it being counter to usual convention.



Is there anything wrong with:



namespace myProject.controls
{
using System;
using System.Collections;

using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


Instead of the more widely-used:



using System;

using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace myProject.controls
{

c# - When a class is inherited from List, XmlSerializer doesn't serialize other attributes



I'm having a situation here, I need my class to be inherited from List, but when I do this XmlSerializer does not serialize any property or field declared in my class, the following sample demonstrates:



public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

DoSerialize();
}
private void DoSerialize()
{
MyClass obj = new MyClass();
obj.Add(1);
obj.Add(2);
obj.Add(3);
XmlSerializer s = new XmlSerializer(typeof(MyClass));
StringWriter sw = new StringWriter();

s.Serialize(sw, obj);
}
}
[Serializable]
[XmlRoot]
public class MyClass : List
{
public MyClass()
{
}

int myAttribute = 2011;
[XmlAttribute]
public int MyAttribute
{
get
{
return myAttribute;
}
set
{

myAttribute = value;
}
}
}


the resulting XML:






1
2
3


Answer



This is by design. I don't know why this decision was made, but it is stated in the documentation:






  • Classes that implement ICollection or IEnumerable. Only collections are
    serialized, not public properties.




(Look under "Items that can be serialized" section). Someone has filed a bug against this, but it won't be changed - here, Microsoft also confirms that not including the properties for classes implementing ICollection is in fact the behaviour of XmlSerializer.



A workaround would be to either:





  • Implement IXmlSerializable and control serialization yourself.



or




  • Change MyClass so it has a public property of type List (and don't subclass it).



or





  • Use DataContractSerializer, which handles this scenario.


Redirect without notification in HTML

In HTML is there a way to redirect to a different web page without there being a notification? I really need this for a website so that people cannot access work in progress pages and are redirected to the home page. But everything I have tried is an optional redirection.

c++ - Unresolved external symbol in object files



During coding in Visual Studio I got an unresolved external symbol error
and I've got no idea what to do. I don't know what's wrong.
Could you please decipher me? Where should I be looking for what kind of errors?



1>Form.obj : error LNK2019: unresolved external symbol "public: class Field * __thiscall Field::addField(class Field *)" (?addField@Field@@QAEPAV1@PAV1@@Z) referenced in function "public: void __thiscall Form::parse(class std::basic_stringstream,class std::allocator > &)" (?parse@Form@@QAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Field::parse(class std::basic_stringstream,class std::allocator > &)" (?parse@Field@@UAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: __thiscall InputField::InputField(class std::basic_stringstream,class std::allocator > &)" (??0InputField@@QAE@AAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::prompt(void)" (?prompt@Field@@UAEXXZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string,class std::allocator > __thiscall Field::getName(void)" (?getName@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)

1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string,class std::allocator > __thiscall Field::getType(void)" (?getType@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::describe(void)" (?describe@Field@@UAEXXZ)
1>C:\Users\tomy\Documents\Visual Studio 2010\Projects\zapoctovkac++\Debug\zapoctovkac++.exe : fatal error LNK1120: 6 unresolved externals

Answer



This error often means that some function has a declaration, but not a definition.



Example:



// A.hpp

class A
{
public:
void myFunc(); // Function declaration
};

// A.cpp

// Function definition
void A::myFunc()

{
// do stuff
}


In your case, the definition cannot be found. The issue could be that you are including a header file, which brings in some function declarations, but you either:




  1. do not define the functions in your cpp file (if you wrote this code yourself)

  2. do not include the lib/dll file that contains the definitions




A common mistake is that you define a function as a standalone and forget the class selector, e.g. A::, in your .cpp file:



Wrong: void myFunc() { /* do stuff */ }

Right: void A::myFunc() { /* do stuff */ }


Java regex match same length groups

I want to match strings like
(()) - 2 open brackets, 2 closed brackets
but not strings like
()() - open and closed and then another opens and closses

(() - two opens, one closed



So more specific i want a regex like this



\({n}\){n}


n opened brackets followed by (same value for n, but n must be greedy) n closed brackets.

php - Wordpress down - no changes

Wordpress website went down without any changes.



Here are the error messages:





Warning: include(/home/theme/public_html/wp-content/themes/sachba/functions.php): failed to open stream: Permission denied in /home/user/public_html/wp-settings.php on line 425



Warning: include(): Failed opening '/home/sachbaco/public_html/wp-content/themes/theme/functions.php' for inclusion (include_path='.:/opt/cpanel/ea-php56/root/usr/share/pear') in /home/user/public_html/wp-settings.php on line 425



Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/wp-settings.php:425) in /home/user/public_html/wp-includes/pluggable.php on line 1195




Any help please?

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO




I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.



I am using PDO and PHP.



My code:



$vals = array(

':from' => $email,
':to' => $recipient,
':name' => $name,
':subject' => $subject,
':message' = >$message
);
print_r($vals);
try {
$pdo = new PDOConfig();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM messages WHERE `message` LIKE :message";
$q = $pdo->prepare($sql);
$q->execute(array(':message' => $vals[':message']));
$resp = $q->fetchAll();

foreach ($resp as $row) {
throw new Exception('Please do not post the same message twice!');
}

$sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";

$q = $pdo->prepare($sql);
$q->execute($vals);
}
catch(PDOException $e) {
echo $e->getMessage();
}


and the first print_r gives




Array ( [:from]    => abc@gmail.com 
[:to] => lala@me.com
[:name] => abc
[:subject] => abc
[:message] => abc )


which is expected (none are null)



but it outputs the error





SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('abc@gmail.com', 'lala@me.com' at line 1




No idea how to fix this. any ideas?


Answer



from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.



Personally, I wouldn't bother; I'd just rename the column.




PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.


excel - Why do I get the 'fatal error LNK1120: 1 unresolved externals' when building (release) my C++ DLL developed for VBA?

I have developed a simple (no COM) C++ DLL for VBA (Excel) in VS 2008, which works perfectly on Win 10 and Excel 2016, as well as on Win XP and Excel 2003, both during debug and release. I have developed it following this example.




Now, jumping to the issue, using the same recipe and piece of code I have developed the same DLL, but in VS 2015. The debug and release versions for x64 work perfectly, but when I want to release the DLL for X86, it throws me the following error:




1>defFile.def : error LNK2001: unresolved external symbol "func_name"




Additional info, the project has only 2 files, as in the example:






Anyone has an idea how to get over this link issue?



My feeling is that, there might be a setting that I overlooked or skipped!
If you need the code or the settings, I will happily provide them, but they should be as in the example!



Thanks!

javascript - Node.JS Async / Await Dealing With Callbacks?




Is there a way to deal with callback functions inside an async function() other than mixing in bluebird or return new Promise()?




Examples are fun...



Problem



async function bindClient () {
client.bind(LDAP_USER, LDAP_PASS, (err) => {
if (err) return log.fatal('LDAP Master Could Not Bind', err);
});
}



Solution



function bindClient () {
return new Promise((resolve, reject) => {
client.bind(LDAP_USER, LDAP_PASS, (err, bindInstance) => {
if (err) {
log.fatal('LDAP Master Could Not Bind', err);
return reject(err);

}
return resolve(bindInstance);
});
});
}


Is there a more elegant solution?


Answer



NodeJS v.8.x.x natively supports promisifying and async-await, so it's time to enjoy the stuff (:




const 
promisify = require('util').promisify,
bindClient = promisify(client.bind);

let clientInstance; // defining variable in global scope
(async () => { // wrapping routine below to tell interpreter that it must pause (wait) for result
try {
clientInstance = await bindClient(LDAP_USER, LDAP_PASS);
}

catch(error) {
console.log('LDAP Master Could Not Bind. Error:', error);
}
})();


or just simply use co package and wait for native support of async-await:



const co = require('co');
co(function*() { // wrapping routine below to tell interpreter that it must pause (wait) for result

clientInstance = yield bindClient(LDAP_USER, LDAP_PASS);

if (!clientInstance) {
console.log('LDAP Master Could Not Bind');
}
});


P.S. async-await is syntactic sugar for generator-yield language construction.


javascript - Why does Google prepend while(1); to their JSON responses?



Why does Google prepend while(1); to their (private) JSON responses?



For example, here's a response while turning a calendar on and off in Google Calendar:



while (1);
[
['u', [
['smsSentFlag', 'false'],

['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]


I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.




I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.



What's going on here?


Answer



It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.



Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a