Programs & Examples On #New operator

new is a language construct that dynamically allocates memory from free store and initialises the memory using the constructor.

Create a folder inside documents folder in iOS apps

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

What uses are there for "placement new"?

I've used it to construct objects allocated on the stack via alloca().

shameless plug: I blogged about it here.

Why should C++ programmers minimize use of 'new'?

new is the new goto.

Recall why goto is so reviled: while it is a powerful, low-level tool for flow control, people often used it in unnecessarily complicated ways that made code difficult to follow. Furthermore, the most useful and easiest to read patterns were encoded in structured programming statements (e.g. for or while); the ultimate effect is that the code where goto is the appropriate way to is rather rare, if you are tempted to write goto, you're probably doing things badly (unless you really know what you're doing).

new is similar — it is often used to make things unnecessarily complicated and harder to read, and the most useful usage patterns can be encoded have been encoded into various classes. Furthermore, if you need to use any new usage patterns for which there aren't already standard classes, you can write your own classes that encode them!

I would even argue that new is worse than goto, due to the need to pair new and delete statements.

Like goto, if you ever think you need to use new, you are probably doing things badly — especially if you are doing so outside of the implementation of a class whose purpose in life is to encapsulate whatever dynamic allocations you need to do.

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

Yes, it is.

I realized that it automatically invokes the destructor... is this normal?

Yes

Make sure that you did not double delete your object.

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

How to add to an existing hash in Ruby

You can use double splat operator which is available since Ruby 2.0:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

Add onclick event to newly added element in JavaScript

I don't think you can do that this way. You should use :

void addEventListener( 
  in DOMString type, 
  in EventListener listener, 
  in boolean useCapture 
); 

Documentation right here.

Is "delete this" allowed in C++?

This is an old, answered, question, but @Alexandre asked "Why would anyone want to do this?", and I thought that I might provide an example usage that I am considering this afternoon.

Legacy code. Uses naked pointers Obj*obj with a delete obj at the end.

Unfortunately I need sometimes, not often, to keep the object alive longer.

I am considering making it a reference counted smart pointer. But there would be lots of code to change, if I was to use ref_cnt_ptr<Obj> everywhere. And if you mix naked Obj* and ref_cnt_ptr, you can get the object implicitly deleted when the last ref_cnt_ptr goes away, even though there are Obj* still alive.

So I am thinking about creating an explicit_delete_ref_cnt_ptr. I.e. a reference counted pointer where the delete is only done in an explicit delete routine. Using it in the one place where the existing code knows the lifetime of the object, as well as in my new code that keeps the object alive longer.

Incrementing and decrementing the reference count as explicit_delete_ref_cnt_ptr get manipulated.

But NOT freeing when the reference count is seen to be zero in the explicit_delete_ref_cnt_ptr destructor.

Only freeing when the reference count is seen to be zero in an explicit delete-like operation. E.g. in something like:

template<typename T> class explicit_delete_ref_cnt_ptr { 
 private: 
   T* ptr;
   int rc;
   ...
 public: 
   void delete_if_rc0() {
      if( this->ptr ) {
        this->rc--;
        if( this->rc == 0 ) {
           delete this->ptr;
        }
        this->ptr = 0;
      }
    }
 };

OK, something like that. It's a bit unusual to have a reference counted pointer type not automatically delete the object pointed to in the rc'ed ptr destructor. But it seems like this might make mixing naked pointers and rc'ed pointers a bit safer.

But so far no need for delete this.

But then it occurred to me: if the object pointed to, the pointee, knows that it is being reference counted, e.g. if the count is inside the object (or in some other table), then the routine delete_if_rc0 could be a method of the pointee object, not the (smart) pointer.

class Pointee { 
 private: 
   int rc;
   ...
 public: 
   void delete_if_rc0() {
        this->rc--;
        if( this->rc == 0 ) {
           delete this;
        }
      }
    }
 };

Actually, it doesn't need to be a member method at all, but could be a free function:

map<void*,int> keepalive_map;
template<typename T>
void delete_if_rc0(T*ptr) {
        void* tptr = (void*)ptr;
        if( keepalive_map[tptr] == 1 ) {
           delete ptr;
        }
};

(BTW, I know the code is not quite right - it becomes less readable if I add all the details, so I am leaving it like this.)

int *array = new int[n]; what is this function actually doing?

The statement basically does the following:

  1. Creates a integer array of 'n' elements
  2. Allocates the memory in HEAP memory of the process as you are using new operator to create the pointer
  3. Returns a valid address (if the memory allocation for the required size if available at the point of execution of this statement)

Create an empty object in JavaScript with {} or new Object()?

The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...

Passing arguments to C# generic new() of templated type

You need to add where T: new() to let the compiler know that T is guaranteed to provide a default constructor.

public static string GetAllItems<T>(...) where T: new()

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

How does delete[] know it's an array?

just define a destructor inside a class and execute your code with both syntax

delete pointer

delete [] pointer

according to the output u can find the solutions

Using "Object.create" instead of "new"

You have to make a custom Object.create() function. One that addresses Crockfords concerns and also calls your init function.

This will work:

var userBPrototype = {
    init: function(nameParam) {
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};


function UserB(name) {
    function F() {};
    F.prototype = userBPrototype;
    var f = new F;
    f.init(name);
    return f;
}

var bob = UserB('bob');
bob.sayHello();

Here UserB is like Object.create, but adjusted for our needs.

If you want, you can also call:

var bob = new UserB('bob');

How to open in default browser in C#

Did you try Processas mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?

You could use

Process myProcess = new Process();

try
{
    // true is the default, but it is important not to set it to false
    myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

What is the 'new' keyword in JavaScript?

Javascript is a dynamic programming language which supports the object oriented programming paradigm, and it use used for creating new instances of object.

Classes are not necessary for objects - Javascript is a prototype based language.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

When should I use the new keyword in C++?

If your variable is used only within the context of a single function, you're better off using a stack variable, i.e., Option 2. As others have said, you do not have to manage the lifetime of stack variables - they are constructed and destructed automatically. Also, allocating/deallocating a variable on the heap is slow by comparison. If your function is called often enough, you'll see a tremendous performance improvement if use stack variables versus heap variables.

That said, there are a couple of obvious instances where stack variables are insufficient.

If the stack variable has a large memory footprint, then you run the risk of overflowing the stack. By default, the stack size of each thread is 1 MB on Windows. It is unlikely that you'll create a stack variable that is 1 MB in size, but you have to keep in mind that stack utilization is cumulative. If your function calls a function which calls another function which calls another function which..., the stack variables in all of these functions take up space on the same stack. Recursive functions can run into this problem quickly, depending on how deep the recursion is. If this is a problem, you can increase the size of the stack (not recommended) or allocate the variable on the heap using the new operator (recommended).

The other, more likely condition is that your variable needs to "live" beyond the scope of your function. In this case, you'd allocate the variable on the heap so that it can be reached outside the scope of any given function.

In what cases do I use malloc and/or new?

new will initialise the default values of the struct and correctly links the references in it to itself.

E.g.

struct test_s {
    int some_strange_name = 1;
    int &easy = some_strange_name;
}

So new struct test_s will return an initialised structure with a working reference, while the malloc'ed version has no default values and the intern references aren't initialised.

Print in new line, java

You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.

Since Java 1.7

System.lineSeparator()

Pre Java 1.7

System.getProperty("line.separator")

Java FileOutputStream Create File if not exists

Before creating a file, it's needed to create all the parent's directories.

Use yourFile.getParentFile().mkdirs()

What is parsing in terms that a new programmer would understand?

Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.

Your content must have a ListView whose id attribute is 'android.R.id.list'

Exact way I fixed this based on feedback above since I couldn't get it to work at first:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>

MainActivity.java:

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

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
    android:key="upgradecategory"
    android:title="Upgrade" >
    <Preference
        android:key="download"
        android:title="Get OnCall Pager Pro"
        android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>

How to check if command line tools is installed

Open your terminal and check to see if you have Xcode installed already with this:

xcode-select -p

in return, if you get this:

/Library/Developer/CommandLineTools

That means you have that Xcode is installed.

Another way you can check would you if you have "HomeBrew" installed you can use the following command to see if you have Xcode and the version:

brew config

And finally, if you don't have the Xcode follow this link to download the Xcode from the Appstore. Xcode from the App Store.

Good Luck.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Simply change,

dispatch_async(kBgQueue, ^{
     NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:   [NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
     dispatch_async(dispatch_get_main_queue(), ^{
        cell.poster.image = [UIImage imageWithData:imgData];
     });
 });

Into

    dispatch_async(kBgQueue, ^{
         NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:   [NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
         cell.poster.image = [UIImage imageWithData:imgData];
         dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
         });
     });

angular js unknown provider

I just had a similar problem. The error said the same the in the question, tried to solve it with the answer of pkozlowski.opensource and Ben G, which both are correct and good answers.

My problem was indeed different with the same error:

in my HTML-Code I had the initialisation like this...

<html ng-app>

A bit further down I tried to do something like this:

<div id="cartView" ng-app="myApp" ng-controller="CartCtrl">

I got rid of the first one... then it worked... obviously you can't initialise ng-app twice or more times. fair enough.

I totaly forgot about the first "ng-app" and got totaly frustrated. Maybe this is gonna help someone oneday...

Is it possible to listen to a "style change" event?

How about jQuery cssHooks?

Maybe I do not understand the question, but what you are searching for is easily done with cssHooks, without changing css() function.

copy from documentation:

(function( $ ) {

// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
  // If not, output an error message
  throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}

// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
  $.cssHooks[ "someCSSProp" ] = {
    get: function( elem, computed, extra ) {
      // Handle getting the CSS property
    },
    set: function( elem, value ) {
      // Handle setting the CSS value
    }
  };
});

})( jQuery ); 

