Saturday 31 March 2018

php - MySQLi prepared statements error reporting




I'm trying to get my head around MySQli and I'm confused by the error reporting.
I am using the return value of the MySQLi 'prepare' statement to detect errors when executing SQL, like this:




$stmt_test =  $mysqliDatabaseConnection->stmt_init();
if($stmt_test->prepare("INSERT INTO testtable VALUES (23,44,56)"))
{
$stmt_test->execute();
$stmt_test->close();
}
else echo("Statement failed: ". $stmt_test->error . "
");


But, is the return value of the prepare statement only detecting if there is an error in the preperation of the SQL statement and not detecting execution errors? If so should I therefore change my execute line to flag errors as well like this:




if($stmt_test->execute()) $errorflag=true;


And then just to be safe should I also do the following after the statement has executed:



if($stmt_test->errno) {$errorflag=true;}


...Or was I OK to start with and the return value on the MySQLi prepare' statement captures all errors associated with the complete execution of the query it defines?




Thanks
C


Answer



I wrote this twice before in the last two days (so for me it's a duplicate even though the questions started a bit different).



Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)



Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.




$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}


$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable

// 2006 "server gone away" is always an option
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();


edit: just a few notes six years later....
The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....


C++: Questions about using namespace std and cout




Why do I need to type in using namespace std; in order to be able to use cout and endl? Also what are these called; is cout a function?



Is there cout in C? I heard it was implemented in C++ because it is better in many ways.


Answer




cout is a global object defined in the std namespace, and endl is a (stream manipulator) function also defined in the std namespace.



If you take no action to import their names into the global namespace, you won't be able to refer to them with the unqualified identifiers cout and endl. You have to use the fully qualified names:



std::cout << "Hello, World!" << std::endl;


Basically, what using namespace std does is to inject all the names of entities that exist in the std namespace into the global namespace:



using namespace std;

cout << "Hello, Wordl!" << endl;


However, keep in mind that have such a using directive in the global namespace is a BAD programming practice, which will almost certainly lead to evil name clashes.



If you really need to use it (e.g. if a function of yours is using many functions defined in the std namespace, and writing std:: makes the code harder to read), you should rather restrict its scope to the local scope of individual functions:



void my_function_using_a_lot_of_stuff_from_std()
{
using namespace std;

cout << "Hello, Wordl!" << endl;

// Other instructions using entities from the std namespace...
}


Much better, as long as this is practical, is to use the following, less invasive using declarations, which will selectively import only the names you specify:



using std::cout;
using std::endl;


cout << "Hello, Wordl!" << endl;

c++ - How can I resolve "error LNK2019: unresolved external symbol"?




I've got this MFC application I'm working on that needs to have an embedded database. So I went hunting for a slick, fast "embeddable" database for it and stumbled accross SQLite.



I created a DB with it, and I created a static library project with Visual Studio 2008. the library project will be used in another main project.



In the library project, I created a class DBClass with a method AddFeedToDB(CFeed f). The library project uses the .lib file from codeproject (cppsqlite3.lib).



When compiling the static library, no error is detected, but when I try to use the library project file in the main project, I get these type of errors:



error LNK2019: unresolved external symbol "public:void __thiscall

CppSQLite3DB::close(void)" (?close@CppSQLite3DB@@QAEXXZ
referenced in function "public: int __thiscall
CTalkingFeedsDB::AddFeedToDB(class CFeed,char const*)" (?
AddFeedToDB@CTalkingFeedsDB@@QAEHVCFeed@@PDB@Z


What am I missing?


Answer



It happened to me more than once that I thought symbol XXX (i.e. ?close@CppSQLite3DB@@QAEXXZ) was in the import lib, while the actual symbol was __impXXX (i.e. __imp?close@CppSQLite3DB@@QAEXXZ).




The reason for the linker error is then to be found in the compilation step: the compiler will generate the ?close@CppSQLite3DB@@QAEXXZ symbol to be imported, where it should generate __imp?close@CppSQLite3DB@@QAEXXZ. This often means that the function declaration itself didn't have __declspec( dllimport ). Which may be caused by some preprocessor symbol not being defined. Or the __declspec not being there at all...


multithreading - What are the differences between event-driven and thread-based server system?


  • Node.js is an event driven I/O and It's a single threaded server that
    acts upon callbacks and never blocks on the main thread.




    1. But how does it manage to non-blocking I/O?

    2. if it does easy to manage, why don't thread-based system manage it?

    3. Does not work the other threads (behind single event-driven thread) as like thread-based ?

    4. if the other threads mean workers(behind event driven thread) are busy, how it still can handle jobs without blocking?



  • Thread-based model assigning a task to a thread and if there is no
    idle thread, block new tasks.




    1. if a thread can handle multiple tasks like as event-driven single
      thread that handles every I/O without blocking, why thread-based
      system doesn't use this tactic on busy threads to I/O without
      blocking.





I am wondering what are the differences (advantages/disadvantages) between event-driven and thread-based server systems.

r - Turning off some legends in a ggplot



Suppose I have a ggplot with more than one legend.



mov <- subset(movies, length != "")
(p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
)



I can turn off the display of all the legends like this:



(p1 <- p0 + theme(legend.position = "none"))


Passing show_guide = FALSE to geom_point (as per this question) turns off the shape legend.



(p2 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point(show_guide = FALSE)
)



But what if I want to turn off the colour legend instead? There doesn't seem to be a way of telling show_guide which legend to apply its behaviour to. And there is no show_guide argument for scales or aesthetics.



(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_discrete(show_guide = FALSE) +
geom_point()
)
# Error in discrete_scale


(p4 <- ggplot(mov, aes(year, rating, shape = mpaa)) +
aes(colour = length, show_guide = FALSE) +
geom_point()
)
#draws both legends


This question suggests that the modern (since ggplot2 v0.9.2) way of controlling legends is with the guides function.



I want to be able to do something like




p0 + guides(
colour = guide_legend(show = FALSE)
)


but guide_legend doesn't have a show argument.



How do I specify which legends get displayed?


Answer




You can use guide=FALSE in scale_..._...() to suppress legend.



For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).



