Saturday, June 30, 2018

java - ArrayList.add throws ArrayIndexOutOfBoundsException

I am trying to add a object to a ArrayList and its throwing ArrayIndexOutOfBoundsException
Following is the code



private void populateInboxResultHolder(List inboxErrors){
inboxList = new ArrayList();
try{
inboxHolder = new InboxResultHolder();
//Lots of Code
inboxList.add(inboxHolder);

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


And the exception is



[3/7/12 15:41:26:715 UTC] 00000045 SystemErr     R java.lang.ArrayIndexOutOfBoundsException
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at java.util.ArrayList.add(ArrayList.java:378)

[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.populateInboxResultHolder(InboxSearchBean.java:388)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.searchInboxErrors(InboxSearchBean.java:197)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.viewInbox(InboxSearchBean.java:207)


But according to the signature of ArrayList.add it should not throw this exception.
Please help.

javascript - Explain the encapsulated anonymous function syntax




Summary



Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but this doesn't: function(){}();?






What I know



In JavaScript, one creates a named function like this:




function twoPlusTwo(){
alert(2 + 2);
}
twoPlusTwo();


You can also create an anonymous function and assign it to a variable:



var twoPlusTwo = function(){
alert(2 + 2);

};
twoPlusTwo();


You can encapsulate a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately:



(function(){
alert(2 + 2);
})();



This is useful when creating modularised scripts, to avoid cluttering up the current scope, or global scope, with potentially conflicting variables - as in the case of Greasemonkey scripts, jQuery plugins, etc.



Now, I understand why this works. The brackets enclose the contents and expose only the outcome (I'm sure there's a better way to describe that), such as with (2 + 2) === 4.






What I don't understand



But I don't understand why this does not work equally as well:




function(){
alert(2 + 2);
}();


Can you explain that to me?


Answer



It doesn't work because it is being parsed as a FunctionDeclaration, and the name identifier of function declarations is mandatory.




When you surround it with parentheses it is evaluated as a FunctionExpression, and function expressions can be named or not.



The grammar of a FunctionDeclaration looks like this:



function Identifier ( FormalParameterListopt ) { FunctionBody }


And FunctionExpressions:



function Identifieropt ( FormalParameterListopt ) { FunctionBody }



As you can see the Identifier (Identifieropt) token in FunctionExpression is optional, therefore we can have a function expression without a name defined:



(function () {
alert(2 + 2);
}());


Or named function expression:




(function foo() {
alert(2 + 2);
}());


The Parentheses (formally called the Grouping Operator) can surround only expressions, and a function expression is evaluated.



The two grammar productions can be ambiguous, and they can look exactly the same, for example:




function foo () {} // FunctionDeclaration

0,function foo () {} // FunctionExpression


The parser knows if it's a FunctionDeclaration or a FunctionExpression, depending on the context where it appears.



In the above example, the second one is an expression because the Comma operator can also handle only expressions.



On the other hand, FunctionDeclarations could actually appear only in what's called "Program" code, meaning code outside in the global scope, and inside the FunctionBody of other functions.




Functions inside blocks should be avoided, because they can lead an unpredictable behavior, e.g.:





if (true) {
function foo() {
alert('true');
}
} else {

function foo() {
alert('false!');
}
}

foo(); // true? false? why?






The above code should actually produce a SyntaxError, since a Block can only contain statements (and the ECMAScript Specification doesn't define any function statement), but most implementations are tolerant, and will simply take the second function, the one which alerts 'false!'.



The Mozilla implementations -Rhino, SpiderMonkey,- have a different behavior. Their grammar contains a non-standard Function Statement, meaning that the function will be evaluated at run-time, not at parse time, as it happens with FunctionDeclarations. In those implementations we will get the first function defined.






Functions can be declared in different ways, compare the following:



1- A function defined with the Function constructor assigned to the variable multiply:




var multiply = new Function("x", "y", "return x * y;");


2- A function declaration of a function named multiply:



function multiply(x, y) {
return x * y;
}



3- A function expression assigned to the variable multiply:



var multiply = function (x, y) {
return x * y;
};


4- A named function expression func_name, assigned to the variable multiply:



var multiply = function func_name(x, y) {

return x * y;
};

android - View.SurfaceView, why its member, mSurfaceHolder, returns null from getSurface()?

I am studying Android Game Development these days. I come across a problem about SurfaceView\SurfaceHolder. When I read the source code of View/SurfaceView.java in android sdk 22, I am confused. following is the code:




public class SurfaceView extends MockView {
...
public SurfaceHolder getHolder() {
return mSurfaceHolder;
}


private SurfaceHolder mSurfaceHolder = new SurfaceHolder() {
...

@Override
public Surface getSurface() { return null; }
@Override
public Canvas lockCanvas() { return null; }
...

}

}


I know, mSurfaceHolder.getSurface()\lockCanvas are very important, but it returns null! So, I think this mSurfaceHolder may be dealt with some other steps. But I have learned an example about SurfaceView, but I didn't figout out any special steps to deal with mSurfaceHolder, the example's code is as following:





public class SurfaceViewTest extends Activity {

String TAG = "SurfaceViewTest";

FastRenderView surfaceView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_surface_view_test);
surfaceView = new FastRenderView(this);
setContentView(surfaceView);
}


@Override
protected void onResume() {
super.onResume();
surfaceView.doResume();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
// present.

getMenuInflater().inflate(R.menu.menu_surface_view_test, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();


//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

/**

* customized surfaceview class
*/
public class FastRenderView extends SurfaceView implements Runnable {

boolean running = false;
SurfaceHolder holder = null;
Thread thread = null;

public FastRenderView(Context context) {
super(context);

// holder
// getHolder() returns a SurfaceHolder implementation, it
// isn't null, but it contains nothing.
holder = getHolder();
if (holder == null)
Log.e(TAG, "failed to get valid holder");

}

public void doResume() {

thread = new Thread(this);
thread.start();
running = true;
}

public Random rand = new Random();
@Override
public void run() {
while (running) {
// from android sdk 22, SurfaceView.java, we can see, this

// holder's getSurface() returns null.
// but why? it returns null, so here it an exception
// should be thrown out!
if (!holder.getSurface().isValid()) {
continue;
}

Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.e(TAG, "get an invalid canvas to draw");

continue;
}
canvas.drawRGB(
rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255));
holder.unlockCanvasAndPost(canvas);

// sleep
try {

Thread.sleep(1000);
}
catch(Exception e) {
e.printStackTrace();
}
}
Log.i(TAG, "running ...");
}

public void doPause() {


running = false;
while (true) {
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}

}
}



Thanks in advance!

'citizen-kane' tag wiki - Movies & TV



Relates to the film by Orson Welles concerning the life of a newspaper owner, politician and magnate as presented through the eyes of an investigative reporter.







There is no tag wiki for this tag … yet!



Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.




All registered users may propose new tag wikis.



(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)


mysqli - Php mysqi bind_param Number of variables doesn't match number of parameters in prepared statement




This has to be a newbie mistake, but I'm not seeing it. Here is a snippet from my code:



$mysqli = mysqli_connect($dbCredentials['hostname'], 
$dbCredentials['username'], $dbCredentials['password'],
$dbCredentials['database']);

if ($mysqli->connect_error) {
throw new exception( 'Connect Error (' . $mysqli->connect_errno . ') '

. $mysqli->connect_error);
}

$stmt = $mysqli->prepare("SELECT DISTINCT model FROM vehicle_types
WHERE year = ? AND make = '?' ORDER by model");

$stmt->bind_param('is', $year, $make);

$stmt->execute();



When I echo out the values for $year and $make, I am seeing values, but when I run this script, I get a null value, and the following warning appears in my log file:



PHP Warning:  mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement


In this case, year is in the database in type int(10), and I have tried passing a copy that had been cast as an int, and make is a varchar(20) with the utf8_unicode_ci encoding. Am I missing something?


Answer



Your prepared statement is wrong, it should be:




$stmt = $mysqli->prepare("SELECT DISTINCT model FROM vehicle_types WHERE year = ? AND make = ? ORDER by model");


The single quotes made that ? be the value not a marker. It will already be a string because you are casting as such with bind_param('is'


php - Syntax error creating mysql database tables

CREATE TABLE items (

'itemnumber' int(10) NOT NULL AUTO_INCREMENT,
'itemname' varchar(255),
'slot' varchar(255),
'level' varchar(255),
'class' varchar(255),
'white1' varchar(255),
'white2' varchar(255),
'white3' varchar(255),
'purple1' varchar(255),
'purple2' varchar(255),

'purple3' varchar(255),
'id1' varchar(255),
'id2' varchar(255),
'id3' varchar(255),
'green1' varchar(255),
'green2' varchar(255),
'green3' varchar(255),
'icon' varchar(255),
'dateadded' varchar(255),
PRIMARY KEY ('itemnumber')

) ENGINE=MyISAM;


returns the following:




ERROR 1064 (42000): 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 ''itemnumber' int(10) NOT NULL AUTO_INCREMENT,
'itemname' varchar(255),
'slot' va' at line 2


Which method should I use to manually bootstrap my AngularJS?



I have seen the following:



angular.bootstrap(document, ['TodoApp']);

angular.bootstrap(angular.element("body")[0], ['TodoApp']);


Also the AngularJS documentation mentions this which I don't really understand.



   angular.element(document).ready(function() {
angular.bootstrap(document);
});



Is there any difference between these methods? In particular what is the last method from the Angular docs doing? Is one any better to use than the other?


Answer



They are roughly the same, with a few differences:






angular.bootstrap(document, ['TodoApp']);


This will work if you have your scripts loaded at the end of the page (instead of in the header).




Otherwise, the DOM will not be loaded at the time of bootrsaping the app (there won't be any template to be compiled, the directives won't have any effect).



This one works: plnkr



This one doesn't: plnkr






angular.bootstrap(angular.element("body")[0], ['TodoApp']);



The same as before, using body as the root of the application. It uses a selector that is not available in jqLite, so you need to have full jQuery included in the app.



I'm not sure what is the advantage of using body instead document, but probably has something to do with e2e testing, as explained in this comment



plknr







angular.element(document).ready(function() {
angular.bootstrap(document);
});


This one actually waits for the DOM to be loaded, so it will work even if you include your scripts in the header.



This is basically the same as jQuery's $(document).ready( , but using jqLite's angular.element.







In the last example, no modules are being passed to the bootstrap function, most likely you will need to declare your main module, unless your app consists only on controllers in the global namespace.



So the last option will be like the following, in order to be similar to the other two:



angular.element(document).ready(function() {
angular.bootstrap(document, ['TodoApp']);
});



plknr



I guess that most of the time the safest bet is using this last approach.


javascript - setTimeout in for-loop does not print consecutive values




I have this script:



for (var i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}


But 3 is alerted both times, instead of 1 then 2.



Is there a way to pass i, without writing the function as a string?


Answer



You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.



function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 100);
}

for (var i = 1; i <= 2; ++i)
doSetTimeout(i);


If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.



edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout() — take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.



Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.



If what you need is for the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:



function doScaledTimeout(i) {
setTimeout(function() {
alert(i);
}, i * 5000);
}


(With a 100 millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.



Update



Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:



for (let i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}


The let declaration, unlike var, will itself cause there to be a distinct i for each iteration of the loop.


virtual machine - What are ODEX files in Android?

After some android apps installed, I found that it will change to odex file (not apk) in smartphone.
How does it happens? Who can teach me, I am very interested about it.

android - Class not found using the boot class loader; no stack trace available



i got simmilar post but nothing working
i have android studio 2.3.1
gradle version 2.3.1
appcompat-v7:25.3.1



I create a new project by android studio(one that is automatically created by Android Studio(Hello Word)). I haven't write any thing in it.




When i install app using usb via android studio it works perfectly
but same app if i open it from it's icon ,i got these errors



One more i noticed that size of apk is 500-600kb ,early it used to be around for hello world(default by android studio) Apk 2.3Mb




FATAL EXCEPTION: main
Process: in.codebucket.check, PID: 32397
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.codebucket.check/in.codebucket.check.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "in.codebucket.check.MainActivity" on path: DexPathList[[zip file "/data/app/in.codebucket.check-1/base.apk"],nativeLibraryDirectories=[/data/app/in.codebucket.check-1/lib/x86, /vendor/lib, /system/lib]]



at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassNotFoundException: Didn't find class "in.codebucket.check.MainActivity" on path: DexPathList[[zip file "/data/app/in.codebucket.check-1/base.apk"],nativeLibraryDirectories=[/data/app/in.codebucket.check-1/lib/x86, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 

at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Suppressed: java.lang.ClassNotFoundException: in.codebucket.check.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)

at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 12 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available



My xml





xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.codebucket.check.MainActivity">

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />



My MainActivity




public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}}


my Manifest



package="in.codebucket.check">


android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"


android:theme="@style/AppTheme">













gradle(Module:App)



apply plugin: 'com.android.application'

android {
compileSdkVersion 25

buildToolsVersion "25.0.2"
defaultConfig {
applicationId "in.codebucket.check"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {

release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}}}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-
core:2.2.2', {

exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}