https://api.jquery.com/jQuery.cssHooks/

Rails: update_attribute vs update_attributes

Great answers. notice that as for ruby 1.9 and above you could (and i think should) use the new hash syntax for update_attributes:

Model.update_attributes(column1: "data", column2: "data")

Command line tool to dump Windows DLL version?

There is an command line application called "ShowVer" at CodeProject:

ShowVer.exe command-line VERSIONINFO display program

As usual the application comes with an exe and the source code (VisualC++ 6).

Out outputs all the meta data available:

On a German Win7 system the output for user32.dll is like this:

VERSIONINFO for file "C:\Windows\system32\user32.dll":  (type:0)
  Signature:       feef04bd
  StrucVersion:    1.0
  FileVersion:     6.1.7601.17514
  ProductVersion:  6.1.7601.17514
  FileFlagsMask:   0x3f
  FileFlags:       0
  FileOS:          VOS_NT_WINDOWS32
  FileType:        VFT_DLL
  FileDate:        0.0
 LangID: 040704B0
  CompanyName       : Microsoft Corporation
  FileDescription   : Multi-User Windows USER API Client DLL
  FileVersion       : 6.1.7601.17514 (win7sp1_rtm.101119-1850)
  InternalName      : user32
  LegalCopyright    : ® Microsoft Corporation. Alle Rechte vorbehalten.
  OriginalFilename  : user32
  ProductName       : Betriebssystem Microsoft« Windows«
  ProductVersion    : 6.1.7601.17514
 Translation: 040704b0

How to trim a list in Python

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]

How can I pass data from Flask to JavaScript in a template?

Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.

Specify a data attribute like so:

<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>

Then access it in a static JavaScript file like so:

// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);

// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));

JavaScript - onClick to get the ID of the clicked button

This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)

_x000D_
_x000D_
function reply_click(e) {
  console.log(e.target.id);
}
_x000D_
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
_x000D_
_x000D_
_x000D_

MySQL - Cannot add or update a child row: a foreign key constraint fails

I solved my 'foreign key constraint fails' issues by adding the following code to the start of the SQL code (this was for importing values to a table)

SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT;
SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS;
SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION;
SET NAMES utf8;
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO';
SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0; 

Then adding this code to the end of the file

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT;
SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS;
SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION;
SET SQL_NOTES=@OLD_SQL_NOTES; 

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Making a mocked method return an argument that was passed to it

If you have Mockito 1.9.5 or higher, there is a new static method that can make the Answer object for you. You need to write something like

import static org.mockito.Mockito.when;
import static org.mockito.AdditionalAnswers.returnsFirstArg;

when(myMock.myFunction(anyString())).then(returnsFirstArg());

or alternatively

doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());

Note that the returnsFirstArg() method is static in the AdditionalAnswers class, which is new to Mockito 1.9.5; so you'll need the right static import.

Select All distinct values in a column using LINQ

var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

The

(condition) ? /* value to return if condition is true */ 
            : /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

AlertDialog.Builder with custom layout and EditText; cannot access view

You can write:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

 // ...Irrelevant code for customizing the buttons and title

LayoutInflater inflater = this.getLayoutInflater(); 

View dialogView= inflater.inflate(R.layout.alert_label_editor, null);                    
dialogBuilder.setView(dialogView);

Button button = (Button)dialogView.findViewById(R.id.btnName);

   button.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         //Commond here......

       }
   });

EditText editText = (EditText)
dialogView.findViewById(R.id.label_field); 

editText.setText("test label"); 

dialogBuilder.create().show();

Laravel: PDOException: could not find driver

Solution 1:

1. php -v

Output: PHP 7.3.11-1+ubuntu16.04.1+deb.sury.org+1 (cli)

2. sudo apt-get install php7.3-mysql

Solution 2:

Check your DB credentials like DB Name, DB User, DB Password

How to get the size of a string in Python?

The most Pythonic way is to use the len(). Keep in mind that the '\' character in escape sequences is not counted and can be dangerous if not used correctly.

>>> len('foo')
3
>>> len('\foo')
3
>>> len('\xoo')
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

Basic HTTP and Bearer Token Authentication

Standard (https://tools.ietf.org/html/rfc6750) says you can use:

  • Form-Encoded Body Parameter: Authorization: Bearer mytoken123
  • URI Query Parameter: access_token=mytoken123

So it's possible to pass many Bearer Token with URI, but doing this is discouraged (see section 5 in the standard).

Python: How to increase/reduce the fontsize of x and y tick labels?

It is simpler than I thought it would be.

To set the font size of the x-axis ticks:

x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)

To do it for the y-axis ticks:

y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

The arguments rotation and fontsize can easily control what I was after.

Reference: http://matplotlib.org/api/axes_api.html

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/*Maximum value that can be entered is 2,147,483,647
 * Program to convert entered number into string
 * */
import java.util.Scanner;

public class NumberToWords 
{

public static void main(String[] args) 
{
    double num;//for taking input number
    Scanner obj=new Scanner(System.in);
    do
    {
        System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
        num=obj.nextDouble();
        if(num<=2147483647)//checking if entered number exceeds maximum integer value
        {
            int number=(int)num;//type casting double number to integer number
            splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
        }
        else
            System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
    }while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{   //splitNumber array-contains the numbers in pair of 3 digits
    int splitNumber[]=new int[4],temp=number,i=0,index;
    //splitting number into pair of 3
    if(temp==0)
        System.out.println("zero");
    while(temp!=0)
    {
        splitNumber[i++]=temp%1000;
        temp/=1000;
    }
    //passing each pair of 3 digits to another function
    for(int j=i-1;j>-1;j--)
    {   //toWords function will split pair of 3 digits to separate digits
        if(splitNumber[j]!=0)
            {toWords(splitNumber[j]);
        if(j==3)//if the number contained more than 9 digits
            System.out.print("billion,");
        else if(j==2)//if the number contained more than 6 digits & less than 10 digits
            System.out.print("million,");
        else if(j==1)
            System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
            }
            }       
}
//function that splits number into individual digits
public static void toWords(int number)
    //splitSmallNumber array contains individual digits of number passed to this function
{   int splitSmallNumber[]=new int[3],i=0,j;
    int temp=number;//making temporary copy of the number
    //logic to split number into its constituent digits

    while(temp!=0)
    {
        splitSmallNumber[i++]=temp%10;
        temp/=10;
    }
    //printing words for each digit
    for(j=i-1;j>-1;j--)
      //{   if the digit is greater than zero
        if(splitSmallNumber[j]>=0)
            //if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
        {   if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
            {
                switch(splitSmallNumber[j])
                {

                    case 1:System.out.print("one ");break;
                    case 2:System.out.print("two ");break;
                    case 3:System.out.print("three ");break;
                    case 4:System.out.print("four ");break;
                    case 5:System.out.print("five ");break;
                    case 6:System.out.print("six ");break;
                    case 7:System.out.print("seven ");break;
                    case 8:System.out.print("eight ");break;
                    case 9:System.out.print("nine ");break;

            }

        }
        //if digit is at 2nd place
        if(j==1)
        {       //if digit at 2nd place is 0 or 1
                if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
                System.out.print("hundred ");
            switch(splitSmallNumber[1])
            {   case 1://if digit at 2nd place is 1 example-213
                        switch(splitSmallNumber[0])
                        {
                        case 1:System.out.print("eleven ");break;
                        case 2:System.out.print("twelve ");break;
                        case 3:System.out.print("thirteen ");break;
                        case 4:System.out.print("fourteen ");break;
                        case 5:System.out.print("fifteen ");break;
                        case 6:System.out.print("sixteen ");break;
                        case 7:System.out.print("seventeen ");break;
                        case 8:System.out.print("eighteen ");break;
                        case 9:System.out.print("nineteen ");break;
                        case 0:System.out.print("ten ");break;
                        }break;
                        //if digit at 2nd place is not 1
                    case 2:System.out.print("twenty ");break;
                    case 3:System.out.print("thirty ");break;
                    case 4:System.out.print("forty ");break;
                    case 5:System.out.print("fifty ");break;
                    case 6:System.out.print("sixty ");break;
                    case 7:System.out.print("seventy ");break;
                    case 8:System.out.print("eighty ");break;
                    case 9:System.out.print("ninety ");break;
                    //case 0:   System.out.println("hundred ");break;

            }                           
        }           
    }
  }

}

Mixing C# & VB In The Same Project

I don't see how you can compile a project with the C# compiler (or the VB compiler) and not have it balk at the wrong language for the compiler.

Keep your C# code in a separate project from your VB project. You can include these projects into the same solution.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

The regular UITableViewCell works well to position things but the cell.imageView doesn't seem to behave like you want it to. I found that it's simple enough to get the UITableViewCell to lay out properly by first giving the cell.imageView a properly sized image like

// Putting in a blank image to make sure text always pushed to the side.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(kGroupImageDimension, kGroupImageDimension), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = blank;

Then you can just connect up your own properly working UIImageView with

// The cell.imageView increases in size to accomodate the image given it.
// We don't want this behaviour so we just attached a view on top of cell.imageView.
// This gives us the positioning of the cell.imageView without the sizing
// behaviour.
UIImageView *anImageView = nil;
NSArray *subviews = [cell.imageView subviews];
if ([subviews count] == 0)
{
    anImageView = [[UIImageView alloc] init];
    anImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.imageView addSubview:anImageView];

