Programs & Examples On #Dynamic

Dynamic is a widely used term that, in general, describes a decision made by the program at run-time rather than at compile time.

How do you dynamically add elements to a ListView on Android?

First, you have to add a ListView, an EditText and a button into your activity_main.xml.

Now, in your ActivityMain:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

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

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

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

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}

This works for me, I hope I helped you

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How can I create a dynamically sized array of structs?

If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

Some example code would be:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

How do I work with dynamic multi-dimensional arrays in C?

If you know the number of columns at compile time, it's pretty simple:

#define COLS ...
...
size_t rows;
// get number of rows
T (*ap)[COLS] = malloc(sizeof *ap * rows); // ap is a *pointer to an array* of T

You can treat ap like any 2D array:

ap[i][j] = x;

When you're done you deallocate it as

free(ap);

If you don't know the number of columns at compile time, but you're working with a C99 compiler or a C2011 compiler that supports variable-length arrays, it's still pretty simple:

size_t rows;
size_t cols;
// get rows and cols
T (*ap)[cols] = malloc(sizeof *ap * rows);
...
ap[i][j] = x;
...
free(ap);

If you don't know the number of columns at compile time and you're working with a version of C that doesn't support variable-length arrays, then you'll need to do something different. If you need all of the elements to be allocated in a contiguous chunk (like a regular array), then you can allocate the memory as a 1D array, and compute a 1D offset:

size_t rows, cols;
// get rows and columns
T *ap = malloc(sizeof *ap * rows * cols);
...
ap[i * rows + j] = x;
...
free(ap);

If you don't need the memory to be contiguous, you can follow a two-step allocation method:

size_t rows, cols;
// get rows and cols
T **ap = malloc(sizeof *ap * rows);
if (ap)
{
  size_t i = 0;
  for (i = 0; i < cols; i++)
  {
    ap[i] = malloc(sizeof *ap[i] * cols);
  }
}

ap[i][j] = x;

Since allocation was a two-step process, deallocation also needs to be a two-step process:

for (i = 0; i < cols; i++)
  free(ap[i]);
free(ap);

How to perform runtime type checking in Dart?

Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:

class Foo { 
  Type get runtimeType => String;
}
main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
  print("type is ${foo.runtimeType}");

}

will output:

it's a foo! 
type is String

Which is wrong. Now, I can't see the reason why one should do such a thing...

How to create own dynamic type or dynamic object in C#?

 var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

  var data = new { studentId, StudentName };

Dynamic WHERE clause in LINQ

I have similar scenario where I need to add filters based on the user input and I chain the where clause.

Here is the sample code.

var votes = db.Votes.Where(r => r.SurveyID == surveyId);
if (fromDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value >= fromDate);
}
if (toDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value <= toDate);
}
votes = votes.Take(LimitRows).OrderByDescending(r => r.VoteDate);

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

Change UITableView height dynamically

Rob's solution is very nice, only thing that in his -(void)adjustHeightOfTableview method the calling of

[self.view needsUpdateConstraints]

does nothing, it just returns a flag, instead calling

[self.view setNeedsUpdateConstraints]

will make the desired effect.

How to dynamically allocate memory space for a string and get that string from user?

You could have an array that starts out with 10 elements. Read input character by character. If it goes over, realloc another 5 more. Not the best, but then you can free the other space later.

Get value of c# dynamic property via string

public static object GetProperty(object target, string name)
{
    var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
    return site.Target(site, target);
}

Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.

Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:

public static object GetProperty(object target, string name)
{
    return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}

Using braces with dynamic variable names in PHP

Try using {} instead of ():

${"file".$i} = file($filelist[$i]);

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

How do I check if a property exists on a dynamic anonymous type in c#?

This works for anonymous types, ExpandoObject, Nancy.DynamicDictionary or anything else that can be cast to IDictionary<string, object>.

    public static bool PropertyExists(dynamic obj, string name) {
        if (obj == null) return false;
        if (obj is IDictionary<string, object> dict) {
            return dict.ContainsKey(name);
        }
        return obj.GetType().GetProperty(name) != null;
    }

How to generate a HTML page dynamically using PHP?

I was wondering if/how I can 'create' a html page for each database row?

You just need to create one php file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST or GET and then get the info form the database.

I'm assuming this would be better for SEO?

Search Engine as Google interpret that example.php?id=33 and example.php?id=44 are different pages, and yes, this way is better than single listing page from the SEO point of view, so you just need two php files at least (listing.php and single.php), because is better link this pages from the listing.php.

Extra advice:

example.php?id=33 is really ugly and not very seo friendly, maybe you need some url rewriting code. Something like example/properties/property-name is better ;)

JavaScript: how to change form action attribute value based on selection?

It's better to use

$('#search-form').setAttribute('action', '/controllerName/actionName');

rather than

$('#search-form').attr('action', '/controllerName/actionName');

So, based on trante's answer we have:

$('#search-form').submit(function() {
    var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
    $("#search-form").setAttribute("action", "/search/" + formAction);
}); 

Using setAttribute can save you a lot of time potentially.

create unique id with javascript

function uniqueid(){
    // always start with a letter (for DOM friendlyness)
    var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
    do {                
        // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
        var ascicode=Math.floor((Math.random()*42)+48);
        if (ascicode<58 || ascicode>64){
            // exclude all chars between : (58) and @ (64)
            idstr+=String.fromCharCode(ascicode);    
        }                
    } while (idstr.length<32);

    return (idstr);
}

What is the difference between call and apply?

Summary:

Both call() and apply() are methods which are located on Function.prototype. Therefore they are available on every function object via the prototype chain. Both call() and apply() can execute a function with a specified value of the this.

The main difference between call() and apply() is the way you have to pass in arguments into it. In both call() and apply() you pass as a first argument the object you want to be the value as this. The other arguments differ in the following way:

  • With call() you have to put in the arguments normally (starting from the second argument)
  • With apply() you have to pass in array of arguments.

Example:

_x000D_
_x000D_
let obj = {_x000D_
  val1: 5,_x000D_
  val2: 10_x000D_
}_x000D_
_x000D_
const summation = function (val3, val4) {_x000D_
  return  this.val1 + this.val2 + val3 + val4;_x000D_
}_x000D_
_x000D_
console.log(summation.apply(obj, [2 ,3]));_x000D_
// first we assign we value of this in the first arg_x000D_
// with apply we have to pass in an array_x000D_
_x000D_
_x000D_
console.log(summation.call(obj, 2, 3));_x000D_
// with call we can pass in each arg individually
_x000D_
_x000D_
_x000D_

Why would I need to use these functions?

The this value can be tricky sometimes in javascript. The value of this determined when a function is executed not when a function is defined. If our function is dependend on a right this binding we can use call() and apply() to enforce this behaviour. For example:

_x000D_
_x000D_
var name = 'unwantedGlobalName';_x000D_
_x000D_
const obj =  {_x000D_
  name: 'Willem',_x000D_
  sayName () { console.log(this.name);}_x000D_
}_x000D_
_x000D_
_x000D_
let copiedMethod = obj.sayName;_x000D_
// we store the function in the copiedmethod variable_x000D_
_x000D_
_x000D_
_x000D_
copiedMethod();_x000D_
// this is now window, unwantedGlobalName gets logged_x000D_
_x000D_
copiedMethod.call(obj);_x000D_
// we enforce this to be obj, Willem gets logged
_x000D_
_x000D_
_x000D_

How to add buttons dynamically to my form?

You could do something like this:

Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
    Button b = new Button();
    b.Size = new Size(10, 50);
    b.Location = newLoc;
    newLoc.Offset(0, b.Height + 5);
    Controls.Add(b);
}

If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.

Automatically create an Enum based on values in a database lookup table?

I've done this with a T4 template. It is fairly trivial to drop a .tt file into your project, and set up Visual Studio to run the T4 template as a pre-build step.

The T4 generates a .cs file, which means you can have it just query the database and build an enum in a .cs file from the result. Wired up as a pre-build task, it would re-create your enum on every build, or you can run the T4 manually as needed instead.

How do I call a dynamically-named method in Javascript?

you can do it like this:

function MyClass() {
    this.abc = function() {
        alert("abc");
    }
}

var myObject = new MyClass();
myObject["abc"]();

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

I would always use sp_executesql these days, all it really is is a wrapper for EXEC which handles parameters & variables.

However do not forget about OPTION RECOMPILE when tuning queries on very large databases, especially where you have data spanned over more than one database and are using a CONSTRAINT to limit index scans.

Unless you use OPTION RECOMPILE, SQL server will attempt to create a "one size fits all" execution plan for your query, and will run a full index scan each time it is run.

This is much less efficient than a seek, and means it is potentially scanning entire indexes which are constrained to ranges which you are not even querying :@

What is the difference between dynamic programming and greedy approach?

I would like to cite a paragraph which describes the major difference between greedy algorithms and dynamic programming algorithms stated in the book Introduction to Algorithms (3rd edition) by Cormen, Chapter 15.3, page 381:

One major difference between greedy algorithms and dynamic programming is that instead of first finding optimal solutions to subproblems and then making an informed choice, greedy algorithms first make a greedy choice, the choice that looks best at the time, and then solve a resulting subproblem, without bothering to solve all possible related smaller subproblems.

Add Bean Programmatically to Spring Web App Context