gradle(Project)




// Top-level build file where you can add configuration options common to  
all sub-projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'


// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}


task clean(type: Delete) {
delete rootProject.buildDir
}

Answer



Got the solution ,it is happening because of instant run,
Just disable it



Goto :




Android Studio --> File --> Setting --> Build, execution, deploy -->  Instant run.

Friday, June 29, 2018

parameter passing - Java pass by reference




What is the difference between this 2 codes:



Code A:



Foo myFoo;
myFoo = createfoo();


where




public Foo createFoo()
{
Foo foo = new Foo();
return foo;
}


Vs. Code B:



Foo myFoo;

createFoo(myFoo);

public void createFoo(Foo foo)
{
Foo f = new Foo();
foo = f;
}


Are there any differences between these 2 pieces of codes?



Answer



Java always passes arguments by value NOT by reference.






Let me explain this through an example:



public class Main
{
public static void main(String[] args)

{
Foo f = new Foo("f");
changeReference(f); // It won't change the reference!
modifyReference(f); // It will modify the object that the reference variable "f" refers to!
}
public static void changeReference(Foo a)
{
Foo b = new Foo("b");
a = b;
}

public static void modifyReference(Foo c)
{
c.setAttribute("c");
}
}


I will explain this in steps:





  1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



    Foo f = new Foo("f");


    enter image description here


  2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



    public static void changeReference(Foo a)



    enter image description here


  3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



    changeReference(f);


    enter image description here


  4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".




    Foo b = new Foo("b");


    enter image description here


  5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



    enter image description here





  6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".




    enter image description here


  7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



    enter image description here