    NSLayoutConstraint *aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:kGroupImageDimension];
    [cell.imageView addConstraint:aConstraint];

    aConstraint = [NSLayoutConstraint constraintWithItem:anImageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:kGroupImageDimension];
    [cell.imageView addConstraint:aConstraint];
}
else
{
    anImageView = [subviews firstObject];
}

Set the image on anImageView and it will do what you expect a UIImageView to do. Be the size you want it regardless of the image you give it. This should go in tableView:cellForRowAtIndexPath:

Why can't Python find shared objects that are in directories in sys.path?

As a supplement to above answers - I'm just bumping into a similar problem, and working completely of the default installed python.

When I call the example of the shared object library I'm looking for with LD_LIBRARY_PATH, I get something like this:

$ LD_LIBRARY_PATH=/path/to/mysodir:$LD_LIBRARY_PATH python example-so-user.py
python: can't open file 'example-so-user.py': [Errno 2] No such file or directory

Notably, it doesn't even complain about the import - it complains about the source file!

But if I force loading of the object using LD_PRELOAD:

$ LD_PRELOAD=/path/to/mysodir/mypyobj.so python example-so-user.py
python: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory

... I immediately get a more meaningful error message - about a missing dependency!

Just thought I'd jot this down here - cheers!

Dynamic Web Module 3.0 -- 3.1

I had similar troubles in eclipse and the only way to fix it for me was to

  • Remove the web module
  • Apply
  • Change the module version
  • Add the module
  • Configure (Further configuration available link at the bottom of the dialog)
  • Apply

Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.

EDIT:

Here is a second way in case nothing else helps

  • Exit eclipse, go to your project in the file system, then to .settings folder.
  • Open the org.eclipse.wst.common.project.facet.core.xml , make backup, and remove the web module entry.
  • You can also modify the web module version there, but again, no guarantees.

Laravel Check If Related Model Exists

I prefer to use exists method:

RepairItem::find($id)->option()->exists()

to check if related model exists or not. It's working fine on Laravel 5.2

Capturing count from an SQL query

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

How to add MVC5 to Visual Studio 2013?

You can look into Windows installed folder from here of your pc path:

C:\Program Files (x86)\Microsoft ASP.NET

View of Opened file where showing installed MVC 3, MVC 4

enter image description here

MySQL "incorrect string value" error when save unicode string in Django

Simply alter your table, no need to any thing. just run this query on database. ALTER TABLE table_nameCONVERT TO CHARACTER SET utf8

it will definately work.

Difference between two dates in MySQL

If you've a date stored in text field as string you can implement this code it will fetch the list of past number of days a week, a month or a year sorting:

SELECT * FROM `table` WHERE STR_TO_DATE(mydate, '%d/%m/%Y') < CURDATE() - INTERVAL 30 DAY AND STR_TO_DATE(date, '%d/%m/%Y') > CURDATE() - INTERVAL 60 DAY

//This is for a month

SELECT * FROM `table` WHERE STR_TO_DATE(mydate, '%d/%m/%Y') < CURDATE() - INTERVAL 7 DAY AND STR_TO_DATE(date, '%d/%m/%Y') > CURDATE() - INTERVAL 14 DAY

//This is for a week 

%d%m%Y is your date format

This query display the record between the days you set there like: Below from last 7 days and Above from last 14 days so it would be your last week record to be display same concept is for month or year. Whatever value you're providing in below date like: below from 7-days so the other value would be its double as 14 days. What we are saying here get all records above from last 14 days and below from last 7 days. This is a week record you can change value to 30-60 days for a month and also for a year.

Thank You Hope it will help someone.

Returning data from Axios API

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

and this NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

HTML5 video won't play in Chrome only

To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.

My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

Auto refresh page every 30 seconds

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload() (docs) inside a setTimeout():

window.setTimeout(function () {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.

Which characters make a URL invalid?

Several of Unicode character ranges are valid HTML5, although it might still not be a good idea to use them.

E.g., href docs say http://www.w3.org/TR/html5/links.html#attr-hyperlink-href:

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

Then the definition of "valid URL" points to http://url.spec.whatwg.org/, which says it aims to:

Align RFC 3986 and RFC 3987 with contemporary implementations and obsolete them in the process.

That document defines URL code points as:

ASCII alphanumeric, "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", and code points in the ranges U+00A0 to U+D7FF, U+E000 to U+FDCF, U+FDF0 to U+FFFD, U+10000 to U+1FFFD, U+20000 to U+2FFFD, U+30000 to U+3FFFD, U+40000 to U+4FFFD, U+50000 to U+5FFFD, U+60000 to U+6FFFD, U+70000 to U+7FFFD, U+80000 to U+8FFFD, U+90000 to U+9FFFD, U+A0000 to U+AFFFD, U+B0000 to U+BFFFD, U+C0000 to U+CFFFD, U+D0000 to U+DFFFD, U+E1000 to U+EFFFD, U+F0000 to U+FFFFD, U+100000 to U+10FFFD.

The term "URL code points" is then used in the statement:

If c is not a URL code point and not "%", parse error.

in a several parts of the parsing algorithm, including the schema, authority, relative path, query and fragment states: so basically the entire URL.

Also, the validator http://validator.w3.org/ passes for URLs like "??", and does not pass for URLs with characters like spaces "a b"

Of course, as mentioned by Stephen C, it is not just about characters but also about context: you have to understand the entire algorithm. But since class "URL code points" is used on key points of the algorithm, it that gives a good idea of what you can use or not.

See also: Unicode characters in URLs

ng-change get new value and original value

You can use a scope watch:

$scope.$watch('user', function(newValue, oldValue) {
  // access new and old value here
  console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

JSONObject json2 = null;
if(x == y)
   json2 = getJSONX();

Error: Local variable statement defined in an enclosing scope must be final or effectively final.

But you can write:

JSONObject json2 = (x == y) ? json2 = getJSONX() : null;

jQuery datepicker years shown

 $("#DateOfBirth").datepicker({
        yearRange: "-100:+0",
        changeMonth: true,
        changeYear: true,
    });

yearRange: '1950:2013', // specifying a hard coded year range or this way

yearRange: "-100:+0", // last hundred years

It will help to show drop down for year and month selection.

Where does Oracle SQL Developer store connections?

In some versions, it stores it under

<installed path>\system\oracle.jdeveloper.db.connection.11.1.1.0.11.42.44
\IDEConnections.xml

failed to open stream: No such file or directory in

include() needs a full file path, relative to the file system's root directory.

This should work:

 include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");

Is there a quick change tabs function in Visual Studio Code?

Another way to quickly change tabs would be in VSCode 1.45 (April 2020)

Switch tabs using mouse wheel

When you use the mouse wheel to scroll over editor tabs, you can currently not switch to the tab, only reveal tabs that are out of view.

Now with a new setting workbench.editor.scrollToSwitchTabs this behaviour can be changed if you change it to true.

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_45/scroll-tabs.gif

Note: you can also press and hold the Shift key while scrolling to get the opposite behaviour (i.e. you can switch to tabs even with this setting being turned off).

DbEntityValidationException - How can I easily tell what caused the error?

To view the EntityValidationErrors collection, add the following Watch expression to the Watch window.

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

I'm using visual studio 2013

Is there a way to get rid of accents and convert a whole string to regular letters?

In case anyone is strugling to do this in kotlin, this code works like a charm. To avoid inconsistencies I also use .toUpperCase and Trim(). then i cast this function:

   fun stripAccents(s: String):String{

   if (s == null) {
      return "";
   }

val chars: CharArray = s.toCharArray()

var sb = StringBuilder(s)
var cont: Int = 0

while (chars.size > cont) {
    var c: kotlin.Char
    c = chars[cont]
    var c2:String = c.toString()
   //these are my needs, in case you need to convert other accents just Add new entries aqui
    c2 = c2.replace("Ã", "A")
    c2 = c2.replace("Õ", "O")
    c2 = c2.replace("Ç", "C")
    c2 = c2.replace("Á", "A")
    c2 = c2.replace("Ó", "O")
    c2 = c2.replace("Ê", "E")
    c2 = c2.replace("É", "E")
    c2 = c2.replace("Ú", "U")

    c = c2.single()
    sb.setCharAt(cont, c)
    cont++

}

return sb.toString()

}

to use these fun cast the code like this:

     var str: String
     str = editText.text.toString() //get the text from EditText
     str = str.toUpperCase().trim()

     str = stripAccents(str) //call the function

inject bean reference into a Quartz job in Spring?

All those solutions above doesn't work for me with Spring 5 and Hibernate 5 and Quartz 2.2.3 when I want to call transactional methods!

I therefore implemented this solution which automatically starts the scheduler and triggers the jobs. I found a lot of that code at dzone. Because I don't need to create triggers and jobs dynamically I wanted the static triggers to be pre defined via Spring Configuration and only the jobs to be exposed as Spring Components.

My basic configuration look like this

@Configuration
public class QuartzConfiguration {

  @Autowired
  ApplicationContext applicationContext;

  @Bean
  public SchedulerFactoryBean scheduler(@Autowired JobFactory jobFactory) throws IOException {
    SchedulerFactoryBean sfb = new SchedulerFactoryBean();

    sfb.setOverwriteExistingJobs(true);
    sfb.setAutoStartup(true);
    sfb.setJobFactory(jobFactory);

    Trigger[] triggers = new Trigger[] {
        cronTriggerTest().getObject()
    };
    sfb.setTriggers(triggers);
    return sfb;
  }

  @Bean
  public JobFactory cronJobFactory() {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
  }

  @Bean 
  public CronTriggerFactoryBean cronTriggerTest() {
    CronTriggerFactoryBean tfb = new CronTriggerFactoryBean();
    tfb.setCronExpression("0 * * ? * * *");

    JobDetail jobDetail = JobBuilder.newJob(CronTest.class)
                            .withIdentity("Testjob")
                            .build()
                            ;

    tfb.setJobDetail(jobDetail);
    return tfb;
  }

}

As you can see, you have the scheduler and a simple test trigger which is defined via a cron expression. You can obviously choose whatever scheduling expression you like. You then need the AutowiringSpringBeanJobFactory which goes like this

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

  @Autowired
  private ApplicationContext applicationContext;

  private SchedulerContext schedulerContext;

  @Override
  public void setApplicationContext(final ApplicationContext context) {
    this.applicationContext = context;
  }


  @Override
  protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    Job job = applicationContext.getBean(bundle.getJobDetail().getJobClass());
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
    pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());

    if (this.schedulerContext != null)
    {
        pvs.addPropertyValues(this.schedulerContext);
    }
    bw.setPropertyValues(pvs, true);

    return job;
  }  

  public void setSchedulerContext(SchedulerContext schedulerContext) {
    this.schedulerContext = schedulerContext;
    super.setSchedulerContext(schedulerContext);
  }

}

In here you wire your normal application context and your job together. This is the important gap because normally Quartz starts it's worker threads which have no connection to your application context. That is the reason why you can't execute Transactional mehtods. The last thing missing is a job. It can look like that

@Component
public class CronTest implements Job {

  @Autowired
  private MyService s;

  public CronTest() {
  }

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    s.execute();
  }

}