(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_continuous(guide = FALSE) +
geom_point()
)



Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.



p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
p0+guides(colour=FALSE)


UPDATE



Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.




library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

What is the native keyword in Java for?



While playing this puzzle (It's a Java keyword trivia game), I came across the native keyword.



What is the native keyword in Java used for?



Answer



The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface).


jquery - Can I use CSS3 Selectors to select based on a child element?



I need to select a

element that has a nested with a specific class.



The is not always a child of the

and may instead be a grandchild. For example:



some textlink




I need to select the

element if it has an with the class f5 anywhere inside.



Answer



this isn't possible with a css selector (theres nothing like a parent-selector).



maybe you can work around this with javascript - in jquery, for example, you should get your paragraphs with $('p:has(a.f5)') (and then you're free to .addClass() or set .css() on this elements directly).



EDIT::
you might also want to take a look at this other questions on SO (and next time: search before you ask):




javascript - Why substring does not handle negative indices?




substr() handles negative indices perfectly but substring() only accepts nonnegative indices.



Is there a reason of not using substr in favor of substring? The usage of negative indices are so useful in a lot of cases by viewing the space of indices as cyclic group. Why substr is indicated "deprecated" by MDN?



Answer



substring is when you want to specify a starting and ending index. substr is when you want to specify a starting offset and a length. They do different things and have different use cases.



Edit:
To better answer the exact question of
Why substring does not handle negative indices?



substring specifies a starting and ending index of characters in a string. substr deals with a starting offset and a length. It makes sense to me that substring does not allow a negative index, because there really isn't a such thing as a negative index (the characters in a string are indexed from 0 to n, a "negative index" would be out of bounds). Since substr is dealing with an offset vs an index, I feel the term offset is loose enough to allow for a negative offset, which of course means counting backwards from the end of the string rather than forward from the beginning. This might just be semantics, but its how I make sense of it.



Why is substr deprecated?




I would argue that is in fact not deprecated.



The revision history for the substr MDN states the deprecation notice was put in based on this blog post:




Aug 16, 2016, 12:00:34 AM
hexalys
add deprecated mention per https://blog.whatwg.org/javascript





Which states that the HTML string methods are deprecated (which they should be!). These are methods that wrap a string in an HTML tag, ie, "abc".sub() would return abc. The blog post lists out all of the HTML string methods, and imho, erroneously includes subtr as an HTML string method (it isn't).



So this looks like a misunderstanding to me.



(Excerpt below, emphasis added by me)




Highlights:



The infamous “string HTML methods”: String.prototype.anchor(name), String.prototype.big(), String.prototype.blink(),

String.prototype.bold(), String.prototype.fixed(),
String.prototype.fontcolor(color), String.prototype.fontsize(size),
String.prototype.italics(), String.prototype.link(href),
String.prototype.small(), String.prototype.strike(),
String.prototype.sub(), String.prototype.substr(start, length), and
String.prototype.sup(). Browsers implemented these slightly
differently in various ways, which in one case lead to a security
issue (and not just in theory!). It was an uphill battle, but
eventually browsers and the ECMAScript spec matched the behavior that
the JavaScript Standard had defined.





https://blog.whatwg.org/javascript


python - Numba environment variable not set through .numba_config.yaml

Some environment variables can be set for numba, as specified in the doc: https://numba.pydata.org/numba-doc/dev/reference/envvars.html



However, launching a python shell in the same folder, I cannot see the variable in os.environ:




In [1]: !cat .numba_config.yaml                                                                      
warnings: 1

In [2]: import os; os.environ["NUMBA_WARNINGS"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
in
----> 1 import os; os.environ["NUMBA_WARNINGS"]


~/anaconda3/lib/python3.6/os.py in __getitem__(self, key)
667 except KeyError:
668 # raise KeyError with the original key value
--> 669 raise KeyError(key) from None
670 return self.decodevalue(value)
671

KeyError: 'NUMBA_WARNINGS'



(I have pyyaml installed, import yaml does not yield an error)

Model-View-Controller in JavaScript

tl;dr: How does one implement MVC in JavaScript in a clean way?



I'm trying to implement MVC in JavaScript. I have googled and reorganized with my code countless times but have not found a suitable solution. (The code just doesn't "feel right".)



Here's how I'm going about it right now. It's incredibly complicated and is a pain to work with (but still better than the pile of code I had before). It has ugly workarounds that sort of defeat the purpose of MVC.



And behold, the mess, if you're really brave:




// Create a "main model"
var main = Model0();

function Model0() {
// Create an associated view and store its methods in "view"
var view = View0();

// Create a submodel and pass it a function
// that will "subviewify" the submodel's view

var model1 = Model1(function (subview) {
view.subviewify(subview);
});

// Return model methods that can be used by
// the controller (the onchange handlers)
return {
'updateModel1': function (newValue) {
model1.update(newValue);
}

};
}

function Model1(makeSubView) {
var info = '';

// Make an associated view and attach the view
// to the parent view using the passed function
var view = View1();
makeSubView(view.__view); // Dirty dirty


// Return model methods that can be used by
// the parent model (and so the controller)
return {
'update': function (newValue) {
info = newValue;

// Notify the view of the new information
view.events.value(info);
}

};
}

function View0() {
var thing = document.getElementById('theDiv');
var input = document.getElementById('theInput');

// This is the "controller", bear with me
input.onchange = function () {
// Ugly, uses a global to contact the model

main.updateModel1(this.value);
};

return {
'events': {},

// Adds a subview to this view.
'subviewify': function (subview) {
thing.appendChild(subview);
}

};
}

// This is a subview.
function View1() {

var element = document.createElement('div');
return {
'events': {
// When the value changes this is

// called so the view can be updated
'value': function (newValue) {
element.innerHTML = newValue;
}
},

// ..Expose the DOM representation of the subview
// so it can be attached to a parent view
'__view': element
};

}


How does one implement MVC in JavaScript in a cleaner way? How can I improve this system? Or is this the completely wrong way to go, should I follow another pattern?

java - Android TextView SetText null object reference error




I am new to android and I am getting a



Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference


error on my app. I have read other questions on here like this one - java.lang.NullPointerException - setText on null object reference but I still get the same issue. My format is a little bit different as this is done in a Fragment and what I am doing is having a Custom Adapter from a listview. Here is my code



fragment_song_genre.xml





xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/tools">



name="handler"
type="com.mgrmobi.joox.fragments.FilterSongGenreFragment" />




android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">

android:id="@+id/toprow"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"

android:background="@null"
android:onClick="@{ handler.onCloseClicked }"
android:src="@drawable/search_close" />

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="80dp"

android:text="Genre"
android:textColor="#fff"
android:textSize="20sp" />

android:onClick="@{ handler.reset }"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"

android:layout_marginRight="15dp"
android:text="@string/reset"
android:textAllCaps="true"
android:textColor="#fff"
android:textSize="12sp" />



android:id="@+id/list"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toprow"
android:layout_marginTop="24dp">







That is the main page and it has a Listview in the Bottom and here is the fragment that calls that xml layout



 public class FilterSongGenreFragment extends BaseFragment {

private SongGenreBinding binding;
private ArrayList genres;
String[] names= {"Johm","Paul","Mike"};

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);
}


private static final String GENRES_KEY = "genres";

public static FilterSongGenreFragment newInstance(ArrayList genres) {

Bundle args = new Bundle();
args.putStringArrayList(GENRES_KEY, genres);

FilterSongGenreFragment fragment = new FilterSongGenreFragment();
fragment.setArguments(args);
return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_song_genre, container, false);
binding.setHandler(this);

genres = getArguments().getStringArrayList(GENRES_KEY);

initList();
return binding.getRoot();
}