I hope you understand now how passing objects as arguments works in Java :)


c++ - are C functions declared in headers guaranteed to be in the global namespace as well as std?

So this is something that I've always wondered but was never quite sure about. So it is strictly a matter of curiosity, not a real problem.


As far as I understand, whenyou do something like #include everything (except macros of course) are declared in the std:: namespace. Every implementation that I've ever seen does this by doing something like the following:


#include 
namespace std {
using ::abort;
// etc....
}

Which of course has the effect of things being in both the global namespace and std. Is this behavior guaranteed? Or is it possible that an implementation could put these things in std but not in the global namespace? The only way I can think of to do that would be to have your libstdc++ implement every c function itself placing them in std directly instead of just including the existing libc headers (because there is no mechanism to remove something from a namespace). Which is of course a lot of effort with little to no benefit.


The essence of my question is, is the following program strictly conforming and guaranteed to work?


#include 
int main() {
::printf("hello world\n");
}

EDIT: The closest I've found is this (17.4.1.2p4):



Except as noted in clauses 18 through
27, the contents of each header cname
shall be the same as that of the
corresponding header name.h, as
specified in ISO/IEC 9899:1990
Programming Languages C (Clause 7), or
ISO/IEC:1990 Programming Languages—C
AMENDMENT 1: C Integrity, (Clause 7),
as appropriate, as if by inclusion. In
the C + + Standard Library, however,
the declarations and definitions
(except for names which are defined as
macros in C) are within namespace
scope (3.3.5) of the namespace std.



which to be honest I could interpret either way. "the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C" tells me that they may be required in the global namespace, but "In the C + + Standard Library, however, the declarations and definitions (except for names
which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std." says they are in std (but doesn't specify any other scoped they are in).

php - Parse error: syntax error, unexpected T_LNUMBER, expecting ')'

I'm getting Parse error: syntax error, unexpected T_LNUMBER, expecting ')'



This is the code I'm using:




function getLevelByXp($xp)
{
$listlevel=array(0,40,60,100,200,350,550,800,1113,1504,1993,2604,3368,4323,5517,7010,8876,11209,13659,16232,18934,21771,24750,27878,31162,34610,38230,42031,46022,50213,54614,59235,64087,69182,74532,80150,86049,92243,98747,105576,112746,120275,128180,136480,145195,154346,163955,174044,184637,195760,207439,219702,232578,246098,260294,275200,290851,307285,324541,342660,361685,381661,402636,424660,447785,472066,497561,524331,552440,581954,612944,645484,679651,715526,756782,804226,858787,921532,993689,1076670,1172098,1281840,1408043,1553176,1720079,1912017,2132746,2386584,2678498,3014199,3400255,3844219,4354778,4941921,5617135,6393631,7286601,8313517,9494470,2016089205);
$j=count($listlevel);
for($i=0;$i<$j;$i++){
if($listlevel[$i] > $xp) break;
}
return $i;
}



This is the line where i'm getting that error $listlevel=array(0,40,60,100,200,350,550,800,1113,1504,1993,2604,3368,4323,5517,7010,8876,11209,13659,16232,18934,21771,24750,27878,31162,34610,38230,42031,46022,50213,54614,59235,64087,69182,74532,80150,86049,92243,98747,105576,112746,120275,128180,136480,145195,154346,163955,174044,184637,195760,207439,219702,232578,246098,260294,275200,290851,307285,324541,342660,361685,381661,402636,424660,447785,472066,497561,524331,552440,581954,612944,645484,679651,715526,756782,804226,858787,921532,993689,1076670,1172098,1281840,1408043,1553176,1720079,1912017,2132746,2386584,2678498,3014199,3400255,3844219,4354778,4941921,5617135,6393631,7286601,8313517,9494470,2016089205);



Edit: Here is my full code from pastebin file



function getLevelByXp($xp){ 
$listlevel=array(0,40,60,100,200,350,550,800,1113,1504,1993,2604,3368,4323,5517,7010,8876,11209,13659,16232,18934,21771,24750,27878,31162,34610,38230,42031,46022,50213,54614,59235,64087,69182,74532,80150,86049,92243,98747,105576,112746,120275,128180,136480,145195,154346,163955,174044,184637,195760,207439,219702,232578,246098,260294,275200,290851,307285,324541,342660,361685,381661,402636,424660,447785,472066,497561,524331,552440,581954,612944,645484,679651,715526,756782,804226,858787,921532,993689,1076670,1172098,1281840,1408043,1553176,1720079,1912017,2132746,2386584,2678498,3014199,3400255,38 44219,4354778,4941921,5617135,6393631,7286601,8313517,9494470,2016089205);
$j=count($listlevel);
for($i=0;$i<$j;$i++){

if($listlevel[$i] > $xp) break;
}
return $i;
}
if(isset($_POST['fbid'])){
$cid = round(rand() * 0x40000000);
$postdata=array('neighbors'=>"",'client_id'=>$cid) ;
$result=sendPost("http://dynamicmw.socialpointgames.com/appsfb/menvswomen/srvsexwars/get_player_info.php?USERID=$_POST[fbid]&user_key=$_POST[ukey]&spdebug=1",$postdata);
$payload = explode(';',$result);
$data = json_decode($payload[1],true);

if($data['result']=='error'){
$str= 'Error : bad user id | bad user key';
goto habis;
}
$str .= "=========================
";
$str .= "Cash : ".number_format($data['playerInfo']['cash'],0,',','.')."
";
$str .= "Gold : ".number_format($data['map']['gold'],0,',','.')."
";
$str .= "Oil : ".number_format($data['map']['oil'],0,',','.')."
";
$str .= "Wood : ".number_format($data['map']['wood'],0,',','.')."
";
$str .= "Steel : ".number_format($data['map']['steel'],0,',','.')."
";

$str .= "XP : ".number_format($data['map']['xp'],0,',','.')."
";
$str .= "Level : ".$data['map']['level']."
";
$str .= "=========================
";
$cmd[]=array(0,'set_variables',array(),array(0,(integer) $_POST['xp'],(integer)$_POST['gold'],(integer)$_POST['wood'],(integer)$_POST['oil'],(integer)$_POST['steel'],(integer)$_POST['cash'],0));
$cmd[]=array(0,'level_up',array(getLevelByXp($data['map']['xp']+(integer)$_POST['xp'])),array(0,0,0,0,0,0,0,0));
if(sendCommand($_POST['fbid'],$_POST['ukey'],'1.5.0',$cmd)){
$result=sendPost("http://dynamicmw.socialpointgames.com/appsfb/menvswomen/srvsexwars/get_player_info.php?USERID=$_POST[fbid]&user_key=$_POST[ukey]&spdebug=1",$postdata);
$payload = explode(';',$result);
$data = json_decode($payload[1],true);
$str .= "Cash : ".number_format($data['playerInfo']['cash'],0,',','.')."
";

$str .= "Gold : ".number_format($data['map']['gold'],0,',','.')."
";
$str .= "Oil : ".number_format($data['map']['oil'],0,',','.')."
";
$str .= "Wood : ".number_format($data['map']['wood'],0,',','.')."
";
$str .= "Steel : ".number_format($data['map']['steel'],0,',','.')."
";
$str .= "XP : ".number_format($data['map']['xp'],0,',','.')."
";
$str .= "Level : ".$data['map']['level']."
";
$str .= "=========================
";
}
habis:
echo $str;

}
function sendPost($url,$data=null){
if($data!=null){
$postdata=http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'timeout' => 30,
'header' => "Content-type: application/x-www-form-urlencoded\r\n"."Content-Length: ".strlen($postdata)."\r\n",
'content' => $postdata

)
);
}else $opts = array('http'=>array('timeout'=>30));
$result=file_get_contents($url,false,stream_context_create($opts));
return $result;
}
function sendCommand($fbid,$ukey,$flash,$cmd){
$cmd = json_encode(array('publishActions'=>"0",'commands' =>$cmd,'flashVersion'=>$flash,'first_number'=>1,'t ries'=>1,'ts'=>time(),'accessToken'=>""));
$hash = hash_hmac('sha256',$cmd,'4vVSD8dftv6hdfb1Hnk9');
$cmd=array('data'=>$hash.';'.$cmd);

$result=sendPost("http://dynamicmw.socialpointgames.com/appsfb/menvswomen/srvsexwars/command.php?USERID=$fbid&user_key=$ukey&spdebug=1" ,$cmd);
$result = json_decode($result,true);
return $result;
}