It's not a perfect solution because you an extra class only for calling your service method. But nevertheless it works.

CodeIgniter: How to use WHERE clause and OR clause

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

Is there a way to get a list of column names in sqlite?

As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.

I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need

SELECT sql FROM sqlite_master WHERE name='tablename';

gives you something like

CREATE TABLE tablename(
        col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        col2 NVARCHAR(100) NOT NULL,
        col3 NVARCHAR(100) NOT NULL,
)

Or using pragma

PRAGMA table_info(tablename);

gives you something like

0|col1|INTEGER|1||1
1|col2|NVARCHAR(100)|1||0
2|col3|NVARCHAR(100)|1||0

What's the difference between map() and flatMap() methods in Java 8?

Stream operations flatMap and map accept a function as input.

flatMap expects the function to return a new stream for each element of the stream and returns a stream which combines all the elements of the streams returned by the function for each element. In other words, with flatMap, for each element from the source, multiple elements will be created by the function. http://www.zoftino.com/java-stream-examples#flatmap-operation

map expects the function to return a transformed value and returns a new stream containing the transformed elements. In other words, with map, for each element from the source, one transformed element will be created by the function. http://www.zoftino.com/java-stream-examples#map-operation

MySQL add days to a date

For your need:

UPDATE classes 
SET `date` = DATE_ADD(`date`, INTERVAL 2 DAY)
WHERE id = 161

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Setting WPF image source in code

Have you tried:

Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = iconStream;
bitmap.EndInit();
_icon.Source = bitmap;

IIS Express gives Access Denied error when debugging ASP.NET MVC

In my case a previous run of my app from VS reserved the URL. I could see this by running in a console:

netsh http show urlacl

to delete this reservation i ran this in an elevated console:

netsh http delete urlacl http://127.0.0.1:10002/

I found these steps here solved my problem.

I'm using VS2013

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How to dynamically create a class?

You want to look at CodeDOM. It allows defining code elements and compiling them. Quoting MSDN:

...This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

Why does "return list.sort()" return None, not the list?

Python habitually returns None from functions and methods that mutate the data, such as list.sort, list.append, and random.shuffle, with the idea being that it hints to the fact that it was mutating.

If you want to take an iterable and return a new, sorted list of its items, use the sorted builtin function.

How do I get the height of a div's full content with jQuery?

You can get it with .outerHeight().

Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})

You can find a detailed post here.

How do you discover model attributes in Rails?

If you're just interested in the properties and data types from the database, you can use Model.inspect.

irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
 reset_password_token: string, reset_password_sent_at: datetime,
 remember_created_at: datetime, sign_in_count: integer,
 current_sign_in_at: datetime, last_sign_in_at: datetime,
 current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
 updated_at: datetime)"

Alternatively, having run rake db:create and rake db:migrate for your development environment, the file db/schema.rb will contain the authoritative source for your database structure:

ActiveRecord::Schema.define(version: 20130712162401) do
  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

Get environment variable value in Dockerfile

An alternative using envsubst without losing the ability to use commands like COPY or ADD, and without using intermediate files would be to use Bash's Process Substitution:

docker build -f <(envsubst < Dockerfile) -t my-target .

SQL Data Reader - handling Null column values

reader.IsDbNull(ColumnIndex) works as many answers says.

And I want to mention if you working with column names, just comparing types may be more comfortable.

if(reader["TeacherImage"].GetType() == typeof(DBNull)) { //logic }

Laravel 5.4 redirection to custom url after login

Path Customization (tested in laravel 7) When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

public const HOME = '/home';

Execute PHP script in cron job

You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser (man runuser). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.

I provide a detailed answer how to use cron in this stackoverflow post.

How to write a cron that will run a script every day at midnight?

what is difference between success and .done() method of $.ajax

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

When should we use mutex and when should we use semaphore

Trying not to sound zany, but can't help myself.

Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'

(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)

In object terminology we can observe that :

observation.1 Semaphore contains mutex

observation.2 Mutex is not semaphore and semaphore is not mutex.

There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.

There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.

There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.

This is where confusion pours in like monsoon rain.

A semaphore with a counter that can be 0 or 1 is NOT mutex.

Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.

Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.

  1. Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore

  2. Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore

  3. Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)

Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive

Use semaphores, when what you want is exactly provided by it.

If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.

And lastly read a book rather than relying just on SO.

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

How to set a value for a selectize.js input?

Answer by the user 'onlyblank' is correct. A small addition to that- You can set more than 1 default values if you want.

Instead of passing on id to the setValue(), pass an array. Example:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Excel telling me my blank cells aren't blank

Here's how I fixed this problem without any coding.

  1. Select the entire column that I wanted to delete the "blank" cells from.
  2. Click the Conditional Formatting tab up top.
  3. Select "New Rule".
  4. Click "Format only cells that contain".
  5. Change "between" to "equal to".
  6. Click the box next to the "equal to" box.
  7. Click one of the problem "blank" cells.
  8. Click the Format Button.
  9. Pick a random color to fill the box with.
  10. Press "OK".
  11. This should change all of the problem "blank" cells to the color that you chose. Now Right click one of the colored cells, and go to "Sort" and "Put selected cell color on top".
  12. This will put all of the problem cells at the top of the column and now all of your other cells will stay in the original order you put them in. You can now select all of the problem cells in one group and click the delete cell button on top to get rid of them.

C++: Rounding up to the nearest multiple of a number

For anyone looking for a short and sweet answer. This is what I used. No accounting for negatives.

n - (n % r)

That will return the previous factor.

(n + r) - (n % r)

Will return the next. Hope this helps someone. :)

Set View Width Programmatically

The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.

Get page title with Selenium WebDriver using Java

In java you can do some thing like:

if(driver.getTitle().contains("some expected text"))
    //Pass
    System.out.println("Page title contains \"some expected text\" ");
else
    //Fail
    System.out.println("Page title doesn't contains \"some expected text\" ");

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

Convert XmlDocument to String

Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?

return xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml.

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

How to take complete backup of mysql database using mysqldump command line utility

To create dump follow below steps:

  1. Open CMD and go to bin folder where you have installed your MySQL
    ex:C:\Program Files\MySQL\MySQL Server 8.0\bin. If you see in this
    folder mysqldump.exe will be there. Or you have setup above folder in your Path variable of Environment Variable.

  2. Now if you hit mysqldump in CMD you can see CMD is able to identify dump command.

  3. Now run "mysqldump -h [host] -P [port] -u [username] -p --skip-triggers --no-create-info --single-transaction --quick --lock-tables=false ABC_databse > c:\xyz.sql"
  4. Above command will prompt for password then it will start processing.

How to simplify a null-safe compareTo() implementation?

I always recommend using Apache commons since it will most likely be better than one you can write on your own. Plus you can then do 'real' work rather then reinventing.

The class you are interested in is the Null Comparator. It allows you to make nulls high or low. You also give it your own comparator to use when the two values are not null.

In your case you can have a static member variable that does the comparison and then your compareTo method just references that.

Somthing like

class Metadata implements Comparable<Metadata> {
private String name;
private String value;

static NullComparator nullAndCaseInsensitveComparator = new NullComparator(
        new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // inputs can't be null
                return o1.compareToIgnoreCase(o2);
            }

        });

@Override
public int compareTo(Metadata other) {
    if (other == null) {
        return 1;
    }
    int res = nullAndCaseInsensitveComparator.compare(name, other.name);
    if (res != 0)
        return res;

    return nullAndCaseInsensitveComparator.compare(value, other.value);
}

}

Even if you decide to roll your own, keep this class in mind since it is very useful when ordering lists thatcontain null elements.