private void initList() {

// ArrayAdapter adapter = new ArrayAdapter(getActivity(), R.layout.genre_list_text, android.R.id.text1, genres);
FilterSongsAdapter filterSongsAdapter= new FilterSongsAdapter(getActivity(),names);



binding.list.setAdapter(filterSongsAdapter);

binding.list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView adapterView, View view,int position, long l) {
((SongFilterListener) getActivity()).onGenreSelected(genres.get(position));
/*

textView = (ImageView) view.findViewById(R.id.selected_genre);
textView.setVisibility(View.VISIBLE);
*/
// close();
}

});

}


private void close() {
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}

public void onCloseClicked(View view) {
close();
}

public void reset(View view) {
((SongFilterListener) getActivity()).onResetFilters();

close();
}

}


Here is the xml for the listview custom style genre_list_text.xml






xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:gravity="center_vertical|left"
android:text="Genre"
android:paddingBottom="16dp"
android:paddingLeft="4dp"
android:paddingTop="16dp"
android:textColor="#fff"
android:textSize="16sp" />

android:id="@+id/selected_genre"

android:layout_height="24dp"
android:layout_width="24dp"
android:visibility="invisible"
android:src="@drawable/check_circle"
android:layout_marginStart="140dp"
android:layout_centerVertical="true" />





and here is my adapter and as stated before the error happens in the SetText area



  public class FilterSongsAdapter extends ArrayAdapter {

private Context c;
String[] names= {};
LayoutInflater inflater;

public FilterSongsAdapter(Context context,String[] names) {
super(context,R.layout.genre_list_text,names);

this.c=context;
this.names=names;

}

public static class ViewHolder {

TextView text1;



}



@Override
public View getView(int position,View convertView,ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = inflater.from(c).inflate(R.layout.genre_list_text, null);
// Initialize
holder.text1=(TextView) convertView.findViewById(R.id.text1);

convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}

holder.text1.setText(names[position]);


return convertView;
}




}



The SetText inside the GetView is throwing the exception every time, that TextView should have 3 objects names from the Names String Array which I have seen that it has. Based on the error I know that i'm setting the SetText before the FindByID method locates the TextView but I have moved things around and nothing works. Any help would be great . I also been following this tutorial for reference https://www.youtube.com/watch?v=99C_UpLcBRk . I do not know if maybe with a Fragment things are different.


Answer



in your layout you have given default id to TextView android:id="@android:id/text1".



and in JAVA file you are giving R.id.text1



make changes in xml or java.



ether change in xml from android:id="@android:id/text1" to android:id="@+id/text1"
or in java android.R.id.text1



java - How to make a JFrame button open another JFrame class in Netbeans?

I have a JFrame class and it was made in the design section on Netbeans. I am trying to make a log in button that takes closes the current frame and opens another, is there anyway I can do that?



I have tried:



JFrame frame = new JFrame(); 



But I want it to be editable in the design section!

java - compilation error with throwing exception




public class A {
public void f(A a) {
System.out.print("in A ");

}
}

public class B extends A {

public static void main(String[] args) {
B b = new B();
A a = new A();
b.f(b);
b.f(a);

}
}


Why by adding the following method in B class there will be a compilation error?



It's known that if method throws something, it doesn't have to be declared in the method header...



public void f(A a) { 
System.out.println("in B");

throw new java.io.IOExeption();
}

Answer




It's known that if method throws something, it doesn't have to be declared in the method header




That's only true for unchecked exceptions. Your method throws an IOException which is a checked exception so you must either catch it or declare that you throw it otherwise compilation will fail.


hyperlink - How do I link two HTML pages in a web application?

I've got two HTML pages, with one being an opening page for an application and the second being a login page. I have a button on the opening page and I want to be able to click on it and have it take me to the login page. How do I do this?

analysis - Why did the prisoners help Bruce? - Movies & TV



When Bruce is left broken and suffering in the Prison Pit, Bane explains that this is where he suffered and where Bruce will fully realize his failure with Gotham, and then be killed.



During his time there, the Doctor and his friend explain that Bane owns the prison, and their only duty is to keep him alive until Bane wants to kill him. However, they seem to turn around, heal his back and start encouraging him to find the will and ability to climb out of the pit.




The question here is, why?



Why would they disobey Bane and help Bruce?


Answer



As far as I see, it's still a prison and those prisoners who are under Bane's orders are trapped in the same way as Bruce Wayne was. There was no privilege which they enjoyed specifically more than him though.