?>

c# - VS 2010, NUNit, and "The breakpoint will not currently be hit. No symbols have been loaded for this document"



Using Windows 7 32 bit, VS 2010, .NET 4 DLL, NUnit (2.5.5) to unit test the application. I'm currently getting the following error; seen plenty of posts and tried the following:





  1. restart machine

  2. restart VS

  3. delete bin/obj and reload

  4. clean/rebuild



But I cannot get NUnit to hit my breakpoints when running;



I set the NUNit test project to point to the nunit.exe, and to load the testing .NET 4 DLL, but when I run it doesn't find the breakpoint, "no symbols have been loaded". I tried debug >windows > modules, it doesn't even show my unit testing project when I run it.




I found this, to use the nunit agent: http://groups.google.com/group/nunit-discuss/browse_thread/thread/5680d7def5b6982f



But I get an error when I use the nunit agent too. I was using nunit-agent-x86.exe, but I get a system.formatexception and it crashes...



Can anybody help?



Thanks.


Answer



The resolution was: start NUnit stand alone, then in VS 2010, do debug > attach to process, and attach to the nunit-agent.exe process, not the nunit process. Nunit process still didn't do it for me.


C++ passing by reference or by value?

I am new to programming and here is a simple question about how passing by reference works. In this program, I am calculating roots of a quadratic equation.



void getCoefficients(double &a, double &b, double &c);
void solveQuadratic(double a, double b, double c, double &x1, double &x2);

void printRoots(double x1, double x2);

void error(string msg);

int main() {
double a,b,c,x1,x2;
getCoefficients(a,b,c);
solveQuadratic(a,b,c,x1,x2);
printRoots(x1,x2);
return 0;

}


So, my question is I seem to be passing values to getCoefficients and solveQuadratic from main program but in the function definitions of getCoefficients and solveQuadratic, I seem to be accepting references as arguments and am confused as to how this works?

sql server - return a string of comma delimited numbers from a sql query




How can I return a comma delimited string using SQL Server?



select ID, 
(<>)
from TableA A


and have it return results like:




1, '11, 12'
2, '22, 33'

Answer



You can use STUFF(), See Demo Here