How to get records randomly from the oracle database?

SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

What is the difference between i++ and ++i?

If you have:

int i = 10;
int x = ++i;

then x will be 11.

But if you have:

int i = 10;
int x = i++;

then x will be 10.

Note as Eric points out, the increment occurs at the same time in both cases, but it's what value is given as the result that differs (thanks Eric!).

Generally, I like to use ++i unless there's a good reason not to. For example, when writing a loop, I like to use:

for (int i = 0; i < 10; ++i) {
}

Or, if I just need to increment a variable, I like to use:

++x;

Normally, one way or the other doesn't have much significance and comes down to coding style, but if you are using the operators inside other assignments (like in my original examples), it's important to be aware of potential side effects.

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

How to make the checkbox unchecked by default always

If you have a checkbox with an id checkbox_id.You can set its state with JS with prop('checked', false) or prop('checked', true)

 $('#checkbox_id').prop('checked', false);

Fragment onResume() & onPause() is not called on backstack

What i do in child fragment:

@Override
public void onDetach() {
   super.onDetach();
   ParentFragment pf = (ParentFragment) this.getParentFragment();
   pf.onResume();
}

And then override onResume on ParentFragment

SVN Commit specific files

Sure. Just list the files:

$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png

I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:

$ svn ci -m "No longer sets printer on fire" printer-driver/*.c

You can also have the svn command read the list of files to commit from a file:

$ svn ci -m "Now works" --targets fix4711.txt

Inserting the same value multiple times when formatting a string

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

Javascript communication between browser tabs/windows

edit: With Flash you can communicate between any window, ANY browser (yes, from FF to IE at runtime ) ..ANY form of instance of flash (ShockWave/activeX)

How to install python-dateutil on Windows?

Install from the "Unofficial Windows Binaries for Python Extension Packages"

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-dateutil

Pretty much has every package you would need.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

You could use feature detection to see if browser is IE10 or greater like so:

var isIE = false;
if (window.navigator.msPointerEnabled) {
    isIE = true;
}

Only true if > IE9

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

Changing the child element's CSS when the parent is hovered

To change it from css you dont even need to set the child class

.parent > div:nth-child(1) { display:none; }
.parent:hover > div:nth-child(1) { display: block; }

Injecting Mockito mocks into a Spring bean

Below code works with autowiring - it is not the shortest version but useful when it should work only with standard spring/mockito jars.

<bean id="dao" class="org.springframework.aop.framework.ProxyFactoryBean">
   <property name="target"> <bean class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="com.package.Dao" /> </bean> </property>
   <property name="proxyInterfaces"> <value>com.package.Dao</value> </property>
</bean> 

Apache redirect to another port

I wanted to do exactly this so I could access Jenkins from the root domain.

I found I had to disable the default site to get this to work. Here's exactly what I did.

$ sudo vi /etc/apache2/sites-available/jenkins

And insert this into file:

<VirtualHost *:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName mydomain.com
  ServerAlias mydomain
  ProxyPass / http://localhost:8080/
  ProxyPassReverse / http://localhost:8080/
  <Proxy *>
        Order deny,allow
        Allow from all
  </Proxy>
</VirtualHost>

Next you need to enable/disable the appropriate sites:

$ sudo a2ensite jenkins
$ sudo a2dissite default
$ sudo service apache2 reload

Hope it helps someone.

Formatting text in a TextBlock

a good site, with good explanations:

http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF

Edit

There are different methods to format the text. for a basic formatting (the easiest in my opinion):

    <TextBlock Margin="10" TextWrapping="Wrap">
                    TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
    </TextBlock>

Example 1 shows basic formatting with Bold Itallic and underscored text.

Following includes the SPAN method, with this you van highlight text:

   <TextBlock Margin="10" TextWrapping="Wrap">
                    This <Span FontWeight="Bold">is</Span> a
                    <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                    with <Span TextDecorations="Underline">several</Span>
                    <Span FontStyle="Italic">Span</Span> elements,
                    <Span Foreground="Blue">
                            using a <Bold>variety</Bold> of <Italic>styles</Italic>
                    </Span>.
   </TextBlock>

Example 2 shows the span function and the different possibilities with it.

For a detailed explanation check the site!

Examples

Invalid attempt to read when no data is present

I would check to see if the SqlDataReader has rows returned first:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
   ...
}

How to print the data in byte array as characters?

Try it:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

Example:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

How can I order a List<string>?

You can use Sort

List<string> ListaServizi = new List<string>() { };
ListaServizi.Sort();

How can you export the Visual Studio Code extension list?

For Linux/Mac only, export the installed Visual Studio Code extensions in the form of an installation script. It's a Z shell (Zsh) script, but it may run in Bash as well.

https://gist.github.com/jvlad/6c92178bbfd1906b7d83c69780ee4630

Regex: Remove lines containing "help", etc

Search with a regular expression:

^.*(help).*$

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

git rebase fatal: Needed a single revision

You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase.

E.g.:

git rebase origin/master

not:

git rebase origin

Note, although origin should resolve to the the ref origin/HEAD when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.

Get PHP class property by string

Something like this? Haven't tested it but should work fine.

function magic($obj, $var, $value = NULL)
{
    if($value == NULL)
    {
        return $obj->$var;
    }
    else
    {
        $obj->$var = $value;
    }
}

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

Need a good hex editor for Linux

I am a VIMer. I can do some rare Hex edits with:

  • :%!xxd to switch into hex mode

  • :%!xxd -r to exit from hex mode

But I strongly recommend ht

apt-cache show ht

Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>

Homepage: http://hte.sourceforge.net/

Note: The package is called ht, whereas the executable is named hte after the package was installed.

  1. Supported file formats
    • common object file format (COFF/XCOFF32)
    • executable and linkable format (ELF)
    • linear executables (LE)
    • standard DO$ executables (MZ)
    • new executables (NE)
    • portable executables (PE32/PE64)
    • java class files (CLASS)
    • Mach exe/link format (MachO)
    • X-Box executable (XBE)
    • Flat (FLT)
    • PowerPC executable format (PEF)
  2. Code & Data Analyser
    • finds branch sources and destinations recursively
    • finds procedure entries
    • creates labels based on this information
    • creates xref information
    • allows to interactively analyse unexplored code
    • allows to create/rename/delete labels
    • allows to create/edit comments
    • supports x86, ia64, alpha, ppc and java code
  3. Target systems
    • DJGPP
    • GNU/Linux
    • FreeBSD
    • OpenBSD
    • Win32

Multiple IF statements between number ranges

standalone one cell solution based on VLOOKUP

US syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
        IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
 {{(TRANSPOSE({{{0;   "Less than 500"},
               {500;  "Between 500 and 1000"}},
              {{1000; "Between 1000 and 1500"},
               {1500; "Between 1500 and 2000"}}}))}}, 2)),)), )

EU syntax:

=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
        IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
 {{(TRANSPOSE({{{0;   "Less than 500"}\
               {500;  "Between 500 and 1000"}}\
              {{1000; "Between 1000 and 1500"}\
               {1500; "Between 1500 and 2000"}}}))}}; 2));)); )

alternatives: https://webapps.stackexchange.com/questions/123729/

Where can I get a list of Countries, States and Cities?

The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html

What is the order of precedence for CSS?

The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.

In your case .smallbox-paysummary is defined after .smallbox hence the 10px precedence.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

Find TODO tags in Eclipse

Sometimes Window ? Show View does not show the Tasks. Just go to Window ? Show View -> Others and type Tasks in the dialog box.

String comparison in Objective-C

You can compare string with below functions.

NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1

What is default session timeout in ASP.NET?

The Default Expiration Period for Session is 20 Minutes.

You can update sessionstate and configure the minutes under timeout

<sessionState 
timeout="30">
</sessionState>

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

My working solution is:

  • Install cross-env
    npm install --save-dev cross-env or npm install -g cross-env.
  • File package.json add new build script
    e.g.
    ... "build:prod:ios": "cross-env NODE_OPTIONS='--max-old-space-size=8192' ionic cordova build ios --prod --release" ...
  • Use that command to build next time.
    npm run build:prod:ios

  • Problem solved.

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to change fontFamily of TextView in Android

If you want it programatically, you could use

label.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);

Where SANS_SERIF you can use:

  • DEFAULT
  • DEFAULT_BOLD
  • MONOSPACE
  • SANS_SERIF
  • SERIF

And where ITALIC you can use:

  • BOLD
  • BOLD_ITALIC
  • ITALIC
  • NORMAL

All is stated on Android Developers

Chmod recursively

You need read access, in addition to execute access, to list a directory. If you only have execute access, then you can find out the names of entries in the directory, but no other information (not even types, so you don't know which of the entries are subdirectories). This works for me:

find . -type d -exec chmod +rx {} \;

Add up a column of numbers at the Unix shell

The whole ls -l and then cut is rather convoluted when you have stat. It is also vulnerable to the exact format of ls -l (it didn't work until I changed the column numbers for cut)

Also, fixed the useless use of cat.

<files.txt  xargs stat -c %s | paste -sd+ - | bc

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

Select from multiple tables without a join?

You could try something like this:

SELECT ...
FROM (
    SELECT f1,f2,f3 FROM table1
    UNION
    SELECT f1,f2,f3 FROM table2
)
WHERE ...

Sanitizing user input before adding it to the DOM in Javascript

You can use this:

function sanitize(string) {
  const map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      "/": '&#x2F;',
  };
  const reg = /[&<>"'/]/ig;
  return string.replace(reg, (match)=>(map[match]));
}

Also see OWASP XSS Prevention Cheat Sheet.

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

A variation on @samvermette's solution:

/// Allows for disabling scrolling headers in plain-styled tableviews
extension UITableView {

    static let shouldScrollSectionHeadersDummyViewHeight = CGFloat(40)

    var shouldScrollSectionHeaders: Bool {
        set {
            if newValue {
                tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: UITableView.shouldScrollSectionHeadersDummyViewHeight))
                contentInset = UIEdgeInsets(top: -UITableView.shouldScrollSectionHeadersDummyViewHeight, left: 0, bottom: 0, right: 0)
            } else {
                tableHeaderView = nil
                contentInset = .zero
            }
        }

        get {
            return tableHeaderView != nil && contentInset.top == UITableView.shouldScrollSectionHeadersDummyViewHeight
        }
    }

}

Checking if an Android application is running in the background

It might be too late to answer but if somebody comes visiting then here is the solution I suggest, The reason(s) an app wants to know it's state of being in background or coming to foreground can be many, a few are, 1. To show toasts and notifications when the user is in BG. 2.To perform some tasks for the first time user comes from BG, like a poll, redraw etc.

The solution by Idolon and others takes care of the first part, but does not for the second. If there are multiple activities in your app, and the user is switching between them, then by the time you are in second activity, the visible flag will be false. So it cannot be used deterministically.

I did something what was suggested by CommonsWare, "If the Service determines that there are no activities visible, and it remains that way for some amount of time, stop the data transfer at the next logical stopping point."

The line in bold is important and this can be used to achieve second item. So what I do is once I get the onActivityPaused() , don not change the visible to false directly, instead have a timer of 3 seconds (that is the max that the next activity should be launched), and if there is not onActivityResumed() call in the next 3 seconds, change visible to false. Similarly in onActivityResumed() if there is a timer then I cancel it. To sum up,the visible becomes isAppInBackground.

Sorry cannot copy-paste the code...

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

In my case, this error was caused by renaming my client machine. I used a new name longer than 13 characters (despite the warning), which resulted in the NETBIOS name being truncated and being different from the full machine name. Once I re-renamed the client to a shorter name, the error went away.

Oracle listener not running and won't start

Problem

The listener service is stopped in services.msc.

Cause

User password was changed.

Solution

  • Open services.msc.
  • Right-click the specific listener service.
  • Click Properties.
  • Click the Logon tab.
  • Change the password.
  • Click OK.
  • Start the service.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Export MySQL database using PHP only

Best way to export database using php script.

Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables

<?php 
    //ENTER THE RELEVANT INFO BELOW
    $mysqlUserName      = "Your Username";
    $mysqlPassword      = "Your Password";
    $mysqlHostName      = "Your Host";
    $DbName             = "Your Database Name here";
    $backup_name        = "mybackup.sql";
    $tables             = "Your tables";

   //or add 5th parameter(array) of specific tables:    array("mytable1","mytable2","mytable3") for multiple tables

    Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName,  $tables=false, $backup_name=false );

    function Export_Database($host,$user,$pass,$name,  $tables=false, $backup_name=false )
    {
        $mysqli = new mysqli($host,$user,$pass,$name); 
        $mysqli->select_db($name); 
        $mysqli->query("SET NAMES 'utf8'");

        $queryTables    = $mysqli->query('SHOW TABLES'); 
        while($row = $queryTables->fetch_row()) 
        { 
            $target_tables[] = $row[0]; 
        }   
        if($tables !== false) 
        { 
            $target_tables = array_intersect( $target_tables, $tables); 
        }
        foreach($target_tables as $table)
        {
            $result         =   $mysqli->query('SELECT * FROM '.$table);  
            $fields_amount  =   $result->field_count;  
            $rows_num=$mysqli->affected_rows;     
            $res            =   $mysqli->query('SHOW CREATE TABLE '.$table); 
            $TableMLine     =   $res->fetch_row();
            $content        = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";

            for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
            {
                while($row = $result->fetch_row())  
                { //when started (and every after 100 command cycle):
                    if ($st_counter%100 == 0 || $st_counter == 0 )  
                    {
                            $content .= "\nINSERT INTO ".$table." VALUES";
                    }
                    $content .= "\n(";
                    for($j=0; $j<$fields_amount; $j++)  
                    { 
                        $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                        if (isset($row[$j]))
                        {
                            $content .= '"'.$row[$j].'"' ; 
                        }
                        else 
                        {   
                            $content .= '""';
                        }     
                        if ($j<($fields_amount-1))
                        {
                                $content.= ',';
                        }      
                    }
                    $content .=")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
                    {   
                        $content .= ";";
                    } 
                    else 
                    {
                        $content .= ",";
                    } 
                    $st_counter=$st_counter+1;
                }
            } $content .="\n\n\n";
        }
        //$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
        $backup_name = $backup_name ? $backup_name : $name.".sql";
        header('Content-Type: application/octet-stream');   
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"".$backup_name."\"");  
        echo $content; exit;
    }
?>

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

How to develop Desktop Apps using HTML/CSS/JavaScript?

Sorry to burst your bubble but Spotify desktop client is just a Webkit-based browser. Of course it exposes specific additional functionality, but it's only able to run JS and render HTML/CSS because it has a JS engine as well as a Chromium rendering engine. This does not help you with coding a client-side web-app and deploying to multiple platforms.

What you're looking for is similar to Sencha Touch - a framework that allows for HTML5 apps to be natively deployed to iOS, Android and Blackberry devices. It basically acts as an intermediary between certain API calls and device-specific functionality available.

I have no experience with appcelerator, bit it appears to be doing exactly that - and get very favourable reviews online. You should give it a go (unless you wanted to go back to 1999 and roll with MS HTA ;)

Default values for Vue component props & how to check if a user did not set the prop?

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

How can I set the max-width of a table cell using percentages?

I know this is literally a year later, but I figured I'd share. I was trying to do the same thing and came across this solution that worked for me. We set a max width for the entire table, then worked with the cell sizes for the desired effect.

Put the table in its own div, then set the width, min-width, and/or max-width of the div as desired for the entire table. Then, you can work and set width and min-widths for other cells, and max width for the div effectively working around and backwards to achieve the max width we wanted.

_x000D_
_x000D_
#tablediv {
    width:90%;
    min-width:800px
    max-width:1500px;
}

.tdleft {
    width:20%;
    min-width:200px;
}
_x000D_
<div id="tablediv">
  <table width="100%" border="1">
    <tr>
      <td class="tdleft">Test</td>
      <td>A long string blah blah blah</td>
    </tr>
  </table>
</div>
_x000D_
_x000D_
_x000D_

Admittedly, this does not give you a "max" width of a cell per se, but it does allow some control that might work in-lieu of such an option. Not sure if it will work for your needs. I know it worked for our situation where we want the navigation side in the page to scale up and down to a point but for all the wide screens these days.

Python unexpected EOF while parsing

Check if all the parameters of functions are defined before they are called. I faced this problem while practicing Kaggle.

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

Java Singleton and Synchronization

public class Elvis { 
   public static final Elvis INSTANCE = new Elvis();
   private Elvis () {...}
 }

Source : Effective Java -> Item 2

It suggests to use it, if you are sure that class will always remain singleton.

Editing an item in a list<T>

public changeAttr(int id)
{
    list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}

With:

  • IdItem is the id of the element you want to modify

  • FieldToModify is the Field of the item that you want to update.

  • NewValueForTheField is exactly that, the new value.

(It works perfect for me, tested and implemented)

Quicksort: Choosing the pivot

It depends on your requirements. Choosing a pivot at random makes it harder to create a data set that generates O(N^2) performance. 'Median-of-three' (first, last, middle) is also a way of avoiding problems. Beware of relative performance of comparisons, though; if your comparisons are costly, then Mo3 does more comparisons than choosing (a single pivot value) at random. Database records can be costly to compare.


Update: Pulling comments into answer.

mdkess asserted:

'Median of 3' is NOT first last middle. Choose three random indexes, and take the middle value of this. The whole point is to make sure that your choice of pivots is not deterministic - if it is, worst case data can be quite easily generated.

To which I responded:

  • Analysis Of Hoare's Find Algorithm With Median-Of-Three Partition (1997) by P Kirschenhofer, H Prodinger, C Martínez supports your contention (that 'median-of-three' is three random items).

  • There's an article described at portal.acm.org that is about 'The Worst Case Permutation for Median-of-Three Quicksort' by Hannu Erkiö, published in The Computer Journal, Vol 27, No 3, 1984. [Update 2012-02-26: Got the text for the article. Section 2 'The Algorithm' begins: 'By using the median of the first, middle and last elements of A[L:R], efficient partitions into parts of fairly equal sizes can be achieved in most practical situations.' Thus, it is discussing the first-middle-last Mo3 approach.]

  • Another short article that is interesting is by M. D. McIlroy, "A Killer Adversary for Quicksort", published in Software-Practice and Experience, Vol. 29(0), 1–4 (0 1999). It explains how to make almost any Quicksort behave quadratically.

  • AT&T Bell Labs Tech Journal, Oct 1984 "Theory and Practice in the Construction of a Working Sort Routine" states "Hoare suggested partitioning around the median of several randomly selected lines. Sedgewick [...] recommended choosing the median of the first [...] last [...] and middle". This indicates that both techniques for 'median-of-three' are known in the literature. (Update 2014-11-23: The article appears to be available at IEEE Xplore or from Wiley — if you have membership or are prepared to pay a fee.)

  • 'Engineering a Sort Function' by J L Bentley and M D McIlroy, published in Software Practice and Experience, Vol 23(11), November 1993, goes into an extensive discussion of the issues, and they chose an adaptive partitioning algorithm based in part on the size of the data set. There is a lot of discussion of trade-offs for various approaches.

  • A Google search for 'median-of-three' works pretty well for further tracking.

Thanks for the information; I had only encountered the deterministic 'median-of-three' before.

Split string on whitespace in Python

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

How do I get the scroll position of a document?

Try this:

var scrollHeight = $(scrollable)[0] == document ? document.body.scrollHeight : $(scrollable)[0].scrollHeight;

how to include js file in php?

Pekka has the correct answer (hence my making this answer a Community Wiki): Use src, not href, to specify the file.

Regarding:

When i try it this way:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>

the first tag in the document.write function closes
what is the correct way to do this?

You don't want or need document.write for this, but just in case you ever do need to put the characters </script> inside a script tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>. There are a couple of ways of doing that. One way is to escape the / even though you don't need to:

<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
//      ^--- note the seemingly-unnecessary backslash
</script>

Or if you're feeling more paranoid:

<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>

...since in each case, JavaScript sees the string as </script> but the HTML parser doesn't.

How to change the project in GCP using CLI commands

I'm posting this answer to give insights into multiple ways available for you to change the project on GCP. I will also explain when to use each of the following options.


Option 1: Cloud CLI - Set Project Property on Cloud SDK on CLI

Use this option, if you want to run all Cloud CLI commands on a specific project.

gcloud config set project <Project-ID>

With this, the selected project on Cloud CLI will change, and the currently selected project is highlighted in yellow.

enter image description here


Option 2: Cloud CLI - Set Project ID flag with most Commands

Use this command if you want to execute commands on multiple projects. Eg: create clusters in one project, and use the same configs to create on another project. Use the following flag for each command.

--project <Project-ID>

Option 3: Cloud CLI - Initialize the Configurations in CLI

This option can be used if you need separate configurations for different projects/accounts. With this, you can easily switch between configurations by using the activate command. Eg: gcloud config configurations activate <congif-name>.

gcloud init

Option 4: Open new Cloud Shell with your preferred project

This is preferred if you don't like to work with CLI commands. Press the PLUS + button for a new tab. enter image description here

Next, select your preferred project.

enter image description here

Get data from file input in JQuery

 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>

Set default time in bootstrap-datetimepicker

It works for me:

 <script type="text/javascript">
        $(function () {
            var dateNow = new Date();
            $('#calendario').datetimepicker({
                locale: 'es',
                format: 'DD/MM/YYYY',
                defaultDate:moment(dateNow).hours(0).minutes(0).seconds(0).milliseconds(0)                    
            });
        });            
    </script>

Bootstrap full responsive navbar with logo or brand name text

Best approach to add a brand logo inside a navbar-inner class and a container. About the <h3> issue <h3> has a certain padding given to it in bootstrap as @creimers told. And if you are using a bigger image, increase the height of navbar too or the logo will float outside.

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-inner"> <!--changes made here-->
    <div class="container">

        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1">

                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>

            </button>
            <a class="navbar-brand" href="#">
                <img src="http://placehold.it/150x50&text=Logo" alt="">
            </a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">About</a></li>
                <li><a href="#">Services</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>
    </div>
</div>
</nav>

filemtime "warning stat failed for"

Shorter version for those who like short code:

// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)


function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {

    // $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age

    foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) { 

        if (is_writable($f) && filemtime($f) < (time() - $timeout))
            unlink($f);

    }

}

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

How to add to an NSDictionary

When ever the array is declared, then only we have to add the key-value's in NSDictionary like

NSDictionary *normalDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2",@"Value3",@"Key3",nil];

we cannot add or remove the key values in this NSDictionary

Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];'
[mutableDict setObject:@"Value1" forKey:@"Key1"];
[mutableDict setObject:@"Value2" forKey:@"Key2"];
[mutableDict setObject:@"Value3" forKey:@"Key3"];

for removing the key value we have to use the following code

[mutableDict removeObject:@"Value1" forKey:@"Key1"];

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

  1. Declare the variable
  2. Set it by your command and add dynamic parts like use parameter values of sp(here @IsMonday and @IsTuesday are sp params)
  3. execute the command

    declare  @sql varchar (100)
    set @sql ='select * from #td1'
    
    if (@IsMonday+@IsTuesday !='')
    begin
    set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
    end
    exec( @sql)
    

Looping through JSON with node.js

If we are using nodeJS, we should definitely take advantage of different libraries it provides. Inbuilt functions like each(), map(), reduce() and many more from underscoreJS reduces our efforts. Here's a sample

    var _=require("underscore");
    var fs=require("fs");

    var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));


    _.map( jsonObject, function(content) {
        _.map(content,function(data){
           if(data.Timestamp)
              console.log(data.Timestamp)          
           })
      })

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Maven does not find JUnit tests to run

In my case we are migration multimodule application to Spring Boot. Unfortunately maven didnt execute all tests anymore in the modules. The naming of the Test Classes didnt change, we are following the naming conventions.

At the end it helped, when I added the dependency surefire-junit47 to the plugin maven-surefire-plugin. But I could not explain, why, it was trial and error:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<dependencies>
  <dependency>
    <groupId>org.apache.maven.surefire</groupId>
    <artifactId>surefire-junit47</artifactId>
    <version>${maven-surefire-plugin.version}</version>
  </dependency>
</dependencies>

Fast query runs slow in SSRS

If your stored procedure uses linked servers or openquery, they may run quickly by themselves but take a long time to render in SSRS. Some general suggestions:

  • Retrieve the data directly from the server where the data is stored by using a different data source instead of using the linked server to retrieve the data.
  • Load the data from the remote server to a local table prior to executing the report, keeping the report query simple.
  • Use a table variable to first retrieve the data from the remote server and then join with your local tables instead of directly returning a join with a linked server.

I see that the question has been answered, I'm just adding this in case someone has this same issue.

Launching an application (.EXE) from C#?

Here's a snippet of helpful code:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

How to export iTerm2 Profiles

There is another way to do this.

From iTerm2 2.9.20140923 you can use Dynamic Profiles as stated in the documentation page:

Dynamic Profiles is a feature that allows you to store your profiles in a file outside the usual macOS preferences database. Profiles may be changed at runtime by editing one or more plist files (formatted as JSON, XML, or in binary). Changes are picked up immediately.

So it is possible to create a file like this one:

    {
        "Profiles": [{
                "Name": "MYSERVER1",
                "Guid": "MYSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "M",
                "Tags": [
                    "LOCAL", "THATCOMPANY", "WORK", "NOCLOUD"
                ],
                "Badge Text": "SRV1",
            },
            {
                "Name": "MYOCEANSERVER1",
                "Guid": "MYOCEANSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "O",
                "Tags": [
                    "THATCOMPANY", "WORK", "DIGITALOCEAN"
                ],
                "Badge Text": "PPOCEAN1",
            },
            {
                "Name": "PI1",
                "Guid": "PI1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "1",
                "Tags": [
                    "LOCAL", "PERSONAL", "RASPBERRY", "SMALL"
                ],
                "Badge Text": "LocalServer",
            },
            {
                "Name": "VUZERO",
                "Guid": "VUZERO",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "0",
                "Tags": [
                    "LOCAL", "PERSONAL", "SMALL"
                ],
                "Badge Text": "TeleVision",
            }
        ]
    }

in the folder ~/Library/Application\ Support/iTerm2/DynamicProfiles/ and share it across different machines. This enables you to retain some visual differences among iterm2 installations such as font type or dimension, while synchronising remote hosts, shortcuts, commands, and even a small badge to quickly identify a session

badge

How to install Boost on Ubuntu

Install libboost-all-dev by entering the following commands in the terminal

Step 1

Update package repositories and get latest package information.

sudo apt update -y

Step 2

Install the packages and dependencies with -y flag .

sudo apt install -y libboost-all-dev

Now that you have your libboost-all-dev installed source: https://linuxtutorial.me/ubuntu/focal/libboost-all-dev/

div hover background-color change?

div hover background color change

Try like this:

.class_name:hover{
    background-color:#FF0000;
}

Finish all previous activities

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case, LoginActivity is the first activity in my program to run.

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. Then put the following code inside the LoginActivity's onCreate(...), to listen for when LoginActivity is recreated and the 'EXIT' signal was passed:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}

Why is making an exit button in Android so hard?

Android tries hard to discourage you from having an "exit" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not.

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.

Specify an SSH key for git push for a given domain

You might need to remove (or comment out) default Host configuration .ssh/config

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

Why does ASP.NET webforms need the Runat="Server" attribute?

Pretty redundant attribute, considering the "asp" tag is obviously an ASP element and should be enough to identify it as a server side accessible element.

Elsewhere however it used to elevate normal tags to be used in the code-behind.

Strings as Primary Keys in SQL Database

Indices imply lots of comparisons.

Typically, strings are longer than integers and collation rules may be applied for comparison, so comparing strings is usually more computationally intensive task than comparing integers.

Sometimes, though, it's faster to use a string as a primary key than to make an extra join with a string to numerical id table.

Standard Android Button with a different color

You can Also use this online tool to customize your button http://angrytools.com/android/button/ and use android:background="@drawable/custom_btn" to define the customized button in your layout.

Define variable to use with IN operator (T-SQL)

I know this is old now but TSQL => 2016, you can use STRING_SPLIT:

DECLARE @InList varchar(255) = 'This;Is;My;List';

WITH InList (Item) AS (
    SELECT value FROM STRING_SPLIT(@InList, ';')
)

SELECT * 
FROM [Table]
WHERE [Item] IN (SELECT Tag FROM InList)

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

Include files from parent or other directory

I took inspiration from frank and I added something like this in my "settings.php" file that is then included in all pages when there is a link:

"settings.php"

    $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

     $slash="";

    for ($i=1;$i<=($folder_depth-2);++$i){

        $slash= $slash."../";

    }

in my header.php to be included in all pages:

a href= .... php echo $slash.'index.php'....

seems it works both on local and hosted environment....

(NOTE: I am an absolute beginner )

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

To add a little bit more information that confused me; I had always thought the same result could be achieved like so;

theDate.ToString("yyyy-MM-dd HH:mm:ss")

However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:

2009-06-15 13.45.30

Just wanted to add why the answer provided needs to be as it is;

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

:-)

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Example #1:

class A{
 void met(){
   Class.forName("com.example.Class1");
 }
}

If com/example/Class1 doesn't exist in any of the classpaths, then It throws ClassNotFoundException.

Example #2:

Class B{
  void met(){
   com.example.Class2 c = new com.example.Class2();
 }
}

If com/example/Class2 existed while compiling B, but not found while execution, then It throws NoClassDefFoundError.

Both are run time exceptions.

How to kill all processes with a given partial name?

Use pkill -f, which matches the pattern for any part of the command line

pkill -f my_pattern

How to pass prepareForSegue: an object

In Swift 4.2 I would do something like that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.yourData = self.someData
    }
}

How to move an element down a litte bit in html

<style>
.row-2 UL LI A
{
  margin-top: 10px;  /* or whatever amount you need it to move down */
}
</style>