In Spring 3.0 you can make your bean implement BeanDefinitionRegistryPostProcessor and add new beans via BeanDefinitionRegistry.

In previous versions of Spring you can do the same thing in BeanFactoryPostProcessor (though you need to cast BeanFactory to BeanDefinitionRegistry, which may fail).

C# winforms combobox dynamic autocomplete

 using (var client = new UserServicesClient())
 {
     var list = new AutoCompleteStringCollection();
     list.AddRange(client.ListNames(query).ToArray());
     comboBoxName.AutoCompleteCustomSource = list;
 }

Static array vs. dynamic array in C++

Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.

int arr[] = { 1, 3, 4 }; // static integer array.   
int* arr = new int[3]; // dynamic integer array.

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

Dynamically fill in form values with jQuery

Automatically fill all form fields from an array

http://jsfiddle.net/brynner/wf0rk7tz/2/

JS

function fill(a){
    for(var k in a){
        $('[name="'+k+'"]').val(a[k]);
    }
}

array_example = {"God":"Jesus","Holy":"Spirit"};

fill(array_example);

HTML

<form>
<input name="God">
<input name="Holy">
</form>

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Compiling dynamic HTML strings from database

You can use

ng-bind-html https://docs.angularjs.org/api/ng/service/$sce

directive to bind html dynamically. However you have to get the data via $sce service.

Please see the live demo at http://plnkr.co/edit/k4s3Bx

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
    $scope.getHtml=function(){
   return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
   }
});

  <body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
  </body>

Deserialize JSON into C# dynamic object?

Look at the article I wrote on CodeProject, one that answers the question precisely:

Dynamic types with JSON.NET

There is way too much for re-posting it all here, and even less point since that article has an attachment with the key/required source file.

WPF Image Dynamically changing Image source during runtime

Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

Modifying CSS class property values on the fly with JavaScript / jQuery

You can't modify the members of a CSS class on the fly. However, you could introduce a new <style> tag on the page with your new css class implementation, and then switch out the class. Example:

Sample.css

.someClass { border: 1px solid black; font-size: 20px; }

You want to change that class entirely, so you create a new style element:

<style>
   .someClassReplacement { border: 1px solid white; font-size: 14px; }       
</style>

You then do a simple replacement via jQuery:

$('.someClass').removeClass('someClass').addClass('someClassReplacement');

What is the correct way to write HTML using Javascript?

element.InnerHtml= allmycontent: will re-write everything inside the element. You must use a variable let allmycontent="this is what I want to print inside this element"to store the whole content you want inside this element. If not each time you will call this function, the content of your element will be erased and replace with the last call you made of it.

document.write(): can be use several times, each time the content will be printed where the call is made on the page.

But be aware: document.write() method is only useful for inserting content at page creation . So use it for not repeating when having a lot of data to write like a catalogue of products or images.

Here a simple example: all your li for your aside menu are stored in an array "tab", you can create a js script with the script tag directly into the html page and then use the write method in an iterative function where you want to insert those li on the page.

<script type="text/javascript">
document.write("<ul>");
for (var i=0; i<=tab.length; i++){
    document.write(tab[i]);
    }document.write("</ul>");