SELECT  ID
,STUFF((SELECT ', ' + CAST(data AS VARCHAR(10)) [text()]
FROM B
WHERE TableBId = A.ID

FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') Comma_Output
FROM A
GROUP BY ID

c - Why does sizeof(x++) not increment x?



Here is the code compiled in dev c++ windows:



#include 

int main() {

int x = 5;
printf("%d and ", sizeof(x++)); // note 1
printf("%d\n", x); // note 2
return 0;
}


I expect x to be 6 after executing note 1. However, the output is:



4 and 5



Can anyone explain why x does not increment after note 1?


Answer



From the C99 Standard (the emphasis is mine)




6.5.3.4/2



The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.




javascript - nodejs express: store parameters in variable

I am still new with nodejs, still not sure how to access a variable in a function and call the variable back.




check few links: but im getting really confused. Please help!



Node.JS: How to pass variables to asynchronous callbacks?



How can we access variable from callback function in node.js?



var express = require('express');
var app = express();
var router = express.Router();

var https = require('https').createServer( ssl_options, app);
var io = require('socket.io')( https );
**var user_id;
var room_id;**

router.use(function(req, res, next) {
next();
});

app.use('/chat',router);


router.route( '/chat/:user_id/:room_id' )
.get(function(req,res){

res.sendFile( __dirname + '/index.html' );

user_id = req.param('user_id');
room_id = req.param('room_id');

});


https.listen(3000);

io.on('connection', function(socket){

**console.log ( user_id );
console.log ( room_id );**


});

ruby on rails - When to use nil, blank, empty?




Is there any guidelines on how to differentiate between .nil?, .blank? and .empty??



I'm generally always confused as to when to use them in my application as they all seem to mean the same thing but have different meanings.




Does anyone have any cheat sheet on the gory details?


Answer




language agnostic - What's your most controversial programming opinion?

This is definitely subjective, but I'd like to try to avoid it becoming argumentative. I think it could be an interesting question if people treat it appropriately.




The idea for this question came from the comment thread from my answer to the "What are five things you hate about your favorite language?" question. I contended that classes in C# should be sealed by default - I won't put my reasoning in the question, but I might write a fuller explanation as an answer to this question. I was surprised at the heat of the discussion in the comments (25 comments currently).



So, what contentious opinions do you hold? I'd rather avoid the kind of thing which ends up being pretty religious with relatively little basis (e.g. brace placing) but examples might include things like "unit testing isn't actually terribly helpful" or "public fields are okay really". The important thing (to me, anyway) is that you've got reasons behind your opinions.



Please present your opinion and reasoning - I would encourage people to vote for opinions which are well-argued and interesting, whether or not you happen to agree with them.

python - How to draw bounding box on best matches?

How can I draw a bounding box on best matches in BF MATCHER using Python?

cinema history - Annual revenue for film industry by year adjusted for inflation

Have a theory about my question about the reasoning behind the average length of feature length films, but that theory is based on finding the annual revenue for film industry by year adjusted for inflation.


Do such numbers exist?


Answer


Hmm, there seems to be plenty of sources for total gross per year but none are adjusted for inflation.


Nonetheless, Box Office Mojo have a little explanation detailing how to adjust total gross using annual average ticket prices here. It also has a table of averages stretching back to the early 20th century. The data gets more intermittent the further back you go, but you could probably get sensible numbers from interpolation.


Essentially it boils down to dividing the gross by the ticket price of that year and multiplying by the ticket price of the year you are adjusting to. For example we can do this with BOM's table for yearly domestic gross found here to give


Year    Total (M)  2012-Adjusted (M)
2012 $3,859.80 $3,859.80
2011 $10,174.10 $10,161.27
2010 $10,565.50 $10,605.67
2009 $10,595.50 $11,188.85
2008 $9,630.70 $10,623.28
2007 $9,663.70 $11,124.49
2006 $9,209.50 $11,135.76
2005 $8,840.50 $10,923.05
2004 $9,380.50 $11,963.54
2003 $9,239.70 $12,135.73
2002 $9,155.00 $12,479.79
2001 $8,412.50 $11,771.55
2000 $7,661.00 $11,256.98
1999 $7,448.00 $11,611.84
1998 $6,949.00 $11,734.77
1997 $6,365.90 $10,984.30
1996 $5,911.50 $10,592.55
1995 $5,493.50 $10,001.96
1994 $5,396.20 $10,224.38
1993 $5,154.20 $9,860.21
1992 $4,871.00 $9,295.98
1991 $4,803.20 $9,035.95
1990 $5,021.80 $9,402.52
1989 $5,033.40 $10,041.44
1988 $4,458.40 $8,591.37
1987 $4,252.90 $8,614.57
1986 $3,778.00 $8,065.16
1985 $3,749.20 $8,364.41
1984 $4,031.00 $9,501.64
1983 $3,766.00 $9,468.80
1982 $3,453.00 $9,301.96
1981 $2,966.00 $8,449.90
1980 $2,749.00 $8,093.71

Which seems pretty reasonable. 2002 was such a strong year because it had Spider-Man, a LotR, a Star Wars, and a Harry Potter.


Unfortunately this data only goes back to 1980 so you will have to find another source if you're interested in before then. Also note that the table above is only for the U.S. domestic market; I'm not sure if that's what you want or if you're after worldwide figures.


c - Why does the order of the loops affect performance when iterating over a 2D array?



Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. Could someone explain why this happens?



Version 1



#include 
#include


main () {
int i,j;
static int x[4000][4000];
for (i = 0; i < 4000; i++) {
for (j = 0; j < 4000; j++) {
x[j][i] = i + j; }
}
}



Version 2



#include 
#include

main () {
int i,j;
static int x[4000][4000];
for (j = 0; j < 4000; j++) {

for (i = 0; i < 4000; i++) {
x[j][i] = i + j; }
}
}

Answer



As others have said, the issue is the store to the memory location in the array: x[i][j]. Here's a bit of insight why:



You have a 2-dimensional array, but memory in the computer is inherently 1-dimensional. So while you imagine your array like this:




0,0 | 0,1 | 0,2 | 0,3
----+-----+-----+----
1,0 | 1,1 | 1,2 | 1,3
----+-----+-----+----
2,0 | 2,1 | 2,2 | 2,3


Your computer stores it in memory as a single line:



0,0 | 0,1 | 0,2 | 0,3 | 1,0 | 1,1 | 1,2 | 1,3 | 2,0 | 2,1 | 2,2 | 2,3



In the 2nd example, you access the array by looping over the 2nd number first, i.e.:



x[0][0] 
x[0][1]
x[0][2]
x[0][3]
x[1][0] etc...



Meaning that you're hitting them all in order. Now look at the 1st version. You're doing:



x[0][0]
x[1][0]
x[2][0]
x[0][1]
x[1][1] etc...



Because of the way C laid out the 2-d array in memory, you're asking it to jump all over the place. But now for the kicker: Why does this matter? All memory accesses are the same, right?



No: because of caches. Data from your memory gets brought over to the CPU in little chunks (called 'cache lines'), typically 64 bytes. If you have 4-byte integers, that means you're geting 16 consecutive integers in a neat little bundle. It's actually fairly slow to fetch these chunks of memory; your CPU can do a lot of work in the time it takes for a single cache line to load.



Now look back at the order of accesses: The second example is (1) grabbing a chunk of 16 ints, (2) modifying all of them, (3) repeat 4000*4000/16 times. That's nice and fast, and the CPU always has something to work on.



The first example is (1) grab a chunk of 16 ints, (2) modify only one of them, (3) repeat 4000*4000 times. That's going to require 16 times the number of "fetches" from memory. Your CPU will actually have to spend time sitting around waiting for that memory to show up, and while it's sitting around you're wasting valuable time.



Important Note:




Now that you have the answer, here's an interesting note: there's no inherent reason that your second example has to be the fast one. For instance, in Fortran, the first example would be fast and the second one slow. That's because instead of expanding things out into conceptual "rows" like C does, Fortran expands into "columns", i.e.:



0,0 | 1,0 | 2,0 | 0,1 | 1,1 | 2,1 | 0,2 | 1,2 | 2,2 | 0,3 | 1,3 | 2,3


The layout of C is called 'row-major' and Fortran's is called 'column-major'. As you can see, it's very important to know whether your programming language is row-major or column-major! Here's a link for more info: http://en.wikipedia.org/wiki/Row-major_order


Thursday, June 28, 2018

How can I generate text from a RegEx?

Or "How can I RegEx in reverse?"


specifically I want to take a regex such as wks[0-9][0-9][0-9]


and create a list such as wks001,wks002,wks003, etc


I know the easiest way in this example would be to simply increment the number through addition, but say I want it to be even more sophisticated later on such as [0-9abc] I'd like to use a more sophisticated tool.


preferable would be some windows capable scripting tech, such as vbscript/powershell but I'm open to other alternatives. I guess I kind of thought this might be something that is done all the time by random number generators and such and would be a programming staple, but I lack the understanding to phrase it correctly I think.

Node.js vs .Net performance

I've read a lot about Node.js being fast and able to accommodate large amounts of load. Does anyone have any real world evidence of this vs other frameworks, particularly .Net? Most of the articles i've read are anecdotal or don't have comparisons to .Net.




Thanks

jquery - JavaScript is it possible to use var in your .html




Is it possible to use var codes in your HTML file but in a .js file you can have the rest of the script?




for example my code is









this




img




but is it possible to do this, if so how do I tell JavaScript to search for the id's between the Body Tags because the script is in the Head Tag and it only searches in the head tag but I don't wont the script in the body tag because it makes it easier to access in the head tag if this is not possible then is it possible to include the var in the html file and the script below the vars in a separate .js file? My example below should explain better.



html file










this



img





js file



// First Image
image.src = "your image link for first image here";
link.title = "Movie title ex Batman (2008)";
tooltipname.href = "link to site when movie is clicked";
namebelowimg.innerHTML = "movie name here";
// End First Image



If you need a better example go here


Answer



You getElementById won't work because scripts are executed before body is rendered. Simplest way to make it work is to move script tag after the body.



Other way might be to wait for body to load





php - What way is the best way to hash a password?




I'm working on a website that should be very safe for the users, so I need the hash the passwords. Usually I'm using the MD5, but I read that it doesn't safe anymore. So I tried PHPass, but then I read that it also has been cracked. So I tried password_hash() of PHP 5.5, but I use HostGator, and the PHP there is 5.4. Also I want to be able to add salt without knowing it (like time() * userid()), like in the password_hash().



The hash strength is very important to me because I want to be 100% sure that my users are safe. So is there a way that very safe and not something like SHA that will be hacked soon?


Answer



Use this library which provides forward compatibility with the password_* functions.



Example usage :



require_once("password.php"); // imports the library, assuming it's in the same directory as the current script


$password = "HelloStackOverflow"; // example password

$hash = password_hash($password, PASSWORD_BCRYPT); // here's the hash of the previous password

$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10)); // you can set the "complexity" of the hashing algorithm, it uses more CPU power but it'll be harder to crack, even though the default is already good enough