How do I protect Python code?

If we focus on software licensing, I would recommend to take a look at another Stack Overflow answer I wrote here to get some inspiration of how a license key verification system can be constructed.

There is an open-source library on GitHub that can help you with the license verification bit.

You can install it by pip install licensing and then add the following code:

pubKey = "<RSAKeyValue><Modulus>sGbvxwdlDbqFXOMlVUnAF5ew0t0WpPW7rFpI5jHQOFkht/326dvh7t74RYeMpjy357NljouhpTLA3a6idnn4j6c3jmPWBkjZndGsPL4Bqm+fwE48nKpGPjkj4q/yzT4tHXBTyvaBjA8bVoCTnu+LiC4XEaLZRThGzIn5KQXKCigg6tQRy0GXE13XYFVz/x1mjFbT9/7dS8p85n8BuwlY5JvuBIQkKhuCNFfrUxBWyu87CFnXWjIupCD2VO/GbxaCvzrRjLZjAngLCMtZbYBALksqGPgTUN7ZM24XbPWyLtKPaXF2i4XRR9u6eTj5BfnLbKAU5PIVfjIS+vNYYogteQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"

res = Key.activate(token="WyIyNTU1IiwiRjdZZTB4RmtuTVcrQlNqcSszbmFMMHB3aWFJTlBsWW1Mbm9raVFyRyJd",\
                   rsa_pub_key=pubKey,\
                   product_id=3349, key="ICVLD-VVSZR-ZTICT-YKGXL", machine_code=Helpers.GetMachineCode())