</script>`

This works because Js is interpreted in a linear way during the loading. So make sure your script is at the right place in your html page.You can also use an external Js file, but then again you must declare it at the place where you want it to be interpreted.

For this reason, document.write cannot be called for writing something on your page as a result of a "user interaction" (like click or hover), because then the DOM has been created and write method will, like said above, write a new page (purge the actual execution stack and start a new stack and a new DOM tree). In this case use:

element.innerHTML=("Myfullcontent");

To learn more about document's methods: open your console: document; then open: __proto__: HTMLDocumentPrototype

You'll see the function property "write" in the document object. You can also use document.writeln which add a new line at each statement. To learn more about a function/method, just write its name into the console with no parenthesis: document.write; The console will return a description instead of calling it.

Are parameters in strings.xml possible?

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>

Declare an empty two-dimensional array in Javascript?

You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Call static method with reflection

You could really, really, really optimize your code a lot by paying the price of creating the delegate only once (there's also no need to instantiate the class to call an static method). I've done something very similar, and I just cache a delegate to the "Run" method with the help of a helper class :-). It looks like this:

static class Indent{    
     public static void Run(){
         // implementation
     }
     // other helper methods
}

static class MacroRunner {

    static MacroRunner() {
        BuildMacroRunnerList();
    }

    static void BuildMacroRunnerList() {
        macroRunners = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(x => x.Namespace.ToUpper().Contains("MACRO"))
            .Select(t => (Action)Delegate.CreateDelegate(
                typeof(Action), 
                null, 
                t.GetMethod("Run", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
            .ToList();
    }

    static List<Action> macroRunners;

    public static void Run() {
        foreach(var run in macroRunners)
            run();
    }
}

It is MUCH faster this way.

If your method signature is different from Action you could replace the type-casts and typeof from Action to any of the needed Action and Func generic types, or declare your Delegate and use it. My own implementation uses Func to pretty print objects:

static class PrettyPrinter {

    static PrettyPrinter() {
        BuildPrettyPrinterList();
    }

    static void BuildPrettyPrinterList() {
        printers = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(x => x.Name.EndsWith("PrettyPrinter"))
            .Select(t => (Func<object, string>)Delegate.CreateDelegate(
                typeof(Func<object, string>), 
                null, 
                t.GetMethod("Print", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
            .ToList();
    }

    static List<Func<object, string>> printers;

    public static void Print(object obj) {
        foreach(var printer in printers)
            print(obj);
    }
}

Dynamic variable names in Bash

Wow, most of the syntax is horrible! Here is one solution with some simpler syntax if you need to indirectly reference arrays:

#!/bin/bash

foo_1=(fff ddd) ;
foo_2=(ggg ccc) ;

for i in 1 2 ;
do
    eval mine=( \${foo_$i[@]} ) ;
    echo ${mine[@]}" " ;
done ;

For simpler use cases I recommend the syntax described in the Advanced Bash-Scripting Guide.

Simple dynamic breadcrumb

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Variable length (Dynamic) Arrays in Java

How about using a List instead? For example, ArrayList<integer>

Android - Dynamically Add Views into View

It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

Changing datagridview cell color dynamically

If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

What is the 'dynamic' type in C# 4.0 used for?

It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:

For example, you might use the following code to increment a counter in XML in C#.

Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);

By using the DLR, you could use the following code instead for the same operation.

scriptobj.Count += 1;

MSDN lists these advantages:

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

See MSDN for more details.

Test if a property is available on a dynamic variable

For me this works:

if (IsProperty(() => DynamicObject.MyProperty))
  ; // do stuff



delegate string GetValueDelegate();

private bool IsProperty(GetValueDelegate getValueMethod)
{
    try
    {
        //we're not interesting in the return value.
        //What we need to know is whether an exception occurred or not

        var v = getValueMethod();
        return v != null;
    }
    catch (RuntimeBinderException)
    {
        return false;
    }
    catch
    {
        return true;
    }
}

How to change default timezone for Active Record in Rails?

for Chinese user, just add two lines below to you config/application.rb :

config.active_record.default_timezone = :local
config.time_zone = 'Beijing'

Remove spaces from a string in VB.NET

"Spaces" in the original post could refer to whitespace, and no answer yet shows how to remove ALL whitespace from a string. For that regular expressions are the most flexible approach I've found.

Below is a console application where you can see the difference between replacing just spaces or all whitespace.

You can find more about .NET regular expressions at http://msdn.microsoft.com/en-us/library/hs600312.aspx and http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Imports System.Text.RegularExpressions
Module TestRegExp
    Sub Main()
        ' Use to match all whitespace (note the lowercase s matters)
        Dim regWhitespace As New Regex("\s")

        ' Use to match space characters only
        Dim regSpace As New Regex(" ")

        Dim testString As String = "First Line" + vbCrLf + _
        "Second line followed by 2 tabs" + vbTab + vbTab + _
        "End of tabs"

        Console.WriteLine("Test string :")
        Console.WriteLine(testString)

        Console.WriteLine("Replace all whitespace :")
        ' This prints the string on one line with no spacing at all
        Console.WriteLine(regWhitespace.Replace(testString, String.Empty))

        Console.WriteLine("Replace all spaces :")
        ' This removes spaces, but retains the tabs and new lines
        Console.WriteLine(regSpace.Replace(testString, String.Empty))

        Console.WriteLine("Press any key to finish")
        Console.ReadKey()
    End Sub
End Module

What's the best way to use R scripts on the command line (terminal)?

Try littler. littler provides hash-bang (i.e. script starting with #!/some/path) capability for GNU R, as well as simple command-line and piping use.

Simple JavaScript problem: onClick confirm not preventing default action

There's a typo in your code (the tag a is closed too early). You can either use:

<a href="whatever" onclick="return confirm('are you sure?')"><img ...></a>

note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:

<script type="text/javascript">
function confirm_delete() {
  return confirm('are you sure?');
}
</script>
...
<a href="whatever" onclick="return confirm_delete()"><img ...></a>

(note that delete is a keyword)

For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

Java/ JUnit - AssertTrue vs AssertFalse

I think it's just for your convenience (and the readers of your code)

Your code, and your unit tests should be ideally self documenting which this API helps with,

Think abt what is more clear to read:

AssertTrue(!(a > 3));

or

AssertFalse(a > 3);

When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I'm using Mojave with rbenv, this solution works for me:

$ vi ~/.bash_profile

Add this line into the file:

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

How to log SQL statements in Spring Boot?

If you want to view the actual parameters used to query you can use

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE

Then notice that actual parameter value is shown as binding parameter......

   2018-08-07 14:14:36.079 DEBUG 44804 --- [           main] org.hibernate.SQL                        : select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.joining_date as joining_3_0_, employee0_.name as name4_0_ from employee employee0_ where employee0_.joining_date=?
    2018-08-07 14:14:36.079 TRACE 44804 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [TIMESTAMP] - [Tue Aug 07 00:00:00 SGT 2018]

Creating a jQuery object from a big HTML-string

the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html. once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object

Remove accents/diacritics in a string in JavaScript

I used this gitHub dundalek's repository as Node module : https://github.com/dundalek/latinize

It's works simply like that :

_x000D_
_x000D_
var latinize = require('latinize');
latinize('??A??lÉ áéíóúýcdenrštžu'); // => 'ExAmPlE aeiouycdenrstzu'
_x000D_
_x000D_
_x000D_

How to create a date and time picker in Android?

Another option is the android-wheel project that comes pretty close the the UIDatePicker dialog of iOS.

It provides a vertical slider to pick anything(including date and time). If you prefer horizontal slider, the DateSlider referenced by Rabi is better.

Extension methods must be defined in a non-generic static class

Change it to

public static class LinqHelper

Select Specific Columns from Spark DataFrame

Solved, just use select method for the dataframe to select columns:

 val df=spark.read.csv("C:\\Users\\Ahmed\\Desktop\\cabs_trajectories\\cabs_trajectories\\green\\2014\\green_tripdata_2014-09.csv")

val df1=df.select("_c0")

this would subset the first column of the dataframe

Difference between Date(dateString) and new Date(dateString)

I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:

var temp = new Date(  Date("2010-08-17 12:09:36")   );
alert(temp);

the internal call to Date() returns a string that new Date() can parse.

Python, Matplotlib, subplot: How to set the axis range?

You have pylab.ylim:

pylab.ylim([0,1000])

Note: The command has to be executed after the plot!

Update 2021
Since the use of pylab is now strongly discouraged by matplotlib, you should instead use pyplot:

from matplotlib import pyplot as plt
plt.ylim(0, 100) 
#corresponding function for the x-axis
plt.xlim(1, 1000)

Disable click outside of bootstrap modal area to close modal

The solution that work for me is the following:

$('#myModal').modal({backdrop: 'static', keyboard: false})  

backdrop: disabled the click outside event

keyboard: disabled the scape keyword event

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

header location not working in my php code

It should be Location not location:

header('Location: index.php');

<img>: Unsafe value used in a resource URL context

Either you can expose sanitizer to the view, or expose a method that forwards the call to bypassSecurityTrustUrl

<img class='photo-img' [hidden]="!showPhoto1" 
    [src]='sanitizer.bypassSecurityTrustUrl(theMediaItem.photoURL1)'>

Delete all records in a table of MYSQL in phpMyAdmin

Go to your db -> structure and do empty in required table. See here:

this screenshot

Oracle Error ORA-06512

I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.

Why should I prefer to use member initialization lists?

Before the body of the constructor is run, all of the constructors for its parent class and then for its fields are invoked. By default, the no-argument constructors are invoked. Initialization lists allow you to choose which constructor is called and what arguments that constructor receives.

If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

Angular2 module has no exported member

For my case, I restarted the server and it worked.

How to deal with "data of class uneval" error from ggplot2?

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)

ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

How to use enums in C++

First of all, make 'E' in enum, 'e' as a lower case.

Second, drop type name 'Days' in 'Days.Saturday'.

Third ...buy yourself a good C++ book.

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Maven does not find JUnit tests to run

In case someone has searched and I do not solve it, I had a library for different tests:

<dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${org.junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>

When I installed junit everything worked, I hope and help this:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

vue.js 'document.getElementById' shorthand

You can use the directive v-el to save an element and then use it later.

https://vuejs.org/api/#vm-els

<div v-el:my-div></div>
<!-- this.$els.myDiv --->

Edit: This is deprecated in Vue 2, see ??? answer

Use PHP to create, edit and delete crontab jobs?

I tried the solution below

class Crontab {

// In this class, array instead of string would be the standard input / output format.

// Legacy way to add a job:
// $output = shell_exec('(crontab -l; echo "'.$job.'") | crontab -');

static private function stringToArray($jobs = '') {
    $array = explode("\r\n", trim($jobs)); // trim() gets rid of the last \r\n
    foreach ($array as $key => $item) {
        if ($item == '') {
            unset($array[$key]);
        }
    }
    return $array;
}

static private function arrayToString($jobs = array()) {
    $string = implode("\r\n", $jobs);
    return $string;
}

static public function getJobs() {
    $output = shell_exec('crontab -l');
    return self::stringToArray($output);
}

static public function saveJobs($jobs = array()) {
    $output = shell_exec('echo "'.self::arrayToString($jobs).'" | crontab -');
    return $output; 
}

static public function doesJobExist($job = '') {
    $jobs = self::getJobs();
    if (in_array($job, $jobs)) {
        return true;
    } else {
        return false;
    }
}

static public function addJob($job = '') {
    if (self::doesJobExist($job)) {
        return false;
    } else {
        $jobs = self::getJobs();
        $jobs[] = $job;
        return self::saveJobs($jobs);
    }
}

static public function removeJob($job = '') {
    if (self::doesJobExist($job)) {
        $jobs = self::getJobs();
        unset($jobs[array_search($job, $jobs)]);
        return self::saveJobs($jobs);
    } else {
        return false;
    }
}

}

credits to : Crontab Class to Add, Edit and Remove Cron Jobs

Preventing multiple clicks on button

We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.

$(document).ready(function () {     
    $("#disable").on('click', function () {
        $(this).off('click'); 
        // enter code here
    });
})

Select values from XML field in SQL Server 2008

SELECT 
cast(xmlField as xml).value('(/person//firstName/node())[1]', 'nvarchar(max)') as FirstName,
cast(xmlField as xml).value('(/person//lastName/node())[1]', 'nvarchar(max)') as LastName
FROM [myTable]

mysql update column with value from another table

In my case, the accepted solution was just too slow. For a table with 180K rows the rate of updates was about 10 rows per second. This is with the indexes on the join elements.

I finally resolved my issue using a procedure:

CREATE DEFINER=`my_procedure`@`%` PROCEDURE `rescue`()
BEGIN
    declare str VARCHAR(255) default '';
    DECLARE n INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE cur_name VARCHAR(45) DEFAULT '';
    DECLARE cur_value VARCHAR(10000) DEFAULT '';
    SELECT COUNT(*) FROM tableA INTO n;
    SET i=0;
    WHILE i<n DO 
      SELECT namea,valuea FROM tableA limit i,1 INTO cur_name,cur_value;
      UPDATE tableB SET nameb=cur_name where valueb=cur_value;
      SET i = i + 1;
    END WHILE;

END

I hope it will help someone in the future like it helped me

How can I assign an ID to a view programmatically?

Yes, you can call setId(value) in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value). Note that it is valid to call setId() with the same value for different sibling views, but findViewById() will return only the first one.

OnclientClick and OnClick is not working at the same time?

Your JavaScript is fine, unless you have other scripts running on this page which may corrupt everything. You may check this using Firebug.

I've now tested a bit and it really seems that ASP.net ignores disabled controls. Basically the postback is issued, but probably the framework ignores such events since it "assumes" that a disabled button cannot raise any postback and so it ignores possibly attached handlers. Now this is just my personal reasoning, one could use Reflector to check this in more depth.

As a solution you could really try to do the disabling at a later point, basically you delay the control.disabled = "disabled" call using a JavaTimer or some other functionality. In this way 1st the postback to the server is issued before the control is being disabled by the JavaScript function. Didn't test this but it could work

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

Compute mean and standard deviation by group for multiple variables in a data.frame

There are a few different ways to go about it. reshape2 is a helpful package. Personally, I like using data.table

Below is a step-by-step

If myDF is your data.frame:

library(data.table)
DT <- data.table(myDF)

DT

# this will get you your mean and SD's for each column
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x)))]

# adding a `by` argument will give you the groupings
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x))), by=ID]

# If you would like to round the values: 
DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID]

# If we want to add names to the columns 
wide <- setnames(DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID], c("ID", sapply(names(DT)[-1], paste0, c(".men", ".SD"))))

wide

   ID Obs.1.men Obs.1.SD Obs.2.men Obs.2.SD Obs.3.men Obs.3.SD
1:  1    35.333    8.021    36.333   10.214      33.0    9.644
2:  2    29.750    3.594    32.250    4.193      30.5    5.916
3:  3    41.500    4.950    43.500    4.950      39.0    4.243

Also, this may or may not be helpful

> DT[, sapply(.SD, summary), .SDcols=names(DT)[-1]]
        Obs.1 Obs.2 Obs.3
Min.    25.00 28.00 22.00
1st Qu. 29.00 31.00 27.00
Median  33.00 32.00 36.00
Mean    34.22 36.11 33.22
3rd Qu. 38.00 40.00 37.00
Max.    45.00 48.00 42.00

How to display a "busy" indicator with jQuery?

yes, it's really just a matter of showing/hiding an animated gif.

C++ preprocessor __VA_ARGS__ number of arguments

With msvc extension:

#define Y_TUPLE_SIZE(...) Y_TUPLE_SIZE_II((Y_TUPLE_SIZE_PREFIX_ ## __VA_ARGS__ ## _Y_TUPLE_SIZE_POSTFIX,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0))
#define Y_TUPLE_SIZE_II(__args) Y_TUPLE_SIZE_I __args

#define Y_TUPLE_SIZE_PREFIX__Y_TUPLE_SIZE_POSTFIX ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0

#define Y_TUPLE_SIZE_I(__p0,__p1,__p2,__p3,__p4,__p5,__p6,__p7,__p8,__p9,__p10,__p11,__p12,__p13,__p14,__p15,__p16,__p17,__p18,__p19,__p20,__p21,__p22,__p23,__p24,__p25,__p26,__p27,__p28,__p29,__p30,__p31,__n,...) __n

Works for 0 - 32 arguments. This limit can be easily extended.

EDIT: Simplified version (works in VS2015 14.0.25431.01 Update 3 & gcc 7.4.0) up to 100 arguments to copy & paste:

#define COUNTOF(...) _COUNTOF_CAT( _COUNTOF_A, ( 0, ##__VA_ARGS__, 100,\
    99, 98, 97, 96, 95, 94, 93, 92, 91, 90,\
    89, 88, 87, 86, 85, 84, 83, 82, 81, 80,\
    79, 78, 77, 76, 75, 74, 73, 72, 71, 70,\
    69, 68, 67, 66, 65, 64, 63, 62, 61, 60,\
    59, 58, 57, 56, 55, 54, 53, 52, 51, 50,\
    49, 48, 47, 46, 45, 44, 43, 42, 41, 40,\
    39, 38, 37, 36, 35, 34, 33, 32, 31, 30,\
    29, 28, 27, 26, 25, 24, 23, 22, 21, 20,\
    19, 18, 17, 16, 15, 14, 13, 12, 11, 10,\
    9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ) )
#define _COUNTOF_CAT( a, b ) a b
#define _COUNTOF_A( a0, a1, a2, a3, a4, a5, a6, a7, a8, a9,\
    a10, a11, a12, a13, a14, a15, a16, a17, a18, a19,\
    a20, a21, a22, a23, a24, a25, a26, a27, a28, a29,\
    a30, a31, a32, a33, a34, a35, a36, a37, a38, a39,\
    a40, a41, a42, a43, a44, a45, a46, a47, a48, a49,\
    a50, a51, a52, a53, a54, a55, a56, a57, a58, a59,\
    a60, a61, a62, a63, a64, a65, a66, a67, a68, a69,\
    a70, a71, a72, a73, a74, a75, a76, a77, a78, a79,\
    a80, a81, a82, a83, a84, a85, a86, a87, a88, a89,\
    a90, a91, a92, a93, a94, a95, a96, a97, a98, a99,\
    a100, n, ... ) n

How to strip comma in Python string

unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

CSS: background image on background color

<li style="background-color: #ffffff;"><a href="/<%=logo_marka_url%>"><img border="0" style="border-radius:5px;background: url(images/picture.jpg') 50% 50% no-repeat;width:150px;height:80px;" src="images/clearpixel.gif"/></a></li>

Other Sample Box Center Image and Background Color

1.First clearpixel fix image area 2.style center image area box 3.li background or div color style

How to do a Jquery Callback after form submit?

For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions

@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{ 
  ... html for form
}

here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form

$("#btnSubmitFileUpload").click(function(e){
        e.preventDefault();
        $("#frmUploadTrainingMedia").submit();
});

here is the callback referenced in the AjaxOptions

function displayUploadMediaMsg(d){
    var rslt = $.parseJSON(d.responseText);
    if (rslt.statusCode == 200){
        $().toastmessage("showSuccessToast", rslt.status);
    }
    else{
        $().toastmessage("showErrorToast", rslt.status);
    }
}

in the controller method for MVC it looks like this

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // there is only one file  ... do something with it
        }
        return Json(new
        {
            statusCode = 200,
            status = "File uploaded",
            file = "",
        }, "text/html");
    }
    else
    {
        return Json(new
        {
            statusCode = 400,
            status = "Unable to upload file",
            file = "",
        }, "text/html");
    }
}

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

Check play state of AVPlayer

The Swift version of maxkonovalov's answer is this:

player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)

and

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "rate" {
        if let rate = change?[NSKeyValueChangeNewKey] as? Float {
            if rate == 0.0 {
                print("playback stopped")
            }
            if rate == 1.0 {
                print("normal playback")
            }
            if rate == -1.0 {
                print("reverse playback")
            }
        }
    }
}

Thank you maxkonovalov!

How to get the URL of the current page in C#

Just sharing as this was my solution thanks to Canavar's post.

If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"

or like this:

"https://www.something.com/index.html?a=123&b=4567"

and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152

Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297

MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Merge two (or more) lists into one, in C# .NET

you can combine them using LINQ:

  list = list1.Concat(list2).Concat(list3).ToList();

the more traditional approach of using List.AddRange() might be more efficient though.

How can I generate a unique ID in Python?

import time
import random
import socket
import hashlib

def guid( *args ):
    """
    Generates a universally unique ID.
    Any arguments only create more randomness.
    """
    t = long( time.time() * 1000 )
    r = long( random.random()*100000000000000000L )
    try:
        a = socket.gethostbyname( socket.gethostname() )
    except:
        # if we can't get a network address, just imagine one
        a = random.random()*100000000000000000L
    data = str(t)+' '+str(r)+' '+str(a)+' '+str(args)
    data = hashlib.md5(data).hexdigest()

    return data

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Indirectly Relevant: when 1=2 is used:

CREATE TABLE New_table_name 
as 
select * 
FROM Old_table_name 
WHERE 1 = 2;

this will create a new table with same schema as old table. (Very handy if you want to load some data for compares)

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

from here ORA-00054: resource busy and acquire with NOWAIT specified

You can also look up the sql,username,machine,port information and get to the actual process which holds the connection

SELECT O.OBJECT_NAME, S.SID, S.SERIAL#, P.SPID, S.PROGRAM,S.USERNAME,
S.MACHINE,S.PORT , S.LOGON_TIME,SQ.SQL_FULLTEXT 
FROM V$LOCKED_OBJECT L, DBA_OBJECTS O, V$SESSION S, 
V$PROCESS P, V$SQL SQ 
WHERE L.OBJECT_ID = O.OBJECT_ID 
AND L.SESSION_ID = S.SID AND S.PADDR = P.ADDR 
AND S.SQL_ADDRESS = SQ.ADDRESS;

ROW_NUMBER() in MySQL

Also a bit late but today I had the same need so I did search on Google and finally a simple general approach found here in Pinal Dave's article http://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/

I wanted to focus on Paul's original question (that was my problem as well) so I summarize my solution as a working example.

Beacuse we want to partition over two column I would create a SET variable during the iteration to identify if a new group was started.

SELECT col1, col2, col3 FROM (
  SELECT col1, col2, col3,
         @n := CASE WHEN @v = MAKE_SET(3, col1, col2)
                    THEN @n + 1 -- if we are in the same group
                    ELSE 1 -- next group starts so we reset the counter
                END AS row_number,
         @v := MAKE_SET(3, col1, col2) -- we store the current value for next iteration
    FROM Table1, (SELECT @n := 0, @v := NULL) r -- helper table for iteration with startup values
   ORDER BY col1, col2, col3 DESC -- because we want the row with maximum value
) x WHERE row_number = 1 -- and here we select exactly the wanted row from each group

The 3 means at the first parameter of MAKE_SET that I want both value in the SET (3=1|2). Of course if we do not have two or more columns constructing the groups we can eliminate the MAKE_SET operation. The construction is exactly the same. This is working for me as required. Many thanks to Pinal Dave for his clear demonstration.

How to upgrade all Python packages with pip

Here is a script that only updates the outdated packages.

import os, sys
from subprocess import check_output, call

file = check_output(["pip.exe",  "list", "--outdated", "--format=legacy"])
line = str(file).split()

for distro in line[::6]:
    call("pip install --upgrade " + distro, shell=True)

For a new version of pip that does not output as a legacy format (version 18+):

import os, sys
from subprocess import check_output, call

file = check_output(["pip.exe", "list", "-o", "--format=json"])
line = str(file).split()

for distro in line[1::8]:
    distro = str(distro).strip('"\",')
    call("pip install --upgrade " + distro, shell=True)

How to avoid HTTP error 429 (Too Many Requests) python

if response.status_code == 429:
  time.sleep(int(response.headers["Retry-After"]))

How to format a JavaScript date

In modern browsers (*), you can just do this:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

Output if executed today (january 24??, 2016):

'24-Jan-2016'

(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.

How do I activate a virtualenv inside PyCharm's terminal?

If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it's full path and paste it in pycharm's terminal then press Enter and you're done!

If you need to create new virtual environment :

Go to files > settings then search for project interpreter, open it, click on gear button and create the environment wherever you want and then follow first paragraph.

The Gear!

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

Convert HH:MM:SS string to seconds only in javascript

Since the getTime function of the Date object gets the milliseconds since 1970/01/01, we can do this:

var time = '12:23:00';
var seconds = new Date('1970-01-01T' + time + 'Z').getTime() / 1000;

How do I get the size of a java.sql.ResultSet?

The way of getting size of ResultSet, No need of using ArrayList etc

int size =0;  
if (rs != null)   
{  
rs.beforeFirst();  
 rs.last();  
size = rs.getRow();
}

Now You will get size, And if you want print the ResultSet, before printing use following line of code too,

rs.beforeFirst();  

Detailed 500 error message, ASP + IIS 7.5

In my case it was permission issue. Open application folder properties -> Security tab -> Edit -> Add

  • IIS AppPool\[DefaultAppPool or any other apppool] (if use ApplicationPoolIdentity option)
  • IUSRS
  • IIS_IUSRS

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

How to create a .gitignore file

In mac - you can just create a new text file. add content using https://www.gitignore.io/

save the file with file format as - Rich Text document with attachments. change file name to .gitingore and select use"." when a pop up comes as in the attached image.

NOTE : since it is a hidden file so you wont be able to see it in the directory. but it will be created.

see image

Something like 'contains any' for Java set?

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

How to dynamically set bootstrap-datepicker's date value?

$("#datepicker").datepicker("setDate", new Date);

How to upgrade rubygems

Or:

gem update `gem outdated | cut -d ' ' -f 1`

Service Reference Error: Failed to generate code for the service reference

I had this problem when trying to update my service reference (The error only shows up when adding a service reference though) but didn't want to remove the assembly reuse checkbox.

What worked for me was the following:

  • Remove referenced assembly that I wanted to re-use
  • Update service reference
  • Keep "Reuse types in specified referenced assemblies"
  • Ignore the errors, it's because the reference is missing!
  • Add reference to assembly again to fix the errors
  • Update service reference again

Voila, now it actually updates and doesn't try to remove all of my generated code anymore.

I was almost ready to give up on the re-use types feature...

EDIT: Also make sure that the build config is AnyCPU or x86, since svcutil is buggy with x64.

To the downvoter: Sorry if it didn't work for you, I don't even know why it worked for me, but it did. I may have done something else that time that fixed the problem, but no way to know now.

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

How can I search for a multiline pattern in a file?

Why don't you go for awk:

awk '/Start pattern/,/End pattern/' filename

How to validate phone numbers using regex

Here is what I use

function isValidTel ($tel) {
    preg_match('/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im', $tel, $matches);
    return !! $matches;
}

Check it out in this regex tester https://www.phpliveregex.com/p/uld

Checkbox for nullable boolean

Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:

@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")

It's like accepted answer from @afinkelstein except we don't need special 'editor template'

How to convert string to string[]?

A string holds one value, but a string[] holds many strings, as it's an array of string.

See more here

Remove trailing zeros from decimal in SQL Server

Try this :

SELECT REPLACE(TRIM(REPLACE(20.5500, "0", " ")), " ", "0")

Gives 20.55

for each inside a for each - Java

most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...

ADB - Android - Getting the name of the current activity

Old answers stopped working in new android versions. Now I use the following:

adb shell "dumpsys activity activities | grep ResumedActivity"

Date to milliseconds and back to date in Swift

//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
    let currentDate = Date()
    let since1970 = currentDate.timeIntervalSince1970
    return Int(since1970 * 1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds() -> Date {
        return Date(timeIntervalSince1970: TimeInterval(self)/1000)
    }
}

I removed seemingly useless conversion via string and all those random !.

How to verify if a file exists in a batch file?

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Possible reason for NGINX 499 error codes

Turns out 499's really does mean "client interrupted connection."

I had a client "read timeout" setting of 60s (and nginx also has a default proxy_read_timeout of 60s). So what was happening in my case is that nginx would error.log an upstream timed out (110: Connection timed out) while reading upstream and then nginx retries "the next proxy server in the backend server group you configured." That's if you have more than one.

Then it tries the next and next till (by default) it has exhausted all of them. As each one times out, it removes them from the list of "live" backend servers, as well. After all are exhausted, it returns a 504 gateway timeout.

So in my case nginx marked the server as "unavailable", re-tried it on the next server, then my client's 60s timeout (immediately) occurred, so I'd see a upstream timed out (110: Connection timed out) while reading upstream log, immediately followed by a 499 log. But it was just timing coincidence.

Related:

If all servers in the group are marked as currently unavailable, then it returns a 502 Bad Gateway. for 10s as well. See here max_fails and fail_timeout. Inn the logs it will say no live upstreams while connecting to upstream.

If you only have one proxy backend in your server group, it just try's the one server, and returns a 504 Gateway Time-out and doesn't remove the single server from the list of "live" servers, if proxy_read_timeout is surpassed. See here "If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable."

The really tricky part is that if you specify proxy_pass to "localhost" and your box happens to also have ipv6 and ipv4 "versions of location" on it at the same time (most boxes do by default), it will count as if you had a "list" of multiple servers in your server group, which means you can get into the situation above of having it return "502 for 10s" even though you list only one server. See here "If a domain name resolves to several addresses, all of them will be used in a round-robin fashion." One workaround is to declare it as proxy_pass http://127.0.0.1:5001; (its ipv4 address) to avoid it being both ipv6 and ipv4. Then it counts as "only a single server" behavior.

There's a few different settings you can tweak to make this "less" of a problem. Like increasing timeouts or making it so it doesn't mark servers as "disabled" when they timeout...or fixing the list so it's only size 1, see above :)

See also: https://serverfault.com/a/783624/27813

What are the advantages and disadvantages of recursion?

Some situation would arise where you would have to abandon recursion in a problem where recursion appears to be to your advantage, this is because for problems where your recursion would have to occur thousand of times this would result in a stackoverflow error even though your code did not get stuck in an infinite recursion. Most programming languages limits you to a number of stack calls, so if your recursion goes beyond this limit, then you might consider not using recursion.

How do I remove background-image in css?

When background-image: none !important; have no effect. You can use:

background-size: 0 !important;

Choose newline character in Notepad++

For a new document: Settings -> Preferences -> New Document/Default Directory -> New Document -> Format -> Windows/Mac/Unix

And for an already-open document: Edit -> EOL Conversion

How to semantically add heading to a list

In this case I would use a definition list as so:

<dl>
  <dt>Fruits I like:</dt>
  <dd>Apples</dd>
  <dd>Bananas</dd>
  <dd>Oranges</dd>
</dl>

Copy folder recursively, excluding some folders

Use tar along with a pipe.

cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )

You can even use this technique across ssh.

How to check for DLL dependency?

The pedeps project (https://github.com/brechtsanders/pedeps) has a command line tool (copypedeps) for copying your .exe (or .dll) file(s) along with all the files it depends on. If you do that on the system where the application works, you should be able to ship it with all it's dependancy DLLs.

What is thread Safe in java?

As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.

Consider the following method:

private int myInt = 0;
public int AddOne()
{
    int tmp = myInt;
    tmp = tmp + 1;
    myInt = tmp;
    return tmp;
}

Now thread A and thread B both would like to execute AddOne(). but A starts first and reads the value of myInt (0) into tmp. Now for some reason the scheduler decides to halt thread A and defer execution to thread B. Thread B now also reads the value of myInt (still 0) into it's own variable tmp. Thread B finishes the entire method, so in the end myInt = 1. And 1 is returned. Now it's Thread A's turn again. Thread A continues. And adds 1 to tmp (tmp was 0 for thread A). And then saves this value in myInt. myInt is again 1.

So in this case the method AddOne() was called two times, but because the method was not implemented in a thread safe way the value of myInt is not 2, as expected, but 1 because the second thread read the variable myInt before the first thread finished updating it.

Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

I cannot start SQL Server browser

go to Services, find SQL Server Browser, right click --> Properties --> General tab --> Startup Type --> select automatic . Then go back to configuration management, start it.

C - determine if a number is prime

Avoid overflow bug

unsigned i, number;
...
for (i=2; i*i<=number; i++) {  // Buggy
for (i=2; i*i<=number; i += 2) {  // Buggy
// or
for (i=5; i*i<=number; i+=6) { // Buggy

These forms are incorrect when number is a prime and i*i is near the max value of the type.

Problem exists with all integer types, signed, unsigned and wider.

Example:

Let UINT_MAX_SQRT as the floor of the square root of the maximum integer value. E.g. 65535 when unsigned is 32-bit.

With for (i=2; i*i<=number; i++), this 10-year old failure occurs because when UINT_MAX_SQRT*UINT_MAX_SQRT <= number and number is a prime, the next iteration results in a multiplication overflow. Had the type been a signed type, the overflow is UB. With unsigned types, this itself is not UB, yet logic has broken down. Interations continue until a truncated product exceeds number. An incorrect result may occur. With 32-bit unsigned, try 4,294,967,291? which is a prime.

If some_integer_type_MAX been a Mersenne Prime, i*i<=number is never true.


To avoid this bug, consider that number%i, number/i is efficient on many compilers as the calculations of the quotient and remainder are done together, thus incurring no extra cost to do both vs. just 1.

A simple full-range solution:

bool IsPrime(unsigned number) {
    for(unsigned i = 2; i <= number/i; i++){
        if(number % i == 0){
            return false;
        }
    }
    return number >= 2;
}

Open multiple Eclipse workspaces on the Mac

One another way is just to duplicate only the "Eclipse.app" file instead of making multiple copies of entire eclipse directory. Right-Click on the "Eclipse.app" file and click the duplicate option to create a duplicate.

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

CSS Div stretch 100% page height

It's simple using a table:

<html>

<head>
    <title>100% Height test</title>
</head>

<body>
    <table style="float: left; height: 100%; width: 200px; border: 1px solid red">
        <tbody>
            <tr>
                <td>Nav area</td>
            </tr>
        </tbody>
    </table>
    <div style="border: 1px solid green;">Content blabla... text
        <br /> text
        <br /> text
        <br /> text
        <br />
    </div>
</body>

</html>

When DIV was introduced, people were so afraid of tables that the poor DIV became the metaphorical hammer.

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

Is there a MySQL option/feature to track history of changes to records?

The direct way of doing this is to create triggers on tables. Set some conditions or mapping methods. When update or delete occurs, it will insert into 'change' table automatically.

But the biggest part is what if we got lots columns and lots of table. We have to type every column's name of every table. Obviously, It's waste of time.

To handle this more gorgeously, we can create some procedures or functions to retrieve name of columns.

We can also use 3rd-part tool simply to do this. Here, I write a java program Mysql Tracker

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Good Free Alternative To MS Access

In the context of a programming forum, we don't usually think of the programmer also needing the application portion of the database. Normally a programmer wants to use their own development environment for the business logic and front end, and just use the store, query, retrieval, and data processing capabilities of the database.

If you really want all those other things, then you're talking about a much larger and more complicated run time environment. You're not going to find anything that's 'lightweight' any more. Even MS Access itself no longer qualifies, because it's hardly light weight. It's just lucky in that a lot of users might already have it, making it appear to be light weight.

This doesn't mean you won't find anything. Just that it's not likely to have the same level of maturity or distribution as Access, especially since the underlying access engine is already baked into Windows.

Send HTML in email via PHP

Use PHPMailer,

To send HTML mail you have to set $mail->isHTML() only, and you can set your body with HTML tags

Here is a well written tutorial :

rohitashv.wordpress.com/2013/01/19/how-to-send-mail-using-php/

How can I toggle word wrap in Visual Studio?

Following https://docs.microsoft.com/en-gb/visualstudio/ide/reference/how-to-manage-word-wrap-in-the-editor

When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)

General settings: Tools / Options / Text Editor / All Languages / Word wrap

Or search for 'word wrap' in the Quick Launch box.


Known issues:

If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:

  1. Triple click doesn't select whole line
  2. Cut command doesn't delete whole line
  3. Pressing End key twice does not move cursor to end of line

Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case it was the distinction between (En dash) and -(Hyphen) as in:

Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

and:

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Dashes, Hyphens, and Minus signs oh my!

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

Converting a String to a List of Words?

To do this properly is quite complex. For your research, it is known as word tokenization. You should look at NLTK if you want to see what others have done, rather than starting from scratch:

>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
...     nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

Kotlin's List missing "add", "remove", Map missing "put", etc?

A list is immutable by Default, you can use ArrayList instead. like this :

 val orders = arrayListOf<String>()

then you can add/delete items from this like below:

orders.add("Item 1")
orders.add("Item 2")

by default ArrayList is mutable so you can perform the operations on it.

How to programmatically set the Image source

try this

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

Could not establish secure channel for SSL/TLS with authority '*'

This was exact the problem I was facing. At some other article I got a hint to change the configuration. For me this works:

<bindings>
  <basicHttpBinding>
    <binding name="xxxBinding">
      <security mode="Transport">
        <transport clientCredentialType="Certificate"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

How to remove multiple indexes from a list at the same time?

There wasn't much hint on performance for the different ways so I performed a test on removing 5000 items from 50000 in all 3 generally different approaches, and for me numpy was the winner (if you have elements that fit in numpy):

  • 7.5 sec for the enumerated list comprehension [4.5 sec on another PC]
  • 0.08 sec for deleting items in reverse order [0.017 (!) sec]
  • 0.009 sec for numpy.delete [0.006 sec]

Here's the code I timed (in the third function conversion from/to list may be removed if working directly on numpy arrays is ok):

import time
import numpy as np
import random

def del_list_indexes(l, id_to_del):
    somelist = [i for j, i in enumerate(l) if j not in id_to_del]
    return somelist

def del_list_inplace(l, id_to_del):
    for i in sorted(id_to_del, reverse=True):
        del(l[i])

def del_list_numpy(l, id_to_del):
    arr = np.array(l, dtype='int32')
    return list(np.delete(arr, id_to_del))

l = range(50000)
random.shuffle(l)
remove_id = random.sample(range(len(l)), 5000) # 10% ==> 5000

# ...

Error: Cannot pull with rebase: You have unstaged changes

When the unstaged change is because git is attempting to fix eol conventions on a file (as is always my case), no amount of stashing or checking-out or resetting will make it go away.

However, if the intent is really to rebase and ignore unstaged changed, then what I do is delete the branch locally then check it out again.

git checkout -f anyotherbranchthanthisone
git branch -D thebranchineedtorebase
git checkout thebranchineedtorebase

Voila! It hasn't failed me yet.

Recursively find all files newer than a given time

You can find every file what is created/modified in the last day, use this example:

find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print

for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want

What does <T> (angle brackets) mean in Java?

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

Display date/time in user's locale format and time offset

Once you have your date object constructed, here's a snippet for the conversion:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

MySQL: Can't create table (errno: 150)

usually, the mismatch between foreign key & primary key causes the error:150.

The foreign key must have the same datatype as the primary key. Also, if the primary key is unsigned then the foreign key must also be unsigned.

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

Twitter Bootstrap - full width navbar

You need to push the container down the navbar.

Please find my working fiddle here http://jsfiddle.net/meetravi/aXCMW/1/

<header>

    <h2 class="title">Test</h2>
</header>
<div class="navbar">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>

        </ul>
    </div>
</div>
<div class="container">

</div>

How to change UIButton image in Swift

From your Obc-C code I think you want to set an Image for button so try this way:

let playButton  = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
    playButton.setImage(image, forState: .Normal)
}

In Short:

playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)

For Swift 3:

let playButton  = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)

How can I generate an HTML report for Junit results?

I found xunit-viewer, which has deprecated junit-viewer mentioned by @daniel-kristof-kiss.

It is very simple, automatically recursively collects all relevant files in ANT Junit XML format and creates a single html-file with filtering and other sweet features.

I use it to upload test results from Travis builds as Travis has no other support for collecting standard formatted test results output.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

You can Use Direct in bootstrap model also.

<div class="modal fade" id="myModal" data-keyboard="false" data-backdrop="static">

Get Wordpress Category from Single Post

For the lazy and the learning, to put it into your theme, Rfvgyhn's full code

<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

Java - Get a list of all Classes loaded in the JVM

This program will prints all the classes with its physical path. use can simply copy this to any JSP if you need to analyse the class loading from any web/application server.

import java.lang.reflect.Field;
import java.util.Vector;

public class TestMain {

    public static void main(String[] args) {
        Field f;
        try {
            f = ClassLoader.class.getDeclaredField("classes");
            f.setAccessible(true);
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Vector<Class> classes =  (Vector<Class>) f.get(classLoader);

            for(Class cls : classes){
                java.net.URL location = cls.getResource('/' + cls.getName().replace('.',
                '/') + ".class");
                System.out.println("<p>"+location +"<p/>");
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

How to pass password to scp?

Once you set up ssh-keygen as explained above, you can do

scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/

If you want to lessen typing each time, you can modify your .bash_profile file and put

alias remote_scp='scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/

Then from your terminal do source ~/.bash_profile. Afterwards if you type remote_scp in your terminal it should run the scp command without password.

Set width to match constraints in ConstraintLayout

For making your view as match_parent is not possible directly, but we can do it in a little different way, but don't forget to use Left and Right attribute with Start and End, coz if you use RTL support, it will be needed.

    <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

What's a "static method" in C#?

Core of the static keyword that you will have only one copy at RAM of this (method /variable /class ) that's shared for all calling

How to read a file in other directory in python

For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

should actually be

x_file = open(os.path.join('direct', "5_1.txt"), "r")   

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


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


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Error: Java: invalid target release: 11 - IntelliJ IDEA

For me, I was having the same issue but it was with java v8, I am using a different version of java on my machine for my different projects. While importing one of my project I got the same problem. To check the configuration I checked all my SDK related settings whether it is in File->Project->Project Structure / Modules or in the Run/Debug configuration setting. Everything I set to java-8 but still I was getting the same issue. While checking all of the configuration files I found that compiler.xml in .idea is having an entry for the bytecodeTargetLevel which was set to 11. Here if I change it to 8 even though it shows the same compiler output and removing <bytecodeTargetLevel target="11" /> from compiler.xml resolve the issue.

Cannot delete directory with Directory.Delete(path, true)

Editor's note: Although this answer contains some useful information, it is factually incorrect about the workings of Directory.Delete. Please read the comments for this answer, and other answers to this question.


I ran into this problem before.

The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.

Just slap this code into your project.

public static void DeleteDirectory(string target_dir)
{
    string[] files = Directory.GetFiles(target_dir);
    string[] dirs = Directory.GetDirectories(target_dir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

    foreach (string dir in dirs)
    {
        DeleteDirectory(dir);
    }

    Directory.Delete(target_dir, false);
}

Also, for me I personally add a restriction on areas of the machine that are allowed to be deleted because do you want someone to call this function on C:\WINDOWS (%WinDir%) or C:\.

Hover and Active only when not disabled

.button:active:hover:not([disabled]) {
    /*your styles*/
}

You can try this..

PHP Excel Header

Try this

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

Failed to execute removeChild on Node

As others have mentioned, myCoolDiv is a child of markerDiv not playerContainer. If you want to remove myCoolDiv but keep markerDiv for some reason you can do the following

myCoolDiv.parentNode.removeChild(myCoolDiv);

JSFiddle

VBA collection: list of keys

I don't thinks that possible with a vanilla collection without storing the key values in an independent array.

The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:

Dim dict As Dictionary
Set dict = New Dictionary

dict.Add "key1", "value1"
dict.Add "key2", "value2"

Dim key As Variant
For Each key In dict.Keys
    Debug.Print "Key: " & key, "Value: " & dict.Item(key)
Next

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

Google Spreadsheet, Count IF contains a string

You should use

=COUNTIF(A2:A51, "*iPad*")/COUNTA(A2:A51)

Additionally, if you wanted to count more than one element, like iPads OR Kindles, you would use

=SUM(COUNTIF(A2:A51, {"*iPad*", "*kindle*"}))/COUNTA(A2:A51)

in the numerator.

Using GSON to parse a JSON array

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

How to view changes made to files on a certain revision in Subversion

The equivalent command in svn is:

svn log --diff -r revision

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

How to create a toggle button in Bootstrap

If you want to keep a small code base, and you are only going to be needing the toggle button for a small part of the application. I would suggest instead maintain you're javascript code your self (angularjs, javascript, jquery) and just use plain CSS.

Good toggle button generator: https://proto.io/freebies/onoff/

Apache: Restrict access to specific source IP inside virtual host

If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):

Order deny,allow
Deny from all
Allow from 10.0.0.1

You can even specify a subnet

Allow from 10.0.0

Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.

Create a dropdown component

I would say that it depends on what you want to do.

If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.

Here is a sample:

export class DropdownValue {
  value:string;
  label:string;

  constructor(value:string,label:string) {
    this.value = value;
    this.label = label;
  }
}

@Component({
  selector: 'dropdown',
  template: `
    <ul>
      <li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
    </ul>
  `
})
export class DropdownComponent {
  @Input()
  values: DropdownValue[];

  @Input()
  value: string[];

  @Output()
  valueChange: EventEmitter;

  constructor(private elementRef:ElementRef) {
    this.valueChange = new EventEmitter();
  }

  select(value) {
    this.valueChange.emit(value);
  }
}

This allows you to use it this way:

<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>

You can build your dropdown within the component, apply styles and manage selections internally.

Edit

You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:

export class DropdownValue {
  value:string;
  label:string;

  constructor(value:string,label:string) {
    this.value = value;
    this.label = label;
  }
}

@Component({
  selector: 'dropdown',
  template: `
    <ul>
      <li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
    </ul>
  `
})
export class DropdownComponent {
  @Input()
  values: DropdownValue[];

  @Output()
  select: EventEmitter;

  constructor() {
    this.select = new EventEmitter();
  }

  selectItem(value) {
    this.select.emit(value);
  }
}

Then you can use the component like this:

<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>

Notice that the action method is the one of the parent component (not the dropdown one).

Page redirect with successful Ajax request

You can just redirect in your success handler, like this:

window.location.href = "thankyou.php";

Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

How to get first 5 characters from string

You can get your result by simply use substr():

Syntax substr(string,start,length)

Example

<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>

Output :

 Hello

Uses for the '&quot;' entity in HTML

As other answers pointed out, it is most likely generated by some tool.

But if I were the original author of the file, my answer would be: Consistency.

If I am not allowed to put double quotes in my attributes, why put them in the element's content ? Why do these specs always have these exceptional cases .. If I had to write the HTML spec, I would say All double quotes need to be encoded. Done.

Today it is like In attribute values we need to encode double quotes, except when the attribute value itself is defined by single quotes. In the content of elements, double quotes can be, but are not required to be, encoded. (And I am surely forgetting some cases here).

Double quotes are a keyword of the spec, encode them. Lesser/greater than are a keyword of the spec, encode them. etc..

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

How to cast from List<Double> to double[] in Java?

You can use primitive collections from Eclipse Collections and avoid boxing altogether.

DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();

If you can't or don't want to initialize a DoubleList:

List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();

Note: I am a contributor to Eclipse Collections.

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

To add slightly to the other answers, if you actually want to catch SIGTERM (the default signal sent by the kill command), you can use syscall.SIGTERM in place of os.Interrupt. Beware that the syscall interface is system-specific and might not work everywhere (e.g. on windows). But it works nicely to catch both:

c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
....

How do you uninstall a python package that was installed using distutils?

for Python in Windows:

python -m pip uninstall "package_keyword"
uninstall **** (y/n)?

How to retry after exception?

Alternatives to retrying: tenacity and backoff (2020 update)

The retrying library was previously the way to go, but sadly it has some bugs and it hasn't got any updates since 2016. Other alternatives seem to be backoff and tenacity. During the time of writing this, the tenacity had more GItHub stars (2.3k vs 1.2k) and was updated more recently, hence I chose to use it. Here is an example:

from functools import partial
import random # producing random errors for this example

from tenacity import retry, stop_after_delay, wait_fixed, retry_if_exception_type

# Custom error type for this example
class CommunicationError(Exception):
    pass

# Define shorthand decorator for the used settings.
retry_on_communication_error = partial(
    retry,
    stop=stop_after_delay(10),  # max. 10 seconds wait.
    wait=wait_fixed(0.4),  # wait 400ms 
    retry=retry_if_exception_type(CommunicationError),
)()


@retry_on_communication_error
def do_something_unreliable(i):
    if random.randint(1, 5) == 3:
        print('Run#', i, 'Error occured. Retrying.')
        raise CommunicationError()

for i in range(100):
    do_something_unreliable(i)

The above code outputs something like:

Run# 3 Error occured. Retrying.
Run# 5 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 10 Error occured. Retrying.
.
.
.

More settings for the tenacity.retry are listed on the tenacity GitHub page.

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

Alternative to file_get_contents?

If the file is local as your comment about SITE_PATH suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :

function print_xml_data_file()
{
    include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}

function get_xml_data()
{
    ob_start();
    print_xml_data_file();
    $xml_file = ob_get_contents();
    ob_end_clean();
    return $xml_file;
}

If it's remote as lot of others said curl is the way to go. If it isn't present try socket_create or fsockopen. If nothing work... change your hosting provider.

Loop through properties in JavaScript object with Lodash

It would be helpful to understand why you need to do this with lodash. If you just want to check if a key exists in an object, you don't need lodash.

myObject.options.hasOwnProperty('property');

If your looking to see if a value exists, you can use _.invert

_.invert(myObject.options)[value]

Summernote image upload

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}

How to open a page in a new window or tab from code-behind

Try this one

string redirect = "<script>window.open('http://www.google.com');</script>"; 
Response.Write(redirect);

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

Maintain aspect ratio of div but fill screen width and height in CSS?

There is now a new CSS property specified to address this: object-fit.

http://docs.webplatform.org/wiki/css/properties/object-fit

Browser support is still somewhat lacking (http://caniuse.com/#feat=object-fit) - currently works to some extent in most browsers except Microsoft - but given time it is exactly what was required for this question.

Can I access constants in settings.py from templates in Django?

Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.

https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors

The default TEMPLATE_CONTEXT_PROCESSORS :

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

Polling the keyboard (detect a keypress) in python

The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

Windows shell command to get the full path to the current directory?

This has always worked for me:

SET CurrentDir="%~dp0"

ECHO The current file path this bat file is executing in is the following:

ECHO %CurrentDir%

Pause

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Go to your web.config/App.config to verify which .net runtime you are using

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

Here is the solution:

  1. .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.

  2. .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  1. .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

  1. .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework.

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

Type of expression is ambiguous without more context Swift

Not an answer to this question, but as I came here looking for the error others might find this also useful:

For me, I got this Swift error when I tried to use the for (index, object) loop on an array without adding the .enumerated() part ...

Best way to parse command line arguments in C#?

A very simple easy to use ad hoc class for command line parsing, that supports default arguments.

class CommandLineArgs
{
    public static CommandLineArgs I
    {
        get
        {
            return m_instance;
        }
    }

    public  string argAsString( string argName )
    {
        if (m_args.ContainsKey(argName)) {
            return m_args[argName];
        }
        else return "";
    }

    public long argAsLong(string argName)
    {
        if (m_args.ContainsKey(argName))
        {
            return Convert.ToInt64(m_args[argName]);
        }
        else return 0;
    }

    public double argAsDouble(string argName)
    {
        if (m_args.ContainsKey(argName))
        {
            return Convert.ToDouble(m_args[argName]);
        }
        else return 0;
    }

    public void parseArgs(string[] args, string defaultArgs )
    {
        m_args = new Dictionary<string, string>();
        parseDefaults(defaultArgs );

        foreach (string arg in args)
        {
            string[] words = arg.Split('=');
            m_args[words[0]] = words[1];
        }
    }

    private void parseDefaults(string defaultArgs )
    {
        if ( defaultArgs == "" ) return;
        string[] args = defaultArgs.Split(';');

        foreach (string arg in args)
        {
            string[] words = arg.Split('=');
            m_args[words[0]] = words[1];
        }
    }

    private Dictionary<string, string> m_args = null;
    static readonly CommandLineArgs m_instance = new CommandLineArgs();
}

class Program
{
    static void Main(string[] args)
    {
        CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12");
        Console.WriteLine("Arg myStringArg  : '{0}' ", CommandLineArgs.I.argAsString("myStringArg"));
        Console.WriteLine("Arg someLong     : '{0}' ", CommandLineArgs.I.argAsLong("someLong"));
    }
}

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Messages Using Command prompt in Windows 7

Type "msg /?" in the command prompt to get various ways of sending meessages to a user.

Type "net send /?" in the command prompt to get another variation of sending messages across.

What is the difference between Bootstrap .container and .container-fluid classes?

Use .container-fluid when you want your page to shapeshift with every little difference in its viewport size.

Use .container when you want your page to shapeshift to only 4 kinds of sizes, which are also known as "breakpoints".

The breakpoints corresponding to their sizes are:

  • Extra Small: (Only Mobile Resolution)
  • Small: 768px (Tablets)
  • Medium: 992px (Laptops)
  • Large: 1200px (Laptops/Desktops)

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

Get first key in a (possibly) associative array?

If efficiency is not that important for you, you can use array_keys($yourArray)[0] in PHP 5.4 (and higher).

Examples:

# 1
$arr = ["my" => "test", "is" => "best"];    
echo array_keys($arr)[0] . "\r\n"; // prints "my"


# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"

# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"

The advantage over solution:

list($firstKey) = array_keys($yourArray);

is that you can pass array_keys($arr)[0] as a function parameter (i.e. doSomething(array_keys($arr)[0], $otherParameter)).

HTH

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

Matplotlib: Specify format of floats for tick labels

The answer above is probably the correct way to do it, but didn't work for me.

The hacky way that solved it for me was the following:

ax = <whatever your plot is> 
# get the current labels 
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family 
plt.show()

How to run only one task in ansible playbook?

I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags or --skip-tags.

I have set up some tasks, however, with a when: clause that will only fire if a var is set.

e.g.

# role/stuff/tasks/main.yml
- name: do stuff
  when: stuff|default(false)

Now, this task will not fire by default, but only if I set the stuff=true

$ ansible-playbook -e '{"stuff":true}'

or in a playbook:

roles:
- {"role":"stuff", "stuff":true}

How do I comment on the Windows command line?

: this is one way to comment

As a result:

:: this will also work
:; so will this
:! and this

Above styles work outside codeblocks, otherwise:

REM is another way to comment.

What is the difference between using constructor vs getInitialState in React / React Native?

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself.
getInitialState is used with React.createClass and
constructor is used with React.Component.

Hence the question boils down to advantages/disadvantages of using ES6 or ES5.

Let's look at the difference in code

ES5

var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});

ES6

class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};

There is an interesting reddit thread regarding this.

React community is moving closer to ES6. Also it is considered as the best practice.

There are some differences between React.createClass and React.Component. For instance, how this is handled in these cases. Read more about such differences in this blogpost and facebook's content on autobinding

constructor can also be used to handle such situations. To bind methods to a component instance, it can be pre-bonded in the constructor. This is a good material to do such cool stuff.

Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6

Update: April 9, 2019,:

With the new changes in Javascript class API, you don't need a constructor.

You could do

class TodoApp extends React.Component {

    this.state = {items: []}
};

This will still get transpiled to constructor format, but you won't have to worry about it. you can use this format that is more readable.

react hooks image With React Hooks

From React version 16.8, there's a new API Called hooks.

Now, you don't even need a class component to have a state. It can even be done in a functional component.

import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);

Note that the initial state is passed as an argument to useState; useState([])

Read more about react hooks from the official docs

Rebasing remote branches in Git

You can disable the check (if you're really sure you know what you're doing) by using the --force option to git push.

std::string to float or double

Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.

Your own version could look like:

template<typename to, typename from>to lexical_cast(from const &x) {
  std::stringstream os;
  to ret;

  os << x;
  os >> ret;

  return ret;  
}

How can I get stock quotes using Google Finance API?

Perhaps of interest, the Google Finance API documentaton includes a section detailing how to access different parameters via JavaScript.

I suppose the JavaScript API might be a wrapper to the JSON request you mention above... perhaps you could check which HTTP requests are being sent.

no module named urllib.parse (How should I install it?)

Install six, the Python 2 and 3 Compatibility Library:

$ sudo -H pip install six

Use it:

from six.moves.urllib.parse import urlparse

(edit: I deleted the other answer)

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Pointers in C: when to use the ampersand and the asterisk?

When you are declaring a pointer variable or function parameter, use the *:

int *x = NULL;
int *y = malloc(sizeof(int)), *z = NULL;
int* f(int *x) {
    ...
}

NB: each declared variable needs its own *.

When you want to take the address of a value, use &. When you want to read or write the value in a pointer, use *.

int a;
int *b;
b = f(&a);
a = *b;

a = *f(&a);

Arrays are usually just treated like pointers. When you declare an array parameter in a function, you can just as easily declare it is a pointer (it means the same thing). When you pass an array to a function, you are actually passing a pointer to the first element.

Function pointers are the only things that don't quite follow the rules. You can take the address of a function without using &, and you can call a function pointer without using *.

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

How to specify the port an ASP.NET Core application is hosted on?

Alternative solution is to use a hosting.json in the root of the project.

{
  "urls": "http://localhost:60000"
}

And then in Program.cs

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

Try-catch speeding up my code?

9 years later and the bug is still there! You can see it easily with:

   static void Main( string[] args )
    {
      int hundredMillion = 1000000;
      DateTime start = DateTime.Now;
      double sqrt;
      for (int i=0; i < hundredMillion; i++)
      {
        sqrt = Math.Sqrt( DateTime.Now.ToOADate() );
      }
      DateTime end = DateTime.Now;

      double sqrtMs = (end - start).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMs );

      DateTime start2 = DateTime.Now;

      double sqrt2;
      for (int i = 0; i < hundredMillion; i++)
      {
        try
        {
          sqrt2 = Math.Sqrt( DateTime.Now.ToOADate() );
        }
        catch (Exception e)
        {
          int br = 0;
        }
      }
      DateTime end2 = DateTime.Now;

      double sqrtMsTryCatch = (end2 - start2).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMsTryCatch );

      Console.WriteLine( "ratio is " + sqrtMsTryCatch / sqrtMs );

      Console.ReadLine();
    }

The ratio is less than one on my machine, running the latest version of MSVS 2019, .NET 4.6.1

SQL Server dynamic PIVOT query?

Dynamic SQL PIVOT

Different approach for creating columns string

create table #temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    select date, amount, category from #temp
) src
pivot 
(
    max(amount) for category in (' + @cols + ')
) piv'

execute(@query)
drop table #temp

Result

date                    ABC     DEF     GHI
2012-01-01 00:00:00.000 1000.00 NULL    NULL
2012-02-01 00:00:00.000 NULL    500.00  800.00
2012-02-10 00:00:00.000 NULL    700.00  NULL
2012-03-01 00:00:00.000 1100.00 NULL    NULL

How to style input and submit button with CSS?

form element UI is somewhat controlled by browser and operating system, so it is not trivial to style them very reliably in a way that it would look the same in all common browser/OS combinations.

Instead, if you want something specific, I would recommend to use a library that provides you stylable form elements. uniform.js is one such library.

Tomcat Servlet: Error 404 - The requested resource is not available

try this (if the Java EE V6)

package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name="hello",urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

now reach the servlet by http://127.0.0.1:8080/yourapp/hello

where 8080 is default tomcat port, and yourapp is the context name of your applciation

How to put a Scanner input into an array... for example a couple of numbers

import  java.util.Scanner;

class Array {
public static void main(String a[]){

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the size of an Array");

    int num = input.nextInt();

    System.out.println("Enter the Element "+num+" of an Array");

    double[] numbers = new double[num];

    for (int i = 0; i < numbers.length; i++)
    {

        System.out.println("Please enter number");

        numbers[i] = input.nextDouble();

    }

    for (int i = 0; i < numbers.length; i++)
    {

        if ( (i%3) !=0){

            System.out.print("");

            System.out.print(numbers[i]+"\t");

        } else {
            System.out.println("");

            System.out.print(numbers[i]+"\t");
        }

    }

}

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

How to check if Receiver is registered in Android?

i put this code in my parent activity

List registeredReceivers = new ArrayList<>();

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    registeredReceivers.add(System.identityHashCode(receiver));
    return super.registerReceiver(receiver, filter);
}

@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
    if(registeredReceivers.contains(System.identityHashCode(receiver)))
    super.unregisterReceiver(receiver);
}