if (password_verify($password, $hash)) { // checking if a password is valid
/* Valid */
} else {

/* Invalid */
}

dalvikvm-heap grow heap (frag case) while upload video android

I am facing problem whiel uploading the video from the 4x devices.I know that only 15 sec vedio recodring will create a 30 mb file in samsung S2 but while I am trying to upload the video on the php server first it shows the msg like
D/dalvikvm(7638): GC_FOR_ALLOC freed 263K, 9% free 12838K/14087K, paused 13ms, total 13ms
I/dalvikvm-heap(7638): Grow heap (frag case) to 14.481MB for 1048592-byte allocation
D/dalvikvm(7638): GC_FOR_ALLOC freed <1K, 9% free 13861K/15175K, paused 22ms, total 22ms
D/dalvikvm(7638): GC_CONCURRENT freed <1K, 9% free 13862K/15175K, paused 12ms+2ms, total 27ms



I know it is the memory managment concept and device memory dependent but I want a real solution for it as I am stuck here from quite a few days.
Below is my code to call and upload the video to server.

public void newmethod( String Imageurl ) throws ClientProtocolException, IOException

{
byte[] data ;
int bytenumber,bufferSize,bytesRead;
int maxBufferSize = 1*1024*1024;
DataOutputStream dos = null;
//File sourceFile = searchForFileInExternalStorage("video.3gp");

Log.e("in the method the path", ""+Imageurl);

FileInputStream fileInputStream = new FileInputStream(Imageurl);

bytenumber = fileInputStream.available();
Log.e("in the method the the size of the file is", ""+bytenumber);
// dos = new DataOutputStream(conn.getOutputStream());
bufferSize = Math.min(bytenumber, maxBufferSize);
data = new byte[bufferSize];
//ProgressDialog pr = new ProgressDialog(getApplicationContext());
// pr.addContentView(getCurrentFocus(), null);
// read file and write it into form...
bytesRead = fileInputStream.read(data, 0, bufferSize);


while (bytesRead > 0) {
// dos.write(data, 0, bufferSize);
bytenumber = fileInputStream.available();
bufferSize = Math.min(bytenumber, maxBufferSize);
bytesRead = fileInputStream.read(data, 0, bufferSize);
}

// pr.show();



HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://67.52.165.116/Kakz/mobiles/uploadvideo");
ByteArrayBody bab = new ByteArrayBody( data, Imageurl);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("user_video", bab);

FormBodyPart bodyPart=new FormBodyPart("title", new StringBody(title));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("desc", new StringBody(description));
reqEntity.addPart(bodyPart);

bodyPart=new FormBodyPart("source", new StringBody("android"));
reqEntity.addPart(bodyPart);
postRequest.setEntity(reqEntity);
final HttpResponse response = httpClient.execute(postRequest);
// FileInputStream fileInputStream = new FileInputStream(response.getEntity().getContent());


runOnUiThread(new Runnable() {
public void run() {


//stuff that updates ui

BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {

// TODO Auto-generated catch block
e1.printStackTrace();
}
String line = null;

try {
while((line = in.readLine()) != null) {
System.out.println(line);

titleText.setText("");

descriptionText.setText("");
// Toast.makeText(getApplicationContext(), "Video Uploaded successfully", Toast.LENGTH_LONG).show();

if (line.equalsIgnoreCase("Its too Heavy")) {
// pr.dismiss();
// titleText.setText("");
//descriptionText.setText("");
Toast.makeText(getApplicationContext(), "Video size is too heavy", Toast.LENGTH_LONG).show();

}


else if (line.equalsIgnoreCase("Error")) {
// pr.dismiss();
// titleText.setText("");
//descriptionText.setText("");
Toast.makeText(getApplicationContext(), "Error uploading video", Toast.LENGTH_LONG).show();


}


else if (line.equalsIgnoreCase("Uploaded")) {
//pr.dismiss();
//titleText.setText("");
//descriptionText.setText("");
Toast.makeText(getApplicationContext(), "Video uploaded successfully", Toast.LENGTH_LONG).show();

}

}
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Please let me know that how I should manage the code to get it right.
Any help would be appreciated ASAP`enter code here`

c++ - Difference between push_back and emplace_back in the case of a temporary value

Consider this snippet:




#include 

struct A
{
A(int b): m_b(b) { }

private:
int m_b;
};


int main()
{
std::vector vec;

vec.push_back( A(3) );

vec.emplace_back( 3 );
}



In that particular case where a temporary value is passed, is there any difference between the 2 calls that a compiler won’t optimize away? Should I prefer one to the other?

Performance optimisations of x86-64 assembly - Alignment and branch prediction

I’m currently coding highly optimised versions of some C99 standard library string functions, like strlen(), memset(), etc, using x86-64 assembly with SSE-2 instructions.




So far I’ve managed to get excellent results in terms of performance, but I sometimes get weird behaviour when I try to optimise more.



For instance, adding or even removing some simple instructions, or simply reorganising some local labels used with jumps completely degrades the overall performances. And there’s absolutely no reason in terms of code.



So my guess is that there is some issues with code alignment, and/or with branches which get mispredicted.



I know that, even with the same architecture (x86-64), different CPUs have different algorithms for branch prediction.



But is there some general advices, when developing for high performances on x86-64, about code alignment and branch prediction?




In particular, about alignment, should I ensure all labels used by jump instructions are aligned on a DWORD?



_func:
; ... Some code ...
test rax, rax
jz .label
; ... Some code ...
ret
.label:

; ... Some code ...
ret


In the previous code, should I use an align directive before .label:, like:



align 4
.label:



If so, is it enough to align on a DWORD when using SSE-2?



And about branch prediction, is there a «preffered» way to organize the labels used by jump instructions, in order to help the CPU, or are today's CPUs smart enough to determine that at runtime by counting the number of times a branch is taken?



EDIT



Ok, here's a concrete example - here's the start of strlen() with SSE-2:



_strlen64_sse2:
mov rsi, rdi

and rdi, -16
pxor xmm0, xmm0
pcmpeqb xmm0, [ rdi ]
pmovmskb rdx, xmm0
; ...


Running it 10'000'000 times with a 1000 character string gives about 0.48 seconds, which is fine.
But it does not check for a NULL string input. So obviously, I'll add a simple check:



_strlen64_sse2:

test rdi, rdi
jz .null
; ...


Same test, it runs now in 0.59 seconds. But if I align the code after this check:



_strlen64_sse2:
test rdi, rdi
jz .null

align 8
; ...


The original performances are back. I used 8 for alignment, as 4 doesn't change anything.
Can anyone explain this, and give some advices about when to align, or not to align code sections?



EDIT 2



Of course, it's not as simple as aligning every branch target. If I do it, performances will usually get worse, unless some specific cases like above.

marvel cinematic universe - How much of Thor is based on actual mythology?

Not having read the comics at all and not being a huge mythology buff, I have only the general knowledge of some Norse mythology and Thor's (comic/movie version) background.


Obviously the names and some settings are the same. But what I'm referring to is the general setting (Asgard, the bifrost, etc), the character's personality (Loki is known as a trickster God if my recollection serves properly) and countless other examples (Mjolnir, Odinsleep, Frost Giants, etc).


How much of the Thor universe is based off of actual Norse mythology and how much of it is either created from the comic for the movie and so on?


Answer


Ok, I'll attempt an answer, based only on the movie (not the comics) and my small bit of knowledge about Norse mythology (paired with up-to-date Wiki-research).


First of all the movie depicts the gods as being just a kind of powerful aliens (wandering on the same paths as Stargate and its farther-in-spirit Erich von Däniken already did). Indeed this isn't that bad an idea, as in Norse mythology (like in Greek mythology and I guess many other pantheistic religions) the gods aren't that almighty as the monotheistic gods. They can be killed by other gods, fight with each other, and aren't completely all-knowing by birth (I think Odin had to sacrifice his eye for gaining the power to see the future). They didn't even create the world on their own, I think. So they are indeed just another race of very powerful, maybe even immortal, but not allmighty, beings in the mythology.


Then Odin is indeed the highest of the Aesir, the higher of the two god races, so it makes sense for him to be the king of Asgard (the home of the Aesir) in the movie. Furthermore he is the father of Thor. But as said, he doesn't lose his eye in a battle against giants, as depicted in the movie, but sacrifices it in order to gain future-seeing powers.


But in mythology everybody knows Loki is the son of two giants (one of them being Laufey, as mentioned in the movie) and nobody would think he is Odin's son. But even in mythology he is still counted to the Aesir and not to the giants, and is indeed somehow like a brother to Thor, with them getting into many adventures together (but also fighting each other when Thor is fed up with Loki's tricks). In mythology he is a very ambivalent character, too. He is both intelligent and intrigant and often helps the other gods with his cunning, while other times trying to sabotage them and even fighting on the side of the giants and other monsters in the final apocalyptic battle. But he doesn't offensively try to kill all humans or even fight the other gods directly, as in the movie, though he would be best choice if the movie wants an intelligent and powerful enemy for Thor.




EDIT: It seems he is even banned from Asgard by Odin after he has gone too far with one of his intrigues and is actually the leader of the giants during Ragnarok (the final battle). This might be seen as parallel to the movie.




Thor is depicted not that inaccurately, I think, being very powerful and sometimes a bit carefree. He does more count on strength than on intelligence or tactics, but he's not dumb. But I think they made him a bit more likeable/friendly in the movie (/comic?) to better appeal to the audience. He also wields the hammer Mjölnir in mythology (though I'm not sure it has to be a hammer in all sources), whose feature to always return to Thor was also depicted in the movie. But he doesn't really have such a gang of co-fighters and friends as in the movie and I don't know in which way they are based on "real" gods (though one of them is called Sif, which is the name of Thor's wife).


The movie depicts the world Jötunheim to be the home of the Frost Giants, although they are actually from Niflheim (but this is just a minor deviation, as Jötunheim is the home of the Giants). But the giants and frost giants are indeed the main antagonists of the gods and Thor would often venture into their lands to beat them up, sometimes together with Loki.


The Bifröst is actually the rainbow bridge between Midgard and Asgard and is indeed guarded by Heimdall, so it makes sense, in the context of the movie, to turn it into some hyperspace teleporter or something the like. But it does just connect Midgard (say Earth) to Asgard and doesn't connect all the 9 worlds together, I think, as depicted in the movie (maybe they have to go over Midgard to reach the other worlds in the mythology?).


And this whole Destroyer thing (this guarding robot misused by Loki) is utter crap. And I think also this urn the giants want to steal doesn't have any real background.




EDIT: Regarding the Odinsleep from the comics, I don't think this has any real background. When in real life you say "someone is going to Odinsleep" means he is entering a very deep and long sleep. This goes back to a particular legend as part of the Sigurd-legend (I'm not sure how far this applies to the more modern and mythology-cleaned Nibelung-legend), where Odin made Brynhild sink into a very long sleep for doing something wrong (I think for killing or rather choosing the wrong men in her role as Valkyrie, at least in the versions where she is a Valkyrie). But I don't think there is any mythological instance of Odin himself going into a long and vulnerable sleep.




These were just some small and superficial things I could come up with. All in all I think they did quite a good job to transfer all those mythological things into some kind of "super-powerful aliens"-context and treated the mythological sources not that inaccurately, even if making some errors and creating some things anew (Ok, this robot destroyer thing was really rubbish). But besides that I was indeed surpised how they managed to turn a god into a superhero without hurting Norse mythology that badly (though an expert on the topic may think differently).


performance - Javascript avoid 0.2 + 0.4 = 0.6000000000000001 other than Math.round()

Is there any better way other than



Math.round(0.2+0.4) = 0.6


Actually, I have a series of index 0, 0.02, 0.04, 0.06, 0.08, 0.10 ----

I have to convert it to Array Index 0,1,2,3,4,5-- by dividing by 0.02



JavaScript provides



 0.28/0.02 = 14.000000000000002


I solve this problem by Math.round(0.28/0.02).
I am curious is there any other or better way to solve this problem

How do I check what version of Python is running my script?



How can I check what version of the Python Interpreter is interpreting my script?


Answer



This information is available in the sys.version string in the sys module:



>>> import sys



Human readable:



>>> print(sys.version)  # parentheses necessary in python 3.       
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]


For further processing:



>>> sys.version_info

(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192


To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:



assert sys.version_info >= (2, 5)



This compares major and minor version information. Add micro (=0, 1, etc) and even releaselevel (='alpha','final', etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.


javascript - Setting "checked" for a checkbox with jQuery?



I'd like to do something like this to tick a checkbox using jQuery:




$(".myCheckBox").checked(true);


or



$(".myCheckBox").selected(true);


Does such a thing exist?



Answer



Modern jQuery



Use .prop():



$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);


DOM API




If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:



$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;


The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.



jQuery 1.5.x and below




The .prop() method is not available, so you need to use .attr().



$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);


Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.



For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.



html - How to apply CSS to iframe?

I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?

reactjs - Having services in React application



I'm coming from the angular world where I could extract logic to a service/factory and consume them in my controllers.




I'm trying to understand how can I achieve the same in a React application.



Let's say that I have a component that validates user's password input (it's strength). It's logic is pretty complex hence I don't want to write it in the component it self.



Where should I write this logic? In a store if I'm using flux? Or is there a better option?


Answer



The first answer doesn't reflect the current Container vs Presenter paradigm.



If you need to do something, like validate a password, you'd likely have a function that does it. You'd be passing that function to your reusable view as a prop.




Containers



So, the correct way to do it is to write a ValidatorContainer, which will have that function as a property, and wrap the form in it, passing the right props in to the child. When it comes to your view, your validator container wraps your view and the view consumes the containers logic.



Validation could be all done in the container's properties, but it you're using a 3rd party validator, or any simple validation service, you can use the service as a property of the container component and use it in the container's methods. I've done this for restful components and it works very well.



Providers



If there's a bit more configuration necessary, you can use a Provider/Consumer model. A provider is a high level component that wraps somewhere close to and underneath the top application object (the one you mount) and supplies a part of itself, or a property configured in the top layer, to the context API. I then set my container elements to consume the context.




The parent/child context relations don't have to be near each other, just the child has to be descended in some way. Redux stores and the React Router function in this way. I've used it to provide a root restful context for my rest containers (if I don't provide my own).



(note: the context API is marked experimental in the docs, but I don't think it is any more, considering what's using it).





//An example of a Provider component, takes a preconfigured restful.js
//object and makes it available anywhere in the application
export default class RestfulProvider extends React.Component {
constructor(props){

super(props);

if(!("restful" in props)){
throw Error("Restful service must be provided");
}
}

getChildContext(){
return {
api: this.props.restful

};
}

render() {
return this.props.children;
}
}

RestfulProvider.childContextTypes = {
api: React.PropTypes.object

};





Middleware



A further way I haven't tried, but seen used, is to use middleware in conjunction with Redux. You define your service object outside the application, or at least, higher than the redux store. During store creation, you inject the service into the middleware and the middleware handles any actions that affect the service.



In this way, I could inject my restful.js object into the middleware and replace my container methods with independent actions. I'd still need a container component to provide the actions to the form view layer, but connect() and mapDispatchToProps have me covered there.




The new v4 react-router-redux uses this method to impact the state of the history, for example.





//Example middleware from react-router-redux
//History is our service here and actions change it.

import { CALL_HISTORY_METHOD } from './actions'


/**
* This middleware captures CALL_HISTORY_METHOD actions to redirect to the
* provided history object. This will prevent these actions from reaching your
* reducer or any middleware that comes after this one.
*/
export default function routerMiddleware(history) {
return () => next => action => {
if (action.type !== CALL_HISTORY_METHOD) {
return next(action)
}


const { payload: { method, args } } = action
history[method](...args)
}
}




c# - How to load entities into private collections using the entity framework

I have a POCO domain model which is wired up to the entity framework using the new ObjectContext class.



public class Product

{
private ICollection _photos;

public Product()
{
_photos = new Collection();
}

public int Id { get; set; }
public string Name { get; set; }

public virtual IEnumerable Photos
{
get
{
return _photos;
}
}

public void AddPhoto(Photo photo)
{

//Some biz logic
//...
_photos.Add(photo);
}
}


In the above example i have set the Photos collection type to IEnumerable as this will make it read only. The only way to add/remove photos is through the public methods.



The problem with this is that the Entity Framework cannot load the Photo entities into the IEnumerable collection as it's not of type ICollection.




By changing the type to ICollection will allow callers to call the Add mentod on the collection itself which is not good.



What are my options?



Edit:



I could refactor the code so it does not expose a public property for Photos:



public class Product

{
public Product()
{
Photos = new Collection();
}

public int Id { get; set; }
public string Name { get; set; }
private Collection Photos {get; set; }


public IEnumerable GetPhotos()
{
return Photos;
}

public void AddPhoto(Photo photo)
{
//Some biz logic
//...
Photos.Add(photo);

}

}


And use the GetPhotos() to return the collection. The other problem with the approach is that I will loose the change tracking abilities as I cannot mark the collection as Virtual - It is not possible to mark a property as private virtual.



In NHibernate I believe it's possible to map the proxy class to the private collection via configuration. I hope that this will become a feature of EF4. Currently i don't like the inability to have any control over the collection!

c++ - Is < faster than



I'm reading a book where the author says that if( a < 901 ) is faster than if( a <= 900 ).



Not exactly as in this simple example, but there are slight performance changes on loop complex code. I suppose this has to do something with generated machine code in case it's even true.


Answer



No, it will not be faster on most architectures. You didn't specify, but on x86, all of the integral comparisons will be typically implemented in two machine instructions:





  • A test or cmp instruction, which sets EFLAGS

  • And a Jcc (jump) instruction, depending on the comparison type (and code layout):

    • jne - Jump if not equal --> ZF = 0

    • jz - Jump if zero (equal) --> ZF = 1

    • jg - Jump if greater --> ZF = 0 and SF = OF

    • (etc...)








Example (Edited for brevity) Compiled with $ gcc -m32 -S -masm=intel test.c



    if (a < b) {
// Do something 1
}



Compiles to:



    mov     eax, DWORD PTR [esp+24]      ; a
cmp eax, DWORD PTR [esp+28] ; b
jge .L2 ; jump if a is >= b
; Do something 1
.L2:



And



    if (a <= b) {
// Do something 2
}


Compiles to:



    mov     eax, DWORD PTR [esp+24]      ; a

cmp eax, DWORD PTR [esp+28] ; b
jg .L5 ; jump if a is > b
; Do something 2
.L5:


So the only difference between the two is a jg versus a jge instruction. The two will take the same amount of time.







I'd like to address the comment that nothing indicates that the different jump instructions take the same amount of time. This one is a little tricky to answer, but here's what I can give: In the Intel Instruction Set Reference, they are all grouped together under one common instruction, Jcc (Jump if condition is met). The same grouping is made together under the Optimization Reference Manual, in Appendix C. Latency and Throughput.




Latency — The number of clock cycles that are required for the
execution core to complete the execution of all of the μops that form
an instruction.



Throughput — The number of clock cycles required to
wait before the issue ports are free to accept the same instruction
again. For many instructions, the throughput of an instruction can be

significantly less than its latency




The values for Jcc are:



      Latency   Throughput
Jcc N/A 0.5


with the following footnote on Jcc:





7) Selection of conditional jump instructions should be based on the recommendation of section Section 3.4.1, “Branch Prediction Optimization,” to improve the predictability of branches. When branches are predicted successfully, the latency of jcc is effectively zero.




So, nothing in the Intel docs ever treats one Jcc instruction any differently from the others.



If one thinks about the actual circuitry used to implement the instructions, one can assume that there would be simple AND/OR gates on the different bits in EFLAGS, to determine whether the conditions are met. There is then, no reason that an instruction testing two bits should take any more or less time than one testing only one (Ignoring gate propagation delay, which is much less than the clock period.)







Edit: Floating Point



This holds true for x87 floating point as well: (Pretty much same code as above, but with double instead of int.)



        fld     QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; Compare ST(0) and ST(1), and set CF, PF, ZF in EFLAGS
fstp st(0)
seta al ; Set al if above (CF=0 and ZF=0).

test al, al
je .L2
; Do something 1
.L2:

fld QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; (same thing as above)
fstp st(0)
setae al ; Set al if above or equal (CF=0).

test al, al
je .L5
; Do something 2
.L5:
leave
ret

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...