if res[0] == None not Helpers.IsOnRightMachine(res[0]):
    print("An error occured: {0}".format(res[1]))
else:
    print("Success")

You can read more about the way the RSA public key, etc are configured here.

Youtube - How to force 480p video quality in embed link / <iframe>

You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.

player.setPlaybackQuality(suggestedQuality:String):Void

This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]

How to rename a directory/folder on GitHub website?

There is no way to do this in the GitHub web application. I believe to only way to do this is in the command line using git mv <old name> <new name> or by using a Git client(like SourceTree).

Converting time stamps in excel to dates

This DATE-thing won't work in all Excel-versions.

=CELL_ID/(60 * 60 * 24) + "1/1/1970"

is a save bet instead.
The quotes are necessary to prevent Excel from calculating the term.

Disabling browser print options (headers, footers, margins) from page?

This worked for me with about 1cm margin

@page 
{
    size:  auto;   /* auto is the initial value */
    margin: 0mm;  /* this affects the margin in the printer settings */
}
html
{
    background-color: #FFFFFF; 
    margin: 0mm;  /* this affects the margin on the html before sending to printer */
}
body
{
    padding:30px; /* margin you want for the content */
}

Is JavaScript's "new" keyword considered harmful?

I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.

Oracle PL/SQL : remove "space characters" from a string