Secondly Bruce was stuck there for a time that was time long enough to develop some camaraderie and seeing his passion and reaction to the way Gotham was destroyed in front of him could've appealed to their human side. It's often said prison is supposed to be creating a lot of retrospective thought processes for people who are imprisoned and I think they could've found a newer path after taking a look at Bruce Wayne and seeing him struggle against his wounds would've sparked a definite surge in them.



This third part I am not sure. Bane while he was in the pit as we see in the flashbacks fought with plenty of them protecting Talia. I think in a way he would've made enemies then. Since Bruce Wayne was against Bane. Enemy of my enemy theory could quite possibly have kicked in.



Get all html tags(parent and child tags) with id and class name with Javascript/JQuery



Does anybody knows how can I get all the HTML tags that exist in a page?



var items = document.getElementsByTagName("*");



This will get all the tags, but my requirement is




  • get a first parent tag and all the child tags under it


  • get the next parent tag and all the child tags under it and so on



I need to get the tags in a kind of tree-structure. Prefer to do that with Javascript or JQuery.



For example:





Example Page



Blabla















Should Return:



html





  1. head->title

  2. body-->h1,(div-->table-->tr-->td,td)


Answer



document.documentElement is the root of the tree (html). You can then get all of its child elements via children (childNodes would include non-Element children), and get their descendants in document order using querySelectorAll("*"):



var results = Array.prototype.map.call(
document.documentElement.children,
function(element) {
return element.querySelectorAll("*");

});


Live example



results will be an array with an entry for each direct child of the html element, where each element is a NodeList. If you want an array of arrays, you can use Array.from on the result of querySelectorAll (polyfilling it if necessary, as it's relatively new).



Of course there are a dozen ways to spin this. For instance, an array of objects instead:



var results = Array.prototype.map.call(

document.documentElement.children,
function(element) {
return {
element: element,
descendants: Array.from(element.querySelectorAll("*"))
};
});

android - How to create a alert message instead of toast

I have a problem. I have made an QR code scanner and i when he scan the code he put the result like toast but I want it as Alert Message. Can anyone help?



    import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;


import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class MainActivity extends AppCompatActivity implements
ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void scan(View view){
zXingScannerView =new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();


}

@Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}

@Override
public void handleResult(Result result) {

Toast.makeText(getApplicationContext(),result.getText(),Toast.LENGTH_SHORT).show();
zXingScannerView.resumeCameraPreview(this);

}
}


It is the last 4 lines in code.

c - Fastest way to count bits





Possible Duplicate:
How to count the number of set bits in a 32-bit integer?







Give a unsigned char type value,count the total bits in it.What's the fastest way?
I wrote three function as below,what's the best way,and can someone come up with a faster one?(I just want the extremely fast one)



const int tbl[] =
{
#define B2(n) n, n+1, n+1, n+2
#define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)

B6(0), B6(1), B6(1), B6(2)
};

char naivecount (unsigned char val)
{
char cnt = 0;
while (val)
{
cnt += (val & 1);
val = val >> 1;

}
return cnt;
}

inline tableLookUp(int val)
{
assert(val >= 0 && val <= 255);
return tbl[val];
}


int asmCount(int val)
{
int res = 0;
asm volatile("xor %0, %0\n\t"
"begin:\n\t"
"cmp $0x0, %1\n\t"
"jle end\n\t"
"movl %1, %%ecx\n\t"
"and $0x1, %%ecx\n\t"
"addl %%ecx, %0\n\t"

"shrl %1\n\t"
"jmp begin\n\t"
"end:"
: "=r"(res)
: "r" (val));
return res;
}


EDIT:




I have test all the method,the fastest one is to use the popcntl instruction.In platform without the instruction,I will use table look-up.


Answer



If you want to code it by hand, try this:



#include 

int popcnt8(uint8_t x) {

x = (x & 0x55) + (x >> 1 & 0x55);

x = (x & 0x33) + (x >> 2 & 0x33);
x = (x & 0x0f) + (x >> 4 & 0x0f);

return x;
}


on x86, this compiles to (AT&T-syntax):



popcnt8:

movl %edi, %eax
shrb %dil
andl $85, %eax
andl $85, %edi
addl %eax, %edi
movl %edi, %eax
shrb $2, %dil
andl $51, %eax
andl $51, %edi
addl %eax, %edi

movl %edi, %eax
shrb $4, %dil
andl $15, %eax
addl %edi, %eax
movzbl %al, %eax
ret


Compare this to what gcc generates with the intrinsic:




#include 

int popcnt8_intrin(uint8_t x) { return __builtin_popcount(x); }


On x86 with SSE 4.2:



popcnt8_intrin:
movzbl %dil, %eax
popcntl %eax, %eax

ret


which is not optimal; clang generates:



popcnt8_intrin:
popcntl %edi,%eax
ret



reducing the calculation to one (!) instruction.



On x86 without SSE 4.2:



popcnt8_intrin:
subq $8, %rsp
movzbl %dil, %edi
call __popcountdi2
addq $8, %rsp
ret



gcc essentially calls its library here. Not quite optimal. clang does a little better:



popcnt8_intrin:                         # @popcnt8_intrin
movl %edi, %eax
shrl %eax
andl $85, %eax
subl %eax, %edi
movl %edi, %eax

andl $858993459, %eax # imm = 0x33333333
shrl $2, %edi
andl $858993459, %edi # imm = 0x33333333
addl %eax, %edi
movl %edi, %eax
shrl $4, %eax
addl %edi, %eax
andl $252645135, %eax # imm = 0xF0F0F0F
imull $16843009, %eax, %eax # imm = 0x1010101
shrl $24, %eax

ret


clang calculates popcnt for a whole 32 bit number. This is not optimal imho.


Friday 30 March 2018

linux - Why do I use double quotes in shell scripts

I understand the usage single quote and double quote.



but I don't know situation need to double quotes in the script.




there is no diff that statements



$ echo hello world! $1
$ echo "hello world! $1"


please show me diff between normal and double quotes.

android - SAX parser crashes with "Permission Denied" exception message when retrieving google weather XML

I'm trying to get the current temperature via google weather with SAX Parser but I get a "permission denied" exception message when I try to get data:




Code:




/* Get what user typed to the
EditText. */



String cityParamString = ((EditText)
findViewById(R.id.edit_input)).getText().toString();