I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL

my_value := regexp_replace(my_value, '[[:space:]]*',''); 

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

CSS 3 slide-in from left transition

I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:

_x000D_
_x000D_
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
    var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
    position: absolute;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: blue;_x000D_
    transform: translateY(-100%);_x000D_
    -webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
    animation: slide-in 0.5s forwards;_x000D_
    -webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
    animation: slide-out 0.5s forwards;_x000D_
    -webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
    _x000D_
@keyframes slide-in {_x000D_
    100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
    100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
    _x000D_
@keyframes slide-out {_x000D_
    0% { transform: translateY(0%); }_x000D_
    100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
    0% { -webkit-transform: translateY(0%); }_x000D_
    100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
    <ul>_x000D_
        <li>Lorem</li>_x000D_
        <li>Ipsum</li>_x000D_
        <li>Dolor</li>_x000D_
    </ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I'm not 100% sure, but I believe the error was caused by some client-side JavaScript that was turning exports into an object. Some code in the Slick plugin (see below) calls the require function if exports is not undefined.

Here's the portion of code I had to change in slick.js. You can see I am just commenting out the if statements, and, instead, I'm just calling factory(jQuery).

;(function(factory) {
console.log('slick in factory', define, 'exports', exports, 'factory', factory);
'use strict';
// if (typeof define === 'function' && define.amd) {
//     define(['jquery'], factory);
// } else if (typeof exports !== 'undefined') {
//     module.exports = factory(require('jquery'));
// } else {
//     factory(jQuery);
// }
factory(jQuery);
}

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

window.location.href doesn't redirect

I'll give you one nice function for this problem:

function url_redirect(url){
    var X = setTimeout(function(){
        window.location.replace(url);
        return true;
    },300);

    if( window.location = url ){
        clearTimeout(X);
        return true;
    } else {
        if( window.location.href = url ){
            clearTimeout(X);
            return true;
        }else{
            clearTimeout(X);
            window.location.replace(url);
            return true;
        }
    }
    return false;
};

This is universal working solution for the window.location problem. Some browsers go into problem with window.location.href and also sometimes can happen that window.location fail. That's why we also use window.location.replace() for any case and timeout for the "last try".

How to get single value from this multi-dimensional PHP array

The first element of $myarray is the array of values you want. So, right now,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

$myarray = $myarray[0];

Now, $myarray['email'] etc. will output as expected.

draw diagonal lines in div background with CSS

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

Can I find events bound on an element with jQuery?

Note that events may be attached to the document itself rather than the element in question. In that case, you'll want to use:

$._data( $(document)[0], "events" );

And find the event with the correct selector:

enter image description here

And then look at the handler > [[FunctionLocation]]

enter image description here

Read Content from Files which are inside Zip file

If you're wondering how to get the file content from each ZipEntry it's actually quite simple. Here's a sample code:

public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:/test.zip");

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);
    }
}

Once you have the InputStream you can read it however you want.

How to pass multiple values through command argument in Asp.net?

I checked your code and seems to be no problem at all. please make sure Image commandArgument getting value. check it first binding in label whether you are getting value.

However, here is sample which I'm using in my project

<asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False" Width="100%" runat="server" OnRowCommand="GridViews_RowCommand" >
        <Columns>
            <asp:TemplateField SortExpression="SendDate">
                <ItemTemplate>
                <asp:Button ID="btnPost" CssClass="submitButton" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>' />

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

first bind the GridView.

public void GetData()
{
   //bind ur GridView
   GridViewUserScraps.DataSource = dt;
   GridViewUserScraps.DataBind();
}

protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Comment")
    {
        string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
        string scrapid = commandArgs[0];
        string uid = commandArgs[1];
    }
}

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

In Mongoose, how do I sort by date? (node.js)

Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

You can send any standard parameters you need to find() (e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort() on. You need to call find() again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.

MySQL CURRENT_TIMESTAMP on create and on update

I think you maybe want ts_create as datetime (so rename -> dt_create) and only ts_update as timestamp? This will ensure it remains unchanging once set.

My understanding is that datetime is for manually-controlled values, and timestamp's a bit "special" in that MySQL will maintain it for you. In this case, datetime is therefore a good choice for ts_create.

java Arrays.sort 2d array

Although this is an old thread, here are two examples for solving the problem in Java8.

sorting by the first column ([][0]):

double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0]));

sorting by the first two columns ([][0], [][1]):

double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.<double[]>comparingDouble(a -> a[0]).thenComparingDouble(a -> a[1]));

Cannot use string offset as an array in php

I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

After changing:

$params = '';

to:

$params = array();

I stopped getting the error. I found the solution in this bug report thread. I hope this helps.

Python Error: "ValueError: need more than 1 value to unpack"

Probably you didn't provide an argument on the command line. In that case, sys.argv only contains one value, but it would have to have two in order to provide values for both user_name and script.