String queryString =
"http://www.google.com/ig/api?weather="+
cityParamString;



/* Replace blanks with
HTML-Equivalent. */



url = new URL(queryString.replace("
", "%20"));




/* Get a SAXParser from the
SAXPArserFactory. */



SAXParserFactory spf =
SAXParserFactory.newInstance();



SAXParser sp = spf.newSAXParser();



/* Get the XMLReader of the
SAXParser we created. */




XMLReader xr = sp.getXMLReader();



/* Create a new ContentHandler and
apply it to the XML-Reader */



GoogleWeatherHandler gwh = new
GoogleWeatherHandler();



xr.setContentHandler(gwh);




/* Parse the xml-data our URL-call
returned. */



xr.parse(new
InputSource(url.openStream())); <----
THIS CRASHES WITH PERMISION DENIED
EXCEPTION MESSAGE





The url seems to be fine, but url.openstream doesn't work.

php - how to redirect url after submitting a form?



It seems to be a simple but still it is difficult for me to achieve.
Let`s make a small example to clarify the situation:
There are two files: Form.PHP and Action.PHP



Form.PHP has one Input field with name = "ID"
and button SUBMIT




Action.PHP has a script of inserting data in MySQL
and in the end next line:



header("location:Form.PHP");


So after the submitting the form, I come back to Form.PHP...
This is easy...




Now, I want to achieve - after the submitting the form redirection to
Form.PHP?ID=$_POST['ID']



So please help me to modify
header("location:Form.PHP"); to redirect to ?ID=$_POST['ID']


Answer



header("Location: Form.PHP?ID=".$_POST['ID']);

apache - How to check if mod_rewrite is enabled in php?



I was wondering if it is possible to check if mod_rewrite is enabled on Apache AND IIS in PHP.



ModRewrite for IIS exists. Check it here.



So, I'm looking for a PHP script that checks for mod_rewrite on Apache and IIS.




Does anyone know such script or can write one?



Especially for Microsoft IIS.



Thanks!


Answer



If you're using mod_php, you can use apache_get_modules(). This will return an array of all enabled modules, so to check if mod_rewrite is enabled, you could simply do



in_array('mod_rewrite', apache_get_modules());



Unfortunately, you're most likely trying to do this with CGI, which makes it a little bit more difficult.



You can test it using the following, though



strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_rewrite') !== false


If the above condition evaluates to true, then mod_write is enabled.


php - syntax error unexpected T_BOOLEAN_OR




I'm pretty sure its probably ( or ) that is causing it maybe one too many of them.



$filechk1 = "/temp/files/" . $data[0] . ".doc";
$filechk2 = "/temp/files/" . $data[1] . ".doc";
$dirchk1 = "/temp/files/" . $batchid . "/" .$data[0] . ".doc";
$dirchk2 = "/temp/files/" . $batchid . "/" . $data[1] . ".doc";

if(is_file($filechk1) && (is_file($filechk2))) || (is_file($dirchk1) && (is_file($dirchk2))){
...

}

Answer



Incorrectly placed parentheses. Needs to be this.



if ((is_file($filechk1) && is_file($filechk2)) || (is_file($dirchk1) && is_file($dirchk2)))

javascript - jQuery Ajax File Upload




Can I use the following jQuery code to perform file upload using POST method of an ajax request ?



$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');

return false;
}
});


If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.



I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.


Answer



file upload is not possible through ajax.

You can upload file, without refreshing page by using IFrame.
you can check further detail here



UPDATE:



With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.



FormData support starts from following desktop browsers versions.
IE 10+,
Firefox 4.0+,

Chrome 7+,
Safari 5+,
Opera 12+



For more detail, see MDN link


performance - How to read a large text file line by line using Java?

I need to read a large text file of around 5-6 GB line by line using Java.




How can I do this quickly?

c++ - Why is my program slow when looping over exactly 8192 elements?

The following tests have been done with Visual C++ compiler as it is used by the default Qt Creator install (I guess with no optimization flag). When using GCC, there is no big difference between Mystical's version and my "optimized" code. So the conclusion is that compiler optimizations take care off micro optimization better than humans (me at last). I leave the rest of my answer for reference.




It's not efficient to process images this way. It's better to use single dimension arrays. Processing all pixels is the done in one loop. Random access to points could be done using:


pointer + (x + y*width)*(sizeOfOnePixel)

In this particular case, it's better to compute and cache the sum of three pixels groups horizontally because they are used three times each.


I've done some tests and I think it's worth sharing. Each result is an average of five tests.


Original code by user1615209:


8193: 4392 ms
8192: 9570 ms

Mystical's version:


8193: 2393 ms
8192: 2190 ms

Two pass using a 1D array: first pass for horizontal sums, second for vertical sum and average.
Two pass addressing with three pointers and only increments like this:


imgPointer1 = &avg1[0][0];
imgPointer2 = &avg1[0][SIZE];
imgPointer3 = &avg1[0][SIZE+SIZE];
for(i=SIZE;i resPointer[i]=(*(imgPointer1++)+*(imgPointer2++)+*(imgPointer3++))/9;
}
8193: 938 ms
8192: 974 ms

Two pass using a 1D array and addressing like this:


for(i=SIZE;i    resPointer[i]=(hsumPointer[i-SIZE]+hsumPointer[i]+hsumPointer[i+SIZE])/9;
}
8193: 932 ms
8192: 925 ms

One pass caching horizontal sums just one row ahead so they stay in cache:


// Horizontal sums for the first two lines
for(i=1;i hsumPointer[i]=imgPointer[i-1]+imgPointer[i]+imgPointer[i+1];
}
// Rest of the computation
for(;i // Compute horizontal sum for next line
hsumPointer[i]=imgPointer[i-1]+imgPointer[i]+imgPointer[i+1];
// Final result
resPointer[i-SIZE]=(hsumPointer[i-SIZE-SIZE]+hsumPointer[i-SIZE]+hsumPointer[i])/9;
}
8193: 599 ms
8192: 652 ms

Conclusion:



  • No benefits of using several pointers and just increments (I thought it would have been faster)

  • Caching horizontal sums is better than computing them several time.

  • Two pass is not three times faster, two times only.

  • It's possible to achieve 3.6 times faster using both a single pass and caching an intermediary result


I'm sure it's possible to do much better.


NOTE
Please, note that I wrote this answer to target general performance issues rather than the cache problem explained in Mystical's excellent answer. At the beginning it was just pseudo code. I was asked to do tests in the comments... Here is a completely refactored version with tests.

character - Is there a special significance to the cat in The Closer? - Movies & TV



When Deputy Chief Brenda Leigh Johnson moves into a new house in season one (two?), she discovers a cat that has been living in the home already, whom she names "Kitty".



"Kitty" is a she, but Brenda keeps referring to her pet as a "he," despite being constantly corrected by her significant other. While her initial ambivalence towards the cat changes, this incorrect gender identification does not.



In the beginning of season five, the cat passes away. She grieves and carries the cat's ashes around with her, first as a mistake, and then as a remembrance. The ashes are finally placed on the mantle in a fancy urn, despite Brenda's opposition to such practices earlier.




In literature, cats carry a symbolic value, for things like cleanliness and good fortune (see Wikipedia). It seems as though for being such a minor "character" this cat gets a lot of attention in the series to not mean something to the plot or character development.



Is there a deeper connection between Brenda and the cat that the writers and director are trying to establish? Are they comparing Brenda's strong skills in interrogation to "catching a rat"? If she's so close with the cat, why does she maintain this distance with the name "Kitty" and referring to she as a "he"? (drawing on any hints from official sources or evaluations from critics if possible)


Answer



In this interview with executive producer James Duff, he says:




Though Brenda is not a "pet person" she adopts the cat, simply calling
it "kitty," and begins to develop a relationship with her. "A pet is
usually not a part of the procedural aspects of a crime show, but it

is a part of everyday life for a lot of people and we wanted to show
Brenda as an ordinary person," says Duff.




As for the death of kitty:




Kyra Sedgwick broke down weeping when she arrived on set to begin
filming the fifth season of TNT's hit show "The Closer" and learned
that her character, Deputy Police Chief Brenda Leigh Johnson, would be

grappling in ensuing episodes with the serious illness of Kitty, her
pet cat. Unbeknownst to the show's creator and executive producer,
James Duff, Sedgwick had just lost her real-life cat.



"We didn't feel like we had a choice," says Duff, explaining why he
decided to make Kitty's illness a major storyline. The cat that played
Kitty had, in real life, been diagnosed with a serious kidney
condition. "We could replace the cat and keep filming, or we could
accept the cat was seriously ill and write it into the story."




PHP and Enumerations




I know that PHP doesn't have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.



Constants do the trick, but there's the namespace collision problem and (or actually because) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely (never?) know how to autofill their keys.



Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enums?


Answer



Depending upon use case, I would normally use something simple like the following:



abstract class DaysOfWeek
{

const Sunday = 0;
const Monday = 1;
// etc.
}

$today = DaysOfWeek::Sunday;


However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:




abstract class BasicEnum {
private static $constCacheArray = NULL;

private static function getConstants() {
if (self::$constCacheArray == NULL) {
self::$constCacheArray = [];
}
$calledClass = get_called_class();
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);

self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}

public static function isValidName($name, $strict = false) {
$constants = self::getConstants();

if ($strict) {
return array_key_exists($name, $constants);

}

$keys = array_map('strtolower', array_keys($constants));
return in_array(strtolower($name), $keys);
}

public static function isValidValue($value, $strict = true) {
$values = array_values(self::getConstants());
return in_array($value, $values, $strict);
}

}


By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:



abstract class DaysOfWeek extends BasicEnum {
const Sunday = 0;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;

const Thursday = 4;
const Friday = 5;
const Saturday = 6;
}

DaysOfWeek::isValidName('Humpday'); // false
DaysOfWeek::isValidName('Monday'); // true
DaysOfWeek::isValidName('monday'); // true
DaysOfWeek::isValidName('monday', $strict = true); // false
DaysOfWeek::isValidName(0); // false


DaysOfWeek::isValidValue(0); // true
DaysOfWeek::isValidValue(5); // true
DaysOfWeek::isValidValue(7); // false
DaysOfWeek::isValidValue('Friday'); // false


As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).



Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.



How to use SharedPreferences in Android to store, fetch and edit values





I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?


Answer



To obtain shared preferences, use the following method
In your activity:



SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);



To read preferences:



String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());


To edit and save preferences




Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();


The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:



/samples/android-/ApiDemos directory


Edit==>




I noticed, it is important to write difference between commit() and apply() here as well.



commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.



apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.


python - what does n += 2 in this def?







I have a def function looks like:



def s(xs, n, m):
t = []

while n < m:
t.append(xs[n])
n += 2
return t


I understand the above code by t.append(xs[n]), but have no idea what n += 2 means here.



Any help will be appreciated.
Thanks

json - Post an array of objects from an HTML form using Flask?

I want to generate this JSON object containing an array of objects from form inputs:



{
"network":[
{"layer_type": "conv2d", "num_filters": 16, "kernel_size": 2, "padding": "valid", "stride": 2},
{"layer_type": "max_pool2d", "num_filters": 16, "kernel_size": 2, "padding": "valid", "stride": 2},
{"layer_type": "conv2d", "num_filters": 32, "kernel_size": 3, "padding": "valid", "stride": 2}
]
}



Is there a way I can do this using Flask?



Update



Here's what the form looks like:



form with array of objects




As for the snippet of html code dynamically generated:
















  • Edit: Since this question is being marked as duplicate I'm going to add more info. I want to achieve something like this in this question but using Flask:



    {"students" => [
    {
    "first" => "foo",
    "last" => "bar",

    "age" => "21"
    },
    {
    "first" => "baz",
    "last" => "qux",
    "age" => "19"
    }
    ]}



    It does work with Ruby according to the accepted answer there by having this kind of form:















    But I want to know how to do it using Flask.

    javascript - check to see if exactly two out of three booleans are true?



    I need to test to see if exactly two out of three booleans are true.



    Something like this:




    if((a && b && !c) || (a && !b && c) || (!a && b && c)){
    //success
    }


    Is this the most direct way to go about this? Does anyone know of a shortcut / shorthand?


    Answer



    To check if exactly two are equal to true:



    [a, b, c].filter(Boolean).length === 2;



    References:




    Thursday 29 March 2018

    Match (a AND b) vs (a OR b) in PHP regex

    I'm trying to search through some files in PHP and I want to give the user a choice between matching any or every term.



    E.g.: Search terms: [apple,banana]



    Is it possible to return only files that have both words in it?




    Also my OR would use the following:



    $s_terms = "(" . implode("|", explode(",", $s_terms)) . ")";



    I want to separate terms with , and use it in a RegEx match like (apple|banana). Does the above code do that?



    Thank you in forward



    EDIT:




    The other question did not answer my question, but I found something that works:
    (.*apple.*banana.*)

    sql - Characters that must be escaped in Tsql

    I was looking for a list of special characters that must be escaped in ms sql server but could not find one and most of answers I saw for the similar questions advised to use Parameterised queries.. which I am already doing but the framework I am using does not does any escaping for me.



    Thus I thought I will give a bunch of those a try and see which one fails.... and I tried a simple query



    select * from x where value = ''


    in such query I tried almost all the characters I could find on my keyboard and all of them seem to work... besides the Singe Quote.. that one fails.




    Thus I want to know the list of characters that are invalid and must be escaped in ms sql server - tsql and do not want to take the risk of just escaping the single quote and leave the rest that could cause trouble



    Appreciate your help

    Can interfaces have static methods or java class stati'fy interface method?

    The following is allowed:-




    public interface JustImplementMe
    {
    public void ClimbMountain();
    }


    The following is not allowed:-



    public interface StaticMethodInterface
    {

    public static void Climb();
    }


    The following is allowed:-



    public class Classic implements JustImplementMe
    {
    public void ClimbMountain()
    {


    }
    }


    The following is not allowed:-



     public class ClassicMusic implements JustImplementMe    
    {
    public static void ClimbMountain()

    {
    // static method cannot hide the instance method in JustImplementMe
    }
    }


    Why is it so? Thanks.

    analysis - What was Frank? - Movies & TV



    During the film Donnie Darko, Donnie occasionally talks with Frank, who we end up finding out at the end of the film is a guy that Donnie shot because he accidentally ran over his girlfriend. Is Frank a manifestation of Donnie's consience, having premonitioned what was going to happen in the future? If not, what was Frank supposed to be?


    Answer




    The real-life Frank that runs over Donnie's girlfriend is Elizabeth's (Donnie's sister) boyfriend. We see him drive past Donnie at the start of the movie after dropping her off at home shortly before the engine crashes into the house. You can see this sequence of events more clearly at the end of the film.



    The Frank that Donnie speaks to throughout the movie is a Messenger sent to warn Donnie of the impending end of the world. The characters that are killed in the alternate universe are manipulated by whomever is helping Donnie save the world. They are known as Manipulated Dead and are briefly explained in the book from the director's cut.


    C++ adding numbers from input file




    I am trying to open files with list of int numbers. I just want to output the total number of numbers in the file, and add together all the numbers from the file.



    This is the part that I am having problems with:



    void workFunc(ifstream& myInput, string fileName, int& count, int& sum)

    {
    //int count = 0;

    //int sum = 0;
    int num;
    myInput >> num;

    while (myInput.good())
    {
    myInput >> num;
    count++;
    sum += num;
    }


    }


    It is giving me the right count, but not adding the numbers together properly every time.


    Answer



    You don't count the first thing you read, but you count the last thing twice. So you get the count right by accident, but of course get the sum wrong unless the first and last values happen to be the same.



    You read something into num and then enter the loop. The first thing your loop does is read into num again, discarding the previous value. So the first value doesn't get counted. You then increment count and add it to sum whether or not the read succeeded, which counts the last value twice.




    You want this:



    myInput >> num;

    while (myInput.good())
    {
    // First count the value that we just read
    count++;
    sum += num;


    // Then read the next value
    myInput >> num;
    }

    bash - Difference between single and double quotes in awk



    I have this awk statement:



    glb_library="my_library"
    awk "

    /^Direct Dependers of/ { next }
    /^---/ { next }
    /^$glb_library:/ { ver=\$0; next }
    { gsub(/[[:space:]]/, '', \$0); print ver':'\$0 }
    " file


    Basically, I have enclosed the awk code in double quotes so that the shell variable glb_library is expanded. I have made sure to escape the $ character to prevent the shell from expanding $0. Followed the guidance from here.



    awk gives me this error:




    awk: syntax error at source line 5
    context is
    { gsub(/[[:space:]]/, >>> ' <<<


    I want to understand:




    • Is it legal to use single quotes inside awk? Why is '' not a null string like "" is?


    • Does awk treat single and double quotes differently?



    My code worked after I escaped the single quotes with backslashes and used \"\" to represent the null string instead of ''.


    Answer



    Based on the comments above by awk experts and some research, I am posting this answer:




    • awk strings are enclosed in double quotes, not single quotes; more precisely: single quotes are not string delimiters in awk, unlike shell

    • awk attaches no special meaning to single quotes and they need to be enclosed in double quotes if used in string literals


    • it is best to use single quotes to wrap awk statements on command line, unlike OP's code that's using double quotes (Ed pointed this out clearly)



    Further clarification:




    • "" is the null string in awk, not ''

    • to use single quotes in an awk string literal, enclose them in double quotes, as in "Ed's answers are great!"

    • other techniques followed while handling single quotes in awk are:




      a) use a variable, as in awk -v q="'" '{ print q }' ...



      b) use octal or hex notation, as in awk '{ print "\047"$0"\047" }' ...







    Relevant documentation here.


    sql - When to use single quotes, double quotes, and backticks in MySQL



    I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.




    Example:



    $query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';


    Also, in the above example, consider that table, col1, val1, etc. may be variables.



    What is the standard for this? What do you do?




    I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.


    Answer



    Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.



    Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.



    MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.



    So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.




    None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).



    Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.



    Backtick (`)
    table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
    ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`)
    VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())
    ";
    ↑↑↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑↑↑↑↑

    Unquoted keyword ─────┴┴┴┘ │ │ │ │ │ │ │││││
    Single-quoted (') strings ───────────┴────┴──┴────┘ │ │ │││││
    Single-quoted (') DATE ───────────────────────────┴──────────┘ │││││
    Unquoted function ─────────────────────────────────────────┴┴┴┴┘


    Variable interpolation



    The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).




    // Same thing with some variable replacements
    // Here, a variable table name $table is backtick-quoted, and variables
    // in the VALUES list are single-quoted
    $query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";


    Prepared statements



    When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:




    // PDO example with named parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";

    // MySQLi example with ? parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";


    Characters requring backtick quoting in identifiers:



    According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:





    ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)




    You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.


    javascript - JSON to Initialize Data in Service

    I'm developing a small AngularJS app and I'm currently struggling with creating a service.


    I have a service that serves as a backend for providing contacts (name, address...).
    Until now they were hard-coded as an array in the service (instance.contacts=[...]), but now I'm trying to read them from a json file :


    myModule.factory('contactService', ['$http',function ($http) {
    var instance = {};
    $http.get('contacts.json').success(function (data) {
    instance.contacts = data;
    });
    return instance;
    }]);

    I see in my browser console that the file has been read successfully, but I don't see any change on-screen.


    So I tried the following instead, and it worked :


    myModule.factory('contactService', ['$http',function ($http) {
    var instance = {
    contacts:[]
    };
    $http.get('contacts.json').success(function (data) {
    angular.forEach(data, function(item) {
    instance.contacts.push(item);
    });
    });
    return instance;
    }]);

    I don't know why the second code snippet works, and not the first. Could someone please help me understand ?

    'horror' tag wiki - Movies & TV



    A genre of fiction in which events are focused on shocking or scaring the viewer by inducing feelings of terror or horror. Use this tag when asking questions pertaining to the overall genre of horror.




    Horror fiction is a broad genre of fiction that is designed to scare or shock the viewer. Such movies or shows include events that induce feelings of fear or terror in the viewer.




    The horror genre includes a number of more specific sub-genres, though most horror films tend to mix elements from different sub-genres. Some of the more popular are:




    • Psychological Thriller - relies more heavily on subtle or implied terror, sound effects, and hidden/unseen antagonises; Rosemary's Baby, The Shining

    • Slasher - Focuses on a single or small number of serial killers that commit multiple violent and gory murders on screen. Frequently includes elements of the supernatural - Friday 13th, Nightmare on Elm Street, Halloween

    • Gothic Horror - One of the oldest types of horror, frequently includes a romance as a core plot-line; Dracula, Sleepy Hollow, Nosferatu

    • Splatter - Includes scenes of extreme or excessive violence and gore; Saw, Hostel

    • Zombie Horror - Depicts a world being taken over by zombies; Dawn of the Dead, 28 Days Later




    Horror films frequently include several tropes that are unique to the genre; the presence of these tropes is often a defining characteristic of a horror film.

    vba - Close excel application using Powershell



    I am initiating a macro in a workbook from powershell (to automate a process). The below in powershell opens the excel workbook and runs the macro without visualizing the process.



    The issue is even though I do not see the macro running, the new instance of excel generated from the macro is still open.



    # start Excel
    $excel = New-Object -comobject Excel.Application

    #open file
    $FilePath = 'C:\file\Book1.xlsm'
    $workbook = $excel.Workbooks.Open($FilePath)


    #access the Application object and run a macro
    $app = $excel.Application
    $app.Run("macro")


    #close excel
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
    Start-Sleep 1
    'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count
    Remove-Variable $excel

    exit $LASTEXITCODE


    The excel file still comes up as a process in task manager and is taking up memory space.



    How do I have powershell completely close the instance of the excel application that opens through the macro?



    enter image description here



    Any help greatly appreciated!


    Answer



    Try using Quit method before you release COM object, like this:



    $excel.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
    Remove-Variable excel

    javascript - What does (function($) {})(jQuery); mean?

    Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.



    1. (
    2. function(){}
    3. )
    4. ()



    Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help



    1. function(){ .. }
    2. (1)
    3. 2()


    You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.



    An example of how it would be used.




    (function(doc){

    doc.location = '/';

    })(document);//This is passed into the function above


    As for the other questions about the plugins:




    Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.



    Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.



    Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

    javascript - remove object from js array knowing it's Id




    I have array of object inside razor view (javascript code).



    var myArr;



    on page load contains let's say 10 objects.



    one object has following structure



     - Id  
    - Name



    how can I remove object from js array knowing it's Id?


    Answer



    Try like this



    var id = 2;
    var list = [{
    Id: 1,
    Name: 'a'
    }, {
    Id: 2,

    Name: 'b'
    }, {
    Id: 3,
    Name: 'c'
    }];
    var index = list.map(x => {
    return x.Id;
    }).indexOf(id);

    list.splice(index, 1);

    console.log(list);


    JSFIDDLE



    Or you can utilize .filter()



    Like this



    var id = 2;

    var list = [{
    Id: 1,
    Name: 'a'
    }, {
    Id: 2,
    Name: 'b'
    }, {
    Id: 3,
    Name: 'c'
    }];

    var lists = list.filter(x => {
    return x.Id != id;
    })
    console.log(lists);


    DEMO


    javascript - Update a div with jQuery

    I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:




    page.html:















    If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:



    http://37.187.90.121:3874/currentsong?sid=1&c=


    The output of this source is like this:





    Inna - Un Momento



    If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?



    EDIT1:
    ok is a policy problem, how i can resolve it?




    EDIT2:+
    The proxy php page solution don't work.
    I have make this php page:



    echo file_get_contents("http://37.187.90.121:3874/currentsong");
    ?>


    But i have this error message:




    Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2

    Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2


    Edit3:
    The external service give me a javascript to get the information:



    window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('Unavailable'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++


    You can check it at this link:
    http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js



    Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.



    This script give me an output like:





    "Radio Name - Author - Title of song"




    and this is a link (if you click on it open another page).



    I need to get only "Author - Title of song" with no link. Any idea?



    Edit4:



    I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:













    sss




    casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

    In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...