Programs & Examples On #Dataitem

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

It should work as well

Eval("item") == null?"0": Eval("item");

How can I give access to a private GitHub repository?

It is a simple 3 Step Process :

  1. Go to your private repo and click on settings
  2. To the left of the screen click on Manage access
  3. Then Click on Invite Collaborator

This, but also - the invited user needs to be logged in to Github before clicking the invitation link in their email or they'll get a 404 error.

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

Egit rejected non-fast-forward

This error means that remote repository has had other commits and has paced ahead of your local branch.
I try doing a git pull followed by a git push. If their are No conflicting changes, git pull gets the latest code to my local branch while keeping my changes intact.
Then a git push pushes my changes to the master branch.

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I hit this same problem after implementing IoC for a project (ASP.Net MVC EF6.2).

Usually I would initialise a data context in the constructor of a controller and use the same context to initialise all my repositories.

However using IoC to instantiate the repositories caused them all to have separate contexts and I started getting this error.

For now I've gone back to just newing up the repositories with a common context while I think of a better way.

Simulating ENTER keypress in bash script

You can just use yes.

# yes "" | someCommand

How to get some values from a JSON string in C#?

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

Can't import database through phpmyadmin file size too large

If you do not want to change the settings or play with command line. There is option to compress the file and upload in phpMyAdmin. It should bring down the size considerably.

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

Update React component every second

class ShowDateTime extends React.Component {
   constructor() {
      super();
      this.state = {
        curTime : null
      }
    }
    componentDidMount() {
      setInterval( () => {
        this.setState({
          curTime : new Date().toLocaleString()
        })
      },1000)
    }
   render() {
        return(
          <div>
            <h2>{this.state.curTime}</h2>
          </div>
        );
      }
    }

How to get parameters from the URL with JSP

In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.

This example demonstrates how to include the value of a request parameter in the generated output:

Hello <b><%= request.getParameter("name") %></b>!

If the page was accessed with the URL:

http://hostname.com/mywebapp/mypage.jsp?name=John+Smith

the resulting output would be:

Hello <b>John Smith</b>!

If name is not specified on the query string, the output would be:

Hello <b>null</b>!

This example uses the value of a query parameter in a scriptlet:

<%
    if (request.getParameter("name") == null) {
        out.println("Please enter your name.");
    } else {
        out.println("Hello <b>"+request. getParameter("name")+"</b>!");
    }
%>

What does the ">" (greater-than sign) CSS selector mean?

html
<div>
    <p class="some_class">lohrem text (it will be of red color )</p>    
    <div>
        <p class="some_class">lohrem text (it will  NOT be of red color)</p> 
    </div>
    <p class="some_class">lohrem text (it will be  of red color )</p>
</div>
css
div > p.some_class{
    color:red;
}

All the direct children that are <p> with .some_class would get the style applied to them.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How to fire a button click event from JavaScript in ASP.NET

document.FormName.btnSubmit.click(); 

works for me. Enjoy.

Python slice first and last element in list

Utilize the packing/unpacking operator to pack the middle of the list into a single variable:

>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *middle, last = l
>>> first
'1'
>>> middle
['B', '3', 'D', '5']
>>> last
'F'
>>> 

Or, if you want to discard the middle:

>>> l = ['1', 'B', '3', 'D', '5', 'F']
>>> first, *_, last = l
>>> first
'1'
>>> last
'F'
>>> 

var.replace is not a function

My guess is that the code that's calling your trim function is not actually passing a string to it.

To fix this, you can make str a string, like this: str.toString().replace(...)
...as alper pointed out below.

OWIN Startup Class Missing

This could be faced in Visual Studio 2015 as well when you use the Azure AD with a MVC project. Here it create the startup file as Startup.Auth.cs in App_Start folder but it will be missing the

[assembly: OwinStartup(typeof(MyWebApp.Startup))]

So add it and you should be good to go. This goes before the namespace start.

SET NAMES utf8 in MySQL?

From the manual:

SET NAMES indicates what character set the client will use to send SQL statements to the server.

More elaborately, (and once again, gratuitously lifted from the manual):

SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)

IOS: verify if a point is inside a rect

In objective c you can use CGRectContainsPoint(yourview.frame, touchpoint)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch* touch = [touches anyObject];
CGPoint touchpoint = [touch locationInView:self.view];
if( CGRectContainsPoint(yourview.frame, touchpoint) ) {

}else{

}}

In swift 3 yourview.frame.contains(touchpoint)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let touchpoint:CGPoint = touch.location(in: self.view)
    if wheel.frame.contains(touchpoint)  {

    }else{

    }

}

Using atan2 to find angle between two vectors

If you care about accuracy for small angles, you want to use this:

angle = 2*atan2(|| ||b||a - ||a||b ||, || ||b||a + ||a||b ||)

Where "||" means absolute value, AKA "length of the vector". See https://math.stackexchange.com/questions/1143354/numerically-stable-method-for-angle-between-3d-vectors/1782769

However, that has the downside that in two dimensions, it loses the sign of the angle.

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

SQL Server Convert Varchar to Datetime

As has been said, datetime has no format/string representational format.

You can change the string output with some formatting.

To convert your string to a datetime:

declare @date nvarchar(25) 
set @date = '2011-09-28 18:01:00' 

-- To datetime datatype
SELECT CONVERT(datetime, @date)

Gives:

-----------------------
2011-09-28 18:01:00.000

(1 row(s) affected)

To convert that to the string you want:

-- To VARCHAR of your desired format
SELECT CONVERT(VARCHAR(10), CONVERT(datetime, @date), 105) +' '+ CONVERT(VARCHAR(8), CONVERT(datetime, @date), 108)

Gives:

-------------------
28-09-2011 18:01:00

(1 row(s) affected)

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

Oracle JDBC ojdbc6 Jar as a Maven Dependency

First you need to download the particular jar from Oracle site (ojdbc.jar version 11.2.0.3)

if you download it to C:\filefolder

go to that directory in cmd prompt and provide the below command.It will install the dependency.Then you can build your project.

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dpackaging=jar -Dversion=11.2.0.4.0 -Dfile=ojdbc6.jar -DgeneratePom=true

python for increment inner loop

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

How to put a tooltip on a user-defined function

I tried @ScottK's approach, first as a side feature of my functional UDF, then as a standalone _Help suffix version when I ran into trouble (see below). In hindsight, the latter approach is better anyway--more obvious to a user attentive enough to see a tool tip, and it doesn't clutter up the functional code.

I figured if an inattentive user just typed the function name and closed the parentheses while he thought it over, help would appear and he would be on his way. But dumping a bunch of text into a single cell that I cannot format didn't seem like a good idea. Instead, When the function is entered in a cell with no arguments i.e.

   = interpolateLinear() 
or
   = interpolateLinear_Help()

a msgBox opens with the help text. A msgBox is limited to ~1000 characters, maybe it's 1024. But that's enough (barely 8^/) for my overly tricked out interpolation function. If it's not, you can always open a user form and go to town.

The first time the message box opened, it looked like success. But there are a couple of problems. First of course, the user has to know to enter the function with no arguments (+1 for the _Help suffix UDF).

The big problem is, the msgBox reopens several times in succession, spontaneously while working in unrelated parts of the workbook. Needless to say, it's very annoying. Sometimes it goes on until I get a circular reference warning. Go figure. If a UDF could change the cell formula, I would have done that to shut it up.

I don't know why Excel feels the need recalculate the formula over and over; neither the _Help standalone, nor the full up version (in help mode) has precedents or dependents. There's not an application.volatile statement anywhere. Of course the function returns a value to the calling cell. Maybe that triggers the recalc? But that's what UDFs do. I don't think you can not return a value.

Since you can't modify a worksheet formula from a UDF, I tried to return a specific string --a value --to the calling cell (the only one you can change the value of from a UDF), figuring I would inspect the cell value using application.caller on the next cycle, spot my string, and know not to re-display the help message. Seemed like a good idea at the time--didn't work. Maybe I did something stupid in my sleep-deprived state. I still like the idea. I'll update this when (if) I fix the problem. My quick fix was to add a line on the help box: "Seek help only in an emergency. Delete the offending formula to end the misery.

In the meantime, I tried the Application.MacroOptions approach. Pretty easy, and it looks professional. Just one problem to work out. I'll post a separate answer on that approach later.

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

How to initialize a struct in accordance with C programming language standards

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

How to enable Bootstrap tooltip on disabled button?

This is what myself and tekromancr came up with.

Example element:

<a href="http://www.google.com" id="btn" type="button" class="btn btn-disabled" data-placement="top" data-toggle="tooltip" data-title="I'm a tooltip">Press Me</a>

note: the tooltip attributes can be added to a separate div, in which the id of that div is to be used when calling .tooltip('destroy'); or .tooltip();

this enables the tooltip, put it in any javascript that is included in the html file. this line might not be necessary to add, however. (if the tooltip shows w/o this line then don't bother including it)

$("#element_id").tooltip();

destroys tooltip, see below for usage.

$("#element_id").tooltip('destroy');

prevents the button from being clickable. because the disabled attribute is not being used, this is necessary, otherwise the button would still be clickable even though it "looks" as if it is disabled.

$("#element_id").click(
  function(evt){
    if ($(this).hasClass("btn-disabled")) {
      evt.preventDefault();
      return false;
    }
  });

Using bootstrap, the classes btn and btn-disabled are available to you. Override these in your own .css file. you can add any colors or whatever you want the button to look like when disabled. Make sure you keep the cursor: default; you can also change what .btn.btn-success looks like.

.btn.btn-disabled{
    cursor: default;
}

add the code below to whatever javascript is controlling the button becoming enabled.

$("#element_id").removeClass('btn-disabled');
$("#element_id").addClass('btn-success');
$('#element_id).tooltip('destroy');

tooltip should now only show when the button is disabled.

if you are using angularjs i also have a solution for that, if desired.

Send data through routing paths in Angular

@dev-nish Your code works with little tweaks in them. make the

const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};

into

let navigationExtras: NavigationExtras = {
  state: {
    transd: '',
    workQueue: ,
    services: ,
    code: ''
  }
};

then if you want to specifically sent a type of data, for example, JSON as a result of a form fill you can send the data in the same way as explained before.

Is there a way to access an iteration-counter in Java's for-each loop?

The best and optimized solution is to do the following thing:

int i=0;

for(Type t: types) {
  ......
  i++;
}

Where Type can be any data type and types is the variable on which you are applying for a loop.

Android webview slow

If you are binding to the onclick event, it might be slow on touch screens.

To make it faster, I use fastclick, which uses the much faster touch events to mimic the click event.

Meaning of "referencing" and "dereferencing" in C

Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:

int  c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1

Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.

int n1;
n1 = *p1;

Invalid dereferencing may or may not cause crashes:

  • Dereferencing an uninitialized pointer can cause a crash
  • Dereferencing with an invalid type cast will have the potential to cause a crash.
  • Dereferencing a pointer to a variable that was dynamically allocated and was subsequently de-allocated can cause a crash
  • Dereferencing a pointer to a variable that has since gone out of scope can also cause a crash.

Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.

References:

http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators

& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.

http://www.cplusplus.com/doc/tutorial/pointers/

& is the reference operator    
* is the dereference operator

http://en.wikipedia.org/wiki/Dereference_operator

The dereference operator * is also called the indirection operator.

How to merge a transparent png image with another image using PIL

One can also use blending:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

Connect multiple devices to one device via Bluetooth

Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2 in dependency section of your build.gradle .

jQuery add class .active on menu

I am guessing you are trying to mix Asp code and JS code and at some point it's breaking or not excusing the binding calls correctly.

Perhaps you can try using a delegate instead. It will cut out the complexity of when to bind the click event.

An example would be:

$('body').delegate('.menu li','click',function(){
   var $li = $(this);

   var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;

   if(shouldAddClass){
       $li.addClass('active');
   }
});

See if that helps, it uses the Attribute Starts With Selector from jQuery.

Chi

Write HTML file using Java

Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.

Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:

String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);

SAXTransformerFactory saxFactory =
    (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);

Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
    tHandler.startElement("", "", "html", new AttributesImpl());
        tHandler.startElement("", "", "head", new AttributesImpl());
            tHandler.startElement("", "", "title", new AttributesImpl());
                tHandler.characters("Hello".toCharArray(), 0, 5);
            tHandler.endElement("", "", "title");
        tHandler.endElement("", "", "head");
        tHandler.startElement("", "", "body", new AttributesImpl());
            tHandler.startElement("", "", "p", new AttributesImpl());
                tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
            tHandler.endElement("", "", "p");
        tHandler.endElement("", "", "body");
    tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();

Note that XSLT transformer will release you from the burden of escaping special characters like >, as it takes necessary care of it by itself.

And it is easy to wrap SAX methods like startElement() and characters() to something more convenient to one's taste...

When creating a service with sc.exe how to pass in context parameters?

It also important taking in account how you access the Arguments in the code of the application.

In my c# application I used the ServiceBase class:

 class MyService : ServiceBase
{

    protected override void OnStart(string[] args)
    {
       }
 }

I registered my service using

sc create myService binpath= "MeyService.exe arg1 arg2"

But I couldn't access the arguments through the args variable when I run it as a service.

The MSDN documentation suggests not using the Main method to retrieve the binPath or ImagePath arguments. Instead it suggests placing your logic in the OnStart method and then using (C#) Environment.GetCommandLineArgs();.

To access the first arguments arg1 I need to do like this:

class MyService : ServiceBase
 {

    protected override void OnStart(string[] args)
    {

                log.Info("arg1 == "+Environment.GetCommandLineArgs()[1]);

       }
 }

this would print

       arg1 == arg1

What is the difference between hg forget and hg remove?

From the documentation, you can apparently use either command to keep the file in the project history. Looks like you want remove, since it also deletes the file from the working directory.

From the Mercurial book at http://hgbook.red-bean.com/read/:

Removing a file does not affect its history. It is important to understand that removing a file has only two effects. It removes the current version of the file from the working directory. It stops Mercurial from tracking changes to the file, from the time of the next commit. Removing a file does not in any way alter the history of the file.

The man page hg(1) says this about forget:

Mark the specified files so they will no longer be tracked after the next commit. This only removes files from the current branch, not from the entire project history, and it does not delete them from the working directory.

And this about remove:

Schedule the indicated files for removal from the repository. This only removes files from the current branch, not from the entire project history.

How to create Java gradle project

Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.

  1. The application has external jar dependencies
  2. Create a runnable fat jar with all dependent classes copied to the jar
  3. Create a runnable jar with all dependent libraries copied to a directory "dependencies" and add the classpath in the manifest.

Here is the solution :

  • Install the latest gradle ( check gradle --version . I used gradle 6.6.1)
  • Create a folder and open a terminal
  • Execute gradle init --type java-application
  • Add the required data in the command line
  • Import the project into an IDE (IntelliJ or Eclipse)
  • Edit the build.gradle file with the following tasks.

Runnable fat Jar

task fatJar(type: Jar) {
 clean
 println("Creating fat jar")
 manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
 }
 archiveName "${runnableJar}"
 from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
 println("Fat jar is created")
}

Copy Dependencies

task copyDepends(type: Copy) {
   from configurations.default
   into "${dependsDir}"
}

Create jar with classpath dependecies in manifest

task createJar(type: Jar) {
   println("Cleaning...")
   clean
   manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
             it.getName() }.join(' ')
    )
}
  from {
      configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println "${outputJar} created"
}

Here is the complete build.gradle

plugins {
    id 'java'
   id 'application'
}
repositories {
    mavenCentral()
}
dependencies {
  implementation 'org.slf4j:slf4j-api:1.7.30'
  implementation 'ch.qos.logback:logback-classic:1.2.3'
  implementation 'ch.qos.logback:logback-core:1.2.3'
  testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";

//Create runnable fat jar
task fatJar(type: Jar) {
   clean
   println("Creating fat jar")
   manifest {
    attributes 'Main-Class': 'com.abc.gradle.hello.App'
  }
  archiveName "${runnableJar}"
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } with jar
  println("Fat jar is created")
}

//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
 from configurations.default
 into "${dependsDir}"
}

//Create runnable jar with dependencies
task createJar(type: Jar) {
 println("Cleaning...")
 clean
 manifest {
    attributes('Main-Class': 'com.abc.gradle.hello.App',
            'Class-Path': configurations.default.collect { 'dependencies/' + 
            it.getName() }.join(' ')
    )
 }
 from {
     configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
 } with jar
  println "${outputJar} created"
}

Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar

More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

When you use angular.js for handling events, you should use ng-keydown for preventing pause in developer in chrome.

Difference between clustered and nonclustered index

A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.

A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.

memcpy() vs memmove()

Just because memcpy doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.

Get the time of a datetime using T-SQL?

CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)

IN SQL Server 2008+

CAST(GETUTCDATE() AS TIME)

Setting initial values on load with Select2 with Ajax

Updated to new version:

Try this solution from here http://jsfiddle.net/EE9RG/430/

$('#sel2').select2({
multiple:true,
ajax:{}}).select2({"data": 
     [{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});

In MS DOS copying several files to one file

for %f in (filenamewildcard0, filenamewildcard1, ...) do echo %f >> newtargetfilename_with_path

Same idea as Mike T; might work better under MessyDog's 127 character command line limit

How can I check if a string represents an int, without using try/except?

You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it's the "Pythonic" way, but that's one area where I part ways with them. To me, it's neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.

I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness.

Here's a quick and dirty edit of Bruno's post:

import sys, time, re

g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")

testvals = [
    # integers
    0, 1, -1, 1.0, -1.0,
    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
    # non-integers
    'abc 123',
    1.1, -1.1, '1.1', '-1.1', '+1.1',
    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
    '1.0.', '1..0', '1..',
    '0.0.', '0..0', '0..',
    'one', object(), (1,2,3), [1,2,3], {'one':'two'},
    # with spaces
    ' 0 ', ' 0.', ' .0','.01 '
]

def isInt_try(v):
    try:     i = int(v)
    except:  return False
    return True

def isInt_str(v):
    v = str(v).strip()
    return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def isInt_re(v):
    import re
    if not hasattr(isInt_re, 'intRegex'):
        isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
    return isInt_re.intRegex.match(str(v).strip()) is not None

def isInt_re2(v):
    return g_intRegex.match(str(v).strip()) is not None

def check_int(s):
    s = str(s)
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()    


def timeFunc(func, times):
    t1 = time.time()
    for n in range(times):
        for v in testvals: 
            r = func(v)
    t2 = time.time()
    return t2 - t1

def testFuncs(funcs):
    for func in funcs:
        sys.stdout.write( "\t%s\t|" % func.__name__)
    print()
    for v in testvals:
        if type(v) == type(''):
            sys.stdout.write("'%s'" % v)
        else:
            sys.stdout.write("%s" % str(v))
        for func in funcs:
            sys.stdout.write( "\t\t%s\t|" % func(v))
        sys.stdout.write("\r\n") 

if __name__ == '__main__':
    print()
    print("tests..")
    testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
    print()

    print("timings..")
    print("isInt_try:   %6.4f" % timeFunc(isInt_try, 10000))
    print("isInt_str:   %6.4f" % timeFunc(isInt_str, 10000)) 
    print("isInt_re:    %6.4f" % timeFunc(isInt_re, 10000))
    print("isInt_re2:   %6.4f" % timeFunc(isInt_re2, 10000))
    print("check_int:   %6.4f" % timeFunc(check_int, 10000))

Here are the performance comparison results:

timings..
isInt_try:   0.6426
isInt_str:   0.7382
isInt_re:    1.1156
isInt_re2:   0.5344
check_int:   0.3452

A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think.

EDIT:

I've updated the code above to work in Python 3.5, and to include the check_int function from the currently most voted up answer, and to use the current most popular regex that I can find for testing for integer-hood. This regex rejects strings like 'abc 123'. I've added 'abc 123' as a test value.

It is Very Interesting to me to note, at this point, that NONE of the functions tested, including the try method, the popular check_int function, and the most popular regex for testing for integer-hood, return the correct answers for all of the test values (well, depending on what you think the correct answers are; see the test results below).

The built-in int() function silently truncates the fractional part of a floating point number and returns the integer part before the decimal, unless the floating point number is first converted to a string.

The check_int() function returns false for values like 0.0 and 1.0 (which technically are integers) and returns true for values like '06'.

Here are the current (Python 3.5) test results:

              isInt_try |       isInt_str       |       isInt_re        |       isInt_re2       |   check_int   |
0               True    |               True    |               True    |               True    |       True    |
1               True    |               True    |               True    |               True    |       True    |
-1              True    |               True    |               True    |               True    |       True    |
1.0             True    |               True    |               False   |               False   |       False   |
-1.0            True    |               True    |               False   |               False   |       False   |
'0'             True    |               True    |               True    |               True    |       True    |
'0.'            False   |               True    |               False   |               False   |       False   |
'0.0'           False   |               True    |               False   |               False   |       False   |
'1'             True    |               True    |               True    |               True    |       True    |
'-1'            True    |               True    |               True    |               True    |       True    |
'+1'            True    |               True    |               True    |               True    |       True    |
'1.0'           False   |               True    |               False   |               False   |       False   |
'-1.0'          False   |               True    |               False   |               False   |       False   |
'+1.0'          False   |               True    |               False   |               False   |       False   |
'06'            True    |               True    |               False   |               False   |       True    |
'abc 123'       False   |               False   |               False   |               False   |       False   |
1.1             True    |               False   |               False   |               False   |       False   |
-1.1            True    |               False   |               False   |               False   |       False   |
'1.1'           False   |               False   |               False   |               False   |       False   |
'-1.1'          False   |               False   |               False   |               False   |       False   |
'+1.1'          False   |               False   |               False   |               False   |       False   |
'1.1.1'         False   |               False   |               False   |               False   |       False   |
'1.1.0'         False   |               False   |               False   |               False   |       False   |
'1.0.1'         False   |               False   |               False   |               False   |       False   |
'1.0.0'         False   |               False   |               False   |               False   |       False   |
'1.0.'          False   |               False   |               False   |               False   |       False   |
'1..0'          False   |               False   |               False   |               False   |       False   |
'1..'           False   |               False   |               False   |               False   |       False   |
'0.0.'          False   |               False   |               False   |               False   |       False   |
'0..0'          False   |               False   |               False   |               False   |       False   |
'0..'           False   |               False   |               False   |               False   |       False   |
'one'           False   |               False   |               False   |               False   |       False   |
<obj..>         False   |               False   |               False   |               False   |       False   |
(1, 2, 3)       False   |               False   |               False   |               False   |       False   |
[1, 2, 3]       False   |               False   |               False   |               False   |       False   |
{'one': 'two'}  False   |               False   |               False   |               False   |       False   |
' 0 '           True    |               True    |               True    |               True    |       False   |
' 0.'           False   |               True    |               False   |               False   |       False   |
' .0'           False   |               False   |               False   |               False   |       False   |
'.01 '          False   |               False   |               False   |               False   |       False   |

Just now I tried adding this function:

def isInt_float(s):
    try:
        return float(str(s)).is_integer()
    except:
        return False

It performs almost as well as check_int (0.3486) and it returns true for values like 1.0 and 0.0 and +1.0 and 0. and .0 and so on. But it also returns true for '06', so. Pick your poison, I guess.

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

Convert from enum ordinal to enum type

You can define a simple method like:

public enum Alphabet{
    A,B,C,D;

    public static Alphabet get(int index){
        return Alphabet.values()[index];
    }
}

And use it like:

System.out.println(Alphabet.get(2));

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I ran into the same problem. My fix was changing <parameter value="v12.0" /> to <parameter value="mssqllocaldb" /> into the "app.config" file.

How to format date string in java?

use SimpleDateFormat to first parse() String to Date and then format() Date to String

How to debug Angular JavaScript Code

there is also $log that you can use! it makes use of your console in a way that you want it to work!

showing the error/warning/info the way your console shows you normally!

use this > Document

Is there a common Java utility to break a list into batches?

Check out Lists.partition(java.util.List, int) from Google Guava:

Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

np.append needs the array as the first argument and the list you want to append as the second:

mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])

Playing HTML5 video on fullscreen in android webview

Tested on Android 9.0 version

None of the answers worked for me . This is the final thing worked

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;


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


        mWebView = (WebView) findViewById(R.id.webView);


        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyChrome());
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

       if (savedInstanceState == null) {
          mWebView.loadUrl("https://www.youtube.com/");
       }

    }


    private class MyChrome extends WebChromeClient {

        private View mCustomView;
        private WebChromeClient.CustomViewCallback mCustomViewCallback;
        protected FrameLayout mFullscreenContainer;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        MyChrome() {}

        public Bitmap getDefaultVideoPoster()
        {
            if (mCustomView == null) {
                return null;
            }
            return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
        }

        public void onHideCustomView()
        {
            ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
            this.mCustomView = null;
            getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
            setRequestedOrientation(this.mOriginalOrientation);
            this.mCustomViewCallback.onCustomViewHidden();
            this.mCustomViewCallback = null;
        }

        public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
        {
            if (this.mCustomView != null)
            {
                onHideCustomView();
                return;
            }
            this.mCustomView = paramView;
            this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            this.mOriginalOrientation = getRequestedOrientation();
            this.mCustomViewCallback = paramCustomViewCallback;
            ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
            getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
}

In AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:configChanges="orientation|screenSize" />

Source Monster Techno

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

How to join entries in a set into one string?

', '.join(set_3)

The join is a string method, not a set method.

Disable Buttons in jQuery Mobile

UPDATE:

Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:

Updated Examples:

enable enable a disabled form button

$('[type="submit"]').button('enable');  

disable disable a form button

$('[type="submit"]').button('disable'); 

refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.

$('[type="submit"]').button('refresh');

Original Post Below:

Live Example: http://jsfiddle.net/XRjh2/2/

UPDATE:

Using @naugtur example below: http://jsfiddle.net/XRjh2/16/

UPDATE #2:

Link button example:

JS

var clicked = false;

$('#myButton').click(function() {
    if(clicked === false) {
        $(this).addClass('ui-disabled');
        clicked = true;
        alert('Button is now disabled');
    } 
});

$('#enableButton').click(function() {
    $('#myButton').removeClass('ui-disabled');
    clicked = false; 
});

HTML

<div data-role="page" id="home">
    <div data-role="content">

        <a href="#" data-role="button" id="myButton">Click button</a>
        <a href="#" data-role="button" id="enableButton">Enable button</a>

    </div>
</div>

NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html

Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.

How to convert a date to milliseconds

The SimpleDateFormat class allows you to parse a String into a java.util.Date object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime().

The full example:

String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();

Note that this gives you a long and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat class has tons on information on how to set it up to parse different formats.

Copy or rsync command

rsync is not necessarily more efficient, due to the more detailed inventory of files and blocks it performs. The algorithm is fantastic at what it does, but you need to understand your problem to know if it is really going to be the best choice.

On a very large file system (say many thousands or millions of files) where files tend to be added but not updated, "cp -u" will likely be more efficient. cp makes the decision to copy solely on metadata and can simply get to the business of copying.

Note that you might want some buffering, e.g. by using tar rather than straight cp, depending on the size of the files, network performance, other disk activity, etc. I find the following idea very useful:

tar cf - . | tar xCf directory -

Metadata itself may actually become a significant overhead on very large (cluster) file systems, but rsync and cp will share this problem.

rsync seems to frequently be the preferred tool (and in general purpose applications is my usual default choice), but there are probably many people who blindly use rsync without thinking it through.

mongodb service is not starting up

Fixed!

The reason was the dbpath variable in /etc/mongodb.conf. Previously, I was using mongodb 1.8, where the default value for dbpath was /data/db. The upstart job mongodb(which comes with mongodb-10gen package) invokes the mongod with --config /etc/mongodb.conf option.

As a solution, I only had to change the owner of the /data/db directory recursively.

How do I enable/disable log levels in Android?

May be you can see this Log extension class: https://github.com/dbauduin/Android-Tools/tree/master/logs.

It enables you to have a fine control on logs. You can for example disable all logs or just the logs of some packages or classes.

Moreover, it adds some useful functionalities (for instance you don't have to pass a tag for each log).

How do check if a PHP session is empty?

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )
    die( "Login required." );

(Assuming you want to check if someone is logged in)

Does Java have an exponential operator?

you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)

System.out.println(Math.pow(2, 3));

Error related to only_full_group_by when executing a query in MySql

I had to edit the below file on my Ubuntu 18.04:

/etc/mysql/mysql.conf.d/mysqld.cnf

with

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

and

sudo service mysql restart

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Button text toggle in jquery

You can use text method:

$(function(){
   $(".pushme").click(function () {
      $(this).text(function(i, text){
          return text === "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME";
      })
   });
})

http://jsfiddle.net/CBajb/

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

Reading a plain text file in Java

Guava provides a one-liner for this:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String contents = Files.toString(filePath, Charsets.UTF_8);

TypeScript: Creating an empty typed container array

Please try this which it works for me.

return [] as Criminal[];

How to get URL parameter using jQuery or plain JavaScript?

Best solution here.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

Deleting Elements in an Array if Element is a Certain value VBA

An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options

(A) Write a custom 'delete' function for your array like (untested)

Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(prLst)
            prLst(i - 1) = prLst(i)
        Next

        ' Shrink the array by one, removing the last one
        ReDim Preserve prLst(Len(prLst) - 1)
End Sub

(B) Simply set a 'dummy' value as the value instead of actually deleting the element

If prLst(eachHdr) = "0" Then        
   prLst(eachHdr) = "n/a"
End If

(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from

Dim prLst As New Collection

How do I get the logfile from an Android device?

Two steps:

  • Generate the log
  • Load Gmail to send the log

.

  1. Generate the log

    File generateLog() {
        File logFolder = new File(Environment.getExternalStorageDirectory(), "MyFolder");
        if (!logFolder.exists()) {
            logFolder.mkdir();
        }
        String filename = "myapp_log_" + new Date().getTime() + ".log";
    
        File logFile = new File(logFolder, filename);
    
        try {
            String[] cmd = new String[] { "logcat", "-f", logFile.getAbsolutePath(), "-v", "time", "ActivityManager:W", "myapp:D" };
            Runtime.getRuntime().exec(cmd);
            Toaster.shortDebug("Log generated to: " + filename);
            return logFile;
        }
        catch (IOException ioEx) {
            ioEx.printStackTrace();
        }
    
        return null;
    }
    
  2. Load Gmail to send the log

    File logFile = generateLog();
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile));
    intent.setType("multipart/");
    startActivity(intent);
    

References for #1

~~

For #2 - there are many different answers out there for how to load the log file to view and send. Finally, the solution here actually worked to both:

  • load Gmail as an option
  • attaches the file successfully

Big thanks to https://stackoverflow.com/a/22367055/2162226 for the correctly working answer

Table header to stay fixed at the top when user scrolls it out of view with jQuery

Well, I was trying to obtain the same effect without resorting to fixed size columns or having a fixed height for the entire table.

The solution I came up with is a hack. It consists of duplicating the entire table then hiding everything but the header, and making that have a fixed position.

HTML

<div id="table-container">
<table id="maintable">
    <thead>
        <tr>
            <th>Col1</th>
            <th>Col2</th>
            <th>Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>some really long line here instead</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
    </tbody>
</table>
<div id="bottom_anchor"></div>
</div>

CSS

body { height: 1000px; }
thead{
    background-color:white;
}

javascript

function moveScroll(){
    var scroll = $(window).scrollTop();
    var anchor_top = $("#maintable").offset().top;
    var anchor_bottom = $("#bottom_anchor").offset().top;
    if (scroll>anchor_top && scroll<anchor_bottom) {
    clone_table = $("#clone");
    if(clone_table.length == 0){
        clone_table = $("#maintable").clone();
        clone_table.attr('id', 'clone');
        clone_table.css({position:'fixed',
                 'pointer-events': 'none',
                 top:0});
        clone_table.width($("#maintable").width());
        $("#table-container").append(clone_table);
        $("#clone").css({visibility:'hidden'});
        $("#clone thead").css({'visibility':'visible','pointer-events':'auto'});
    }
    } else {
    $("#clone").remove();
    }
}
$(window).scroll(moveScroll); 

See here: http://jsfiddle.net/QHQGF/7/

Edit: updated the code so that the thead can receive pointer events(so buttons and links in the header still work). This fixes the problem reported by luhfluh and Joe M.

New jsfiddle here: http://jsfiddle.net/cjKEx/

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

AttributeError: 'module' object has no attribute 'model'

As the error message says in the last line: the module models in the file c:\projects\mysite..\mysite\polls\models.py contains no class model. This error occurs in the definition of the Poll class:

class Poll(models.model):

Either the class model is misspelled in the definition of the class Poll or it is misspelled in the module models. Another possibility is that it is completely missing from the module models. Maybe it is in another module or it is not yet implemented in models.

SQL Server datetime LIKE select?

You can use CONVERT to get the date in text form. If you convert it to a varchar(10), you can use = instead of like:

select *
from record
where CONVERT(VARCHAR(10),register_date,120) = '2009-10-10'

Or you can use an upper and lower boundary date, with the added advantage that it could make use of an index:

select *
from record
where '2009-10-10' <= register_date
and register_date < '2009-10-11'

SQL query, store result of SELECT in local variable

Isn't this a much simpler solution, if I correctly understand the question, of course.

I want to load email addresses that are in a table called "spam" into a variable.

select email from spam

produces the following list, say:

.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu

To load into the variable @list:

declare @list as varchar(8000)
set @list += @list (select email from spam)

@list may now be INSERTed into a table, etc.

I hope this helps.

To use it for a .csv file or in VB, spike the code:

declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list

and it produces ready-made code to use elsewhere:

".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"

One can be very creative.

Thanks

Nico

How can I install a previous version of Python 3 in macOS using homebrew?

The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/

There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.

To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.

What's the fastest way to loop through an array in JavaScript?

The absolute fastest way to loop through a javascript array is:

var len = arr.length;
while (len--) {
    // blah blah
}

See this post for a full comparison

Int to Decimal Conversion - Insert decimal point at specified location

Simple math.

double result = ((double)number) / 100.0;

Although you may want to use decimal rather than double: decimal vs double! - Which one should I use and when?

How can I return the difference between two lists?

You may call U.difference(lists) method in underscore-java library. I am the maintainer of the project. Live example

import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3);
        List<Integer> list2 = Arrays.asList(1, 2);
        List<Integer> list3 = U.difference(list1, list2);
        System.out.println(list3);
        // [3]
    }
}

Controller not a function, got undefined, while defining controllers globally

If all else fails and you are using Gulp or something similar...just rerun it!

I wasted 30mins quadruple checking everything when all it needed was a swift kick in the pants.

How do I unlock a SQLite database?

I found the documentation of the various states of locking in SQLite to be very helpful. Michael, if you can perform reads but can't perform writes to the database, that means that a process has gotten a RESERVED lock on your database but hasn't executed the write yet. If you're using SQLite3, there's a new lock called PENDING where no more processes are allowed to connect but existing connections can sill perform reads, so if this is the issue you should look at that instead.

How do I remove the height style from a DIV using jQuery?

$('div#someDiv').removeAttr("height");

Is it bad practice to use break to exit a loop in Java?

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.

Example

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

Edit in response to comment

Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.

Edit for the sake of completeness

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loop with a termination condition that looks like this:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

Android Studio - debug keystore

It is at the same location: ~/.android/debug.keystore

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

For Spring Boot RestTemplate:

  • add org.apache.httpcomponents.httpcore dependency
  • use NoopHostnameVerifier for SSL factory:

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new URL("file:pathToServerKeyStore"), storePassword)
    //        .loadKeyMaterial(new URL("file:pathToClientKeyStore"), storePassword, storePassword)
            .build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
    RestTemplate restTemplate = new RestTemplate(factory);
    

How to resolve /var/www copy/write permission denied?

Enter the following command in the directory you want to modify the right:

for example the directory: /var/www/html

sudo setfacl -m g:username:rwx . #-> for file

sudo setfacl -d -m g:username: rwx . #-> for directory

This will solve the problem.

Replace username with your username.

Error 500: Premature end of script headers

Error can be caused by various issues. for more info check suexec or fcgi logs. For example if suexec has wrong user and permssion it can cause the error to occur to solve try

chgrp WEBGROUP /usr/local/apache2/bin/suexec
chmod 4750 /usr/local/apache2/bin/suexec

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

How can I autoformat/indent C code in vim?

I find that clang-format works well.

There are some example keybindings in the clang documentation

I prefer to use the equalprg binding in vim. This allows you to invoke clang-format with G=gg or other = indent options.

Just put the following in your .vimrc file:

autocmd FileType c,cpp setlocal equalprg=clang-format

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

How to restore the permissions of files and directories within git if they have been modified?

Git keeps track of filepermission and exposes permission changes when creating patches using git diff -p. So all we need is:

  1. create a reverse patch
  2. include only the permission changes
  3. apply the patch to our working copy

As a one-liner:

git diff -p -R --no-ext-diff --no-color \
    | grep -E "^(diff|(old|new) mode)" --color=never  \
    | git apply

you can also add it as an alias to your git config...

git config --global --add alias.permission-reset '!git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never | git apply'

...and you can invoke it via:

git permission-reset

Note, if you shell is bash, make sure to use ' instead of " quotes around the !git, otherwise it gets substituted with the last git command you ran.

Thx to @Mixologic for pointing out that by simply using -R on git diff, the cumbersome sed command is no longer required.

bootstrap popover not showing on top of all elements

When you have some styles on a parent element that interfere with a popover, you’ll want to specify a custom container so that the popover’s HTML appears within that element instead.

For instance say the parent for a popover is body then you can use.

    <a href="#" data-toggle="tooltip" data-container="body"> Popover One </a>

Other case might be when popover is placed inside some other element and you want to show popover over that element, then you'll need to specify that element in data-container. ex: Suppose, we have popover inside a bootstrap modal with id as 'modal-two', then you'll need to set 'data-container' to 'modal-two'.

    <a href="#" data-toggle="tooltip" data-container="#modal-two"> Popover Two </a>

Notepad++ Setting for Disabling Auto-open Previous Files

In Notepad++ v6.6 this setting is moved to the Backup tab of the Preferences menu.

enter image description here

MySQL Data Source not appearing in Visual Studio

Tried everything but on Visual Studio 2015 Community edition I got it working when I installed MySQL for Visual Studio 1.2.4+ from http://dev.mysql.com/downloads/windows/visualstudio/ At time of writing I could download 1.2.6 which worked for me.

enter image description here

Release notes of 1.2.4 which adds support for VS2015 can be found at http://forums.mysql.com/read.php?3,633391

List files ONLY in the current directory

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

files = os.listdir(os.curdir)  #files and directories

or

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

Getting only Month and Year from SQL DATE

Try this

select to_char(DATEFIELD,'MON') from YOUR_TABLE

eg.

select to_char(sysdate, 'MON') from dual

INSERT VALUES WHERE NOT EXISTS

More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.

They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.

The example code used for each technique is as follows (straight copy/paste from their page) :

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.

How to change shape color dynamically?

This works for me, with an initial xml resource:

example.setBackgroundResource(R.drawable.myshape);
GradientDrawable gd = (GradientDrawable) example.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000"));
gd.setCornerRadii(new float[]{30, 30, 30, 30, 0, 0, 30, 30});
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

Result of the above: http://i.stack.imgur.com/hKUR7.png

How to compare strings in an "if" statement?

if(!strcmp(favoriteDairyProduct, "cheese"))
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}

How to watch and compile all TypeScript sources?

Look into using grunt to automate this, there are numerous tutorials around, but here's a quick start.

For a folder structure like:

blah/
blah/one.ts
blah/two.ts
blah/example/
blah/example/example.ts
blah/example/package.json
blah/example/Gruntfile.js
blah/example/index.html

You can watch and work with typescript easily from the example folder with:

npm install
grunt

With package.json:

{
  "name": "PROJECT",
  "version": "0.0.1",
  "author": "",
  "description": "",
  "homepage": "",
  "private": true,
  "devDependencies": {
    "typescript": "~0.9.5",
    "connect": "~2.12.0",
    "grunt-ts": "~1.6.4",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-contrib-connect": "~0.6.0",
    "grunt-open": "~0.2.3"
  }
}

And a grunt file:

module.exports = function (grunt) {

  // Import dependencies
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-open');
  grunt.loadNpmTasks('grunt-ts');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {  // <--- Run a local server on :8089
        options: {
          port: 8089,
          base: './'
        }
      }
    },
    ts: {
      lib: { // <-- compile all the files in ../ to PROJECT.js
        src: ['../*.ts'],
        out: 'PROJECT.js',
        options: {
          target: 'es3',
          sourceMaps: false,
          declaration: true,
          removeComments: false
        }
      },
      example: {  // <--- compile all the files in . to example.js
        src: ['*.ts'],
        out: 'example.js',
        options: {
          target: 'es3',
          sourceMaps: false,
          declaration: false,
          removeComments: false
        }
      }
    },
    watch: { 
      lib: { // <-- Watch for changes on the library and rebuild both
        files: '../*.ts',
        tasks: ['ts:lib', 'ts:example']
      },
      example: { // <--- Watch for change on example and rebuild
        files: ['*.ts', '!*.d.ts'],
        tasks: ['ts:example']
      }
    },
    open: { // <--- Launch index.html in browser when you run grunt
      dev: {
        path: 'http://localhost:8089/index.html'
      }
    }
  });

  // Register the default tasks to run when you run grunt
  grunt.registerTask('default', ['ts', 'connect', 'open', 'watch']);
}

Connect to mysql on Amazon EC2 from a remote server

I went through all the previous answers (and answers to similar questions) without success, so here is what finally worked for me. The key step was to explicitly grant privileges on the mysql server to a local user (for the server), but with my local IP appended to it (myuser@*.*.*.*). The complete step by step solution is as follows:

  1. Comment out the bind_address line in /etc/mysql/my.cnf at the server (i.e. the EC2 Instance). I suppose bind_address=0.0.0.0 would also work, but it's not needed as others have mentioned.

  2. Add a rule (as others have mentioned too) for MYSQL to the EC2 instance's security group with port 3306 and either My IP or Anywhere as Source. Both work fine after following all the steps.

  3. Create a new user myuser with limited privileges to one particular database mydb (basically following the instructions in this Amazon tutorial):

    $EC2prompt> mysql -u root -p
    [...omitted output...]
    mysql>  CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'your_strong_password';
    mysql>  GRANT ALL PRIVILEGES ON 'mydb'.* TO 'myuser'@'localhost';`
    
  4. Here's the key step, without which my local address was refused when attempting a remote connection (ERROR 1130 (HY000): Host '*.*.*.23' is not allowed to connect to this MySQL server):

    mysql> GRANT ALL PRIVILEGES ON 'mydb'.* TO 'myuser'@'*.*.*.23';
    mysql> FLUSH PRIVILEGES;`
    

    (replace '*.*.*.23' by your local IP address)

  5. For good measure, I exited mysql to the shell and restarted the msyql server:

    $EC2prompt> sudo service mysql restart

  6. After these steps, I was able to happily connect from my computer with:

    $localprompt> mysql -h myinstancename.amazonaws.com -P 3306 -u myuser -p

    (replace myinstancename.amazonaws.com by the public address of your EC2 instance)

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

Updating Anaconda fails: Environment Not Writable Error

this line of code on your terminal, solves the problem

$ sudo chown -R $USER:$USER anaconda 3

web-api POST body object always null

This is another issue related to invalid property values in an Angular Typescript request.

This is was related to the conversion between a Typescript number to an int(Int32) in C#. I was using Ticks (UTC milliseconds) which is larger than the signed, Int32 range (int in C#). Changed the C# model from int to long and everything worked fine.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

Node.js: socket.io close client connection

Just try socket.disconnect(true) on the server side by emitting any event from the client side.

What are .tpl files? PHP, web design

In this specific case it is Smarty, but it could also be Jinja2 templates. They usually also have a .tpl extension.

Duplicate and rename Xcode project & associated folders

This answer is the culmination of various other StackOverflow posts and tutorials around the internet brought into one place for my future reference, and to help anyone else who may be facing the same issue. All credit is given for other answers at the end.

Duplicating an Xcode Project

  • In the Finder, duplicate the project folder to the desired location of your new project. Do not rename the .xcodeproj file name or any associated folders at this stage.

  • In Xcode, rename the project. Select your project from the navigator pane (left pane). In the Utilities pane (right pane) rename your project, Accept the changes Xcode proposes.

  • In Xcode, rename the schemes in "Manage Schemes", also rename any targets you may have.

  • If you're not using the default Bundle Identifier which contains the current PRODUCT_NAME at the end (so will update automatically), then change your Bundle Identifier to the new one you will be using for your duplicated project.

Renaming the source folder

So after following the above steps you should have a duplicated and renamed Xcode project that should build and compile successfully, however your source code folder will still be named as it was in the original project. This doesn't cause any compiler issues, but it's not the clearest file structure for people to navigate in SCM, etc. To rename this folder without breaking all your file links, follow these steps:

  • In the Finder, rename the source folder. This will break your project, because Xcode won't automatically detect the changes. All of your xcode file listings will lose their links with the actual files, so will all turn red.

  • In Xcode, click on the virtual folder which you renamed (This will likely be right at the top, just under your actual .xcodeproject) Rename this to match the name in the Finder, this won't fix anything and strictly isn't a required step but it's nice to have the file names matching.

  • In Xcode, Select the folder you just renamed in the navigation pane. Then in the Utilities pane (far right) click the icon that looks like dark grey folder, just underneath the 'Location' drop down menu. From here, navigate to your renamed folder in the finder and click 'Choose'. This will automagically re-associate all your files, and they should no longer appear red within the Xcode navigation pane.

Icon to click

  • In your project / targets build settings, search for the old folder name and manually rename any occurrences you find. Normally there is one for the prefix.pch and one for the info.plist, but there may be more.

  • If you are using any third party libraries (Testflight/Hockeyapp/etc) you will also need to search for 'Library Search Paths' and rename any occurrences of the old file name here too.

  • Repeat this process for any unit test source code folders your project may contain, the process is identical.

This should allow you to duplicate & rename an xcode project and all associated files without having to manually edit any xcode files, and risk messing things up.

Credits

Many thanks is given to Nick Lockwood, and Pauly Glott for providing the separate answers to this problem.

Android: Expand/collapse animation

If you don't want to expand or collapse all the way - here is a simple HeightAnimation -

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

Usage:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

How to iterate through LinkedHashMap with lists as values

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.

get the selected index value of <select> tag in php

As you said..

$Gender  = isset($_POST["gender"]); ' it returns a empty string 

because, you haven't mention method type either use POST or GET, by default it will use GET method. On the other side, you are trying to retrieve your value by using POST method, but in the form you haven't mentioned POST method. Which means miss-match method will result for empty.

Try this code..

<form name="signup_form"  action="./signup.php" onsubmit="return validateForm()"   method="post">
<table> 
  <tr> <td> First Name    </td><td> <input type="text" name="fname" size=10/></td></tr>
  <tr> <td> Last Name     </td><td> <input type="text" name="lname" size=10/></td></tr>
  <tr> <td> Your Email    </td><td> <input type="text" name="email" size=10/></td></tr>
  <tr> <td> Re-type Email </td><td> <input type="text" name="remail"size=10/></td></tr>
  <tr> <td> Password      </td><td> <input type="password" name="paswod" size=10/> </td></tr>
  <tr> <td> Gender        </td><td> <select name="gender">
  <option value="select">                Select </option>    
  <option value="male">   Male   </option>
  <option value="female"> Female </option></select></td></tr> 
  <tr> <td> <input type="submit" value="Sign up" id="signup"/> </td> </tr>
 </table>
 </form>

and on signup page

$Gender  = $_POST["gender"];

i'm sure.. now, you will get the value..

How to find a text inside SQL Server procedures / triggers?

I use this one for work. leave off the []'s though in the @TEXT field, seems to want to return everything...

SET NOCOUNT ON

DECLARE @TEXT   VARCHAR(250)
DECLARE @SQL    VARCHAR(250)

SELECT  @TEXT='10.10.100.50'

CREATE TABLE #results (db VARCHAR(64), objectname VARCHAR(100),xtype VARCHAR(10), definition TEXT)

SELECT @TEXT as 'Search String'
DECLARE #databases CURSOR FOR SELECT NAME FROM master..sysdatabases where dbid>4
    DECLARE @c_dbname varchar(64)   
    OPEN #databases
    FETCH #databases INTO @c_dbname   
    WHILE @@FETCH_STATUS  -1
    BEGIN
        SELECT @SQL = 'INSERT INTO #results '
        SELECT @SQL = @SQL + 'SELECT ''' + @c_dbname + ''' AS db, o.name,o.xtype,m.definition '   
        SELECT @SQL = @SQL + ' FROM '+@c_dbname+'.sys.sql_modules m '   
        SELECT @SQL = @SQL + ' INNER JOIN '+@c_dbname+'..sysobjects o ON m.object_id=o.id'   
        SELECT @SQL = @SQL + ' WHERE [definition] LIKE ''%'+@TEXT+'%'''   
        EXEC(@SQL)
        FETCH #databases INTO @c_dbname
    END
    CLOSE #databases
DEALLOCATE #databases

SELECT * FROM #results order by db, xtype, objectname
DROP TABLE #results

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

How to check if a specified key exists in a given S3 bucket using Java

Using Object isting. Java function to check if specified key exist in AWS S3.

boolean isExist(String key)
    {
        ObjectListing objects = amazonS3.listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix(key));

        for (S3ObjectSummary objectSummary : objects.getObjectSummaries())
        {
            if (objectSummary.getKey().equals(key))
            {
                return true;
            }

        }
        return false;
    }

How do I install Keras and Theano in Anaconda Python on Windows?

It is my solution for the same problem

  • Install TDM GCC x64.
  • Install Anaconda x64.
  • Open the Anaconda prompt
  • Run conda update conda
  • Run conda update --all
  • Run conda install mingw libpython
  • Install the latest version of Theano, pip install git+git://github.com/Theano/Theano.git
  • Run pip install git+git://github.com/fchollet/keras.git

Remove all occurrences of char from string

If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.

StringUtils.remove("TextX Xto modifyX", 'X');

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

Searching a string in eclipse workspace

A lot of answers only explain how to do the search.

To view the results look for a search tab (normally docked at the bottom of the screen):

How to define a connection string to a SQL Server 2008 database?

Instead of writing it in your code directly I suggest you make use of the dedicated <connectionStrings> element in the .config file and retrieve it from there.

Also make use of the using statement so that after usage your connection automatically gets closed and disposed of.

A great reference for finding connection strings: connectionstrings.com/sql-server-2008.

Java Constructor Inheritance

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.
  public Son(){
    // If you dont call any other constructor in the first line a call to super() will be placed instead.
    super();
  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

How to Navigate from one View Controller to another using Swift

In swift 3

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController        
self.navigationController?.pushViewController(nextVC, animated: true)

jquery - return value using ajax result on success

With Help from here

function get_result(some_value) {
   var ret_val = {};
   $.ajax({
       url: '/some/url/to/fetch/from',
       type: 'GET',
       data: {'some_key': some_value},
       async: false,
       dataType: 'json'
   }).done(function (response) {
       ret_val = response;
   }).fail(function (jqXHR, textStatus, errorThrown) {
           ret_val = null;
       });
   return ret_val;
}

Hope this helps someone somewhere a bit.

Android ListView not refreshing after notifyDataSetChanged

You are assigning reloaded items to global variable items in onResume(), but this will not reflect in ItemAdapter class, because it has its own instance variable called 'items'.

For refreshing ListView, add a refresh() in ItemAdapter class which accepts list data i.e items

class ItemAdapter
{
    .....

    public void refresh(List<Item> items)
    {
        this.items = items;
        notifyDataSetChanged();
    } 
}

update onResume() with following code

@Override
public void onResume()
{
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); //reload the items from database
    **adapter.refresh(items);**
}

Rails Object to hash

There are some great suggestions here.

I think it's worth noting that you can treat an ActiveRecord model as a hash like so:

@customer = Customer.new( name: "John Jacob" )
@customer.name    # => "John Jacob"
@customer[:name]  # => "John Jacob"
@customer['name'] # => "John Jacob"

Therefore, instead of generating a hash of the attributes, you can use the object itself as a hash.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

How to allow Cross domain request in apache2

OS=GNU/Linux Debian
Httpd=Apache/2.4.10

Change in /etc/apache2/apache2.conf

<Directory /var/www/html>
     Order Allow,Deny
     Allow from all
     AllowOverride all
     Header set Access-Control-Allow-Origin "*"
</Directory>

Add/activate module

 a2enmod headers 

Restart service

/etc/init.d/apache2 restart

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

Determining if an Object is of primitive type

public class CheckPrimitve {
    public static void main(String[] args) {
        int i = 3;
        Object o = i;
        System.out.println(o.getClass().getSimpleName().equals("Integer"));
        Field[] fields = o.getClass().getFields();
        for(Field field:fields) {
            System.out.println(field.getType());
        }
    }
}  

Output:
true
int
int
class java.lang.Class
int

Locking a file in Python

To add on to Evan Fossmark's answer, here's an example of how to use filelock:

from filelock import FileLock

lockfile = r"c:\scr.txt"
lock = FileLock(lockfile + ".lock")
with lock:
    file = open(path, "w")
    file.write("123")
    file.close()

Any code within the with lock: block is thread-safe, meaning that it will be finished before another process has access to the file.

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

Using PHP Replace SPACES in URLS with %20

I think you must use rawurlencode() instead urlencode() for your purpose.

sample

$image = 'some images.jpg';
$url   = 'http://example.com/'

With urlencode($str) will result

echo $url.urlencode($image); //http://example.com/some+images.jpg

its not change to %20 at all

but with rawurlencode($image) will produce

echo $url.rawurlencode(basename($image)); //http://example.com/some%20images.jpg

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.

Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.

Reload child component when variables on parent component changes. Angular2

On Angular to update a component including its template, there is a straight forward solution to this, having an @Input property on your ChildComponent and add to your @Component decorator changeDetection: ChangeDetectionStrategy.OnPush as follows:

import { ChangeDetectionStrategy } from '@angular/core';

@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1],
    changeDetection: ChangeDetectionStrategy.OnPush    
})

export class ChildComponent{
  @Input() data: MyData;
}

This will do all the work of check if Input data have changed and re-render the component

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I was also having the same problem. I tried the following and it's working for me now:
Please try the following steps:

Go to..

File > Settings > Appearance & Behavior > System Settings > HTTP Proxy [Under IDE Settings] Enable following option Auto-detect proxy settings

On Mac it's under:

Android Studio > Preferences > Appearance & Behaviour... etc

you can also use the test connection button and check with google.com to see if it works or not.

Jquery DatePicker Set default date

use defaultDate()

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current [[UI/Datepicker#option-dateFormat|dateFormat]], or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

try this

$("[name=trainingStartFromDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: new Date()});
$("[name=trainingStartToDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: +15}); 

How to read a CSV file from a URL with Python?

You need to replace open with urllib.urlopen or urllib2.urlopen.

e.g.

import csv
import urllib2

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
    print row

This would output the following

Year,City,Sport,Discipline,NOC,Event,Event gender,Medal
1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver
1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold
...

The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) see below.

Best way to check if object exists in Entity Framework?

From a performance point of view, I guess that a direct SQL query using the EXISTS command would be appropriate. See here for how to execute SQL directly in Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

How to copy sheets to another workbook using vba?

Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:

Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False

Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String

numSheets = 0

For Each ws In Application.ActiveWorkbook.Worksheets
    If ws.Name <> "Sheet1" Then
       Sheets.Add.Name = "Sheet1"
   End If
Next

Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String

fileExplorer.AllowMultiSelect = False

  With fileExplorer
     If .Show = -1 Then 'Any file is selected
     MyString = .SelectedItems.Item(1)

     Else ' else dialog is cancelled
        MsgBox "You have cancelled the dialogue"
        [filePath] = "" ' when cancelled set blank as file path.
        End If
    End With

    LString = Range("A1").Value
    dashpos = InStr(1, LString, "\") + 1
    LArray = Split(LString, "\")
    'MsgBox LArray(dashpos - 1)
    FileName = LArray(dashpos)

strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & FileName

Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count

        For x = 1 To numSheets
            closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
        x = x + 1
                 If x = numSheets Then
                    GoTo 1000
                 End If
Next

1000

closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True

End Sub

Key value pairs using JSON

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:

{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}

Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Beyond making clean up easy with stack-based objects, RAII is also useful because the same 'automatic' clean up occurs when the object is a member of another class. When the owning class is destructed, the resource managed by the RAII class gets cleaned up because the dtor for that class gets called as a result.

This means that when you reach RAII nirvana and all members in a class use RAII (like smart pointers), you can get away with a very simple (maybe even default) dtor for the owner class since it doesn't need to manually manage its member resource lifetimes.

python xlrd unsupported format, or corrupt file.

Open in google sheets and then download from sheets as CSV and then reupload to drive. Then you can Open CSV file from python.

How to setup Main class in manifest file in jar produced by NetBeans project

I read and read and read to figure out why I was getting a class not found error, it turns out the manifest.mf had an error in the line:

Main-Class: com.example.MainClass

I fixed the error by going to Project Properties dialog (right-click Project Files), then Run and Main Class and corrected whatever Netbeans decided to put here. Netbean inserted the project name instead of the class name. No idea why. Probably inebriated on muratina...

Populating spinner directly in the layout xml

In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!

Example -Before :

<string-array name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Example - After:

<string-array android:name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

@angular/material/index.d.ts' is not a module

First try to downgrade your angular version using "ng add @angular/material7.3..0" after that check if the error is gone in my case it is gone after that use this ng update @angular/material in case you are using angular 9 or 10 you have to write code like this import {MatInputModule} from 'angular/material/input' Hope it will work for you

How do I see if Wi-Fi is connected on Android?

Add this for JAVA:

public boolean CheckWifiConnection() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }

in Manifest file add the following permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Downloading all maven dependencies to a directory NOT in repository?

Please check if you have some config files in ${MAVEN_HOME}/conf directory like settings.xml. Those files overrides settings from .m2 folder and because of that, repository folder from .m2 might not be visible or discarded.

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

Difference between Activity Context and Application Context

This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context. In the second place, the doc should specify which context to use or not explicitly.

Create whole path automatically when writing to a new file

Use File.mkdirs():

File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);

How do I get the parent directory in Python?

>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))

For example in Ubuntu:

>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'

For example in Windows:

>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'

Both examples tried in Python 2.7

Java generics - ArrayList initialization

You can't assign a List<Number> to a reference of type List<Integer> because List<Number> allows types of numbers other than Integer. If you were allowed to do that, the following would be allowed:

List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!

The type List<Integer> is making a guarantee that anything it contains will be an Integer. That's why you're allowed to get an Integer out of it without casting. As you can see, if the compiler allowed a List of another type such as Number to be assigned to a List<Integer> that guarantee would be broken.

Assigning a List<Integer> to a reference of a type such as List<?> or List<? extends Number> is legal because the ? means "some unknown subtype of the given type" (where the type is Object in the case of just ? and Number in the case of ? extends Number).

Since ? indicates that you do not know what specific type of object the List will accept, it isn't legal to add anything but null to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X bounded wildcard type. Note that the opposite is true for a ? super X bounded wildcard type... a List<? super Integer> is "a list of some unknown type that is at least a supertype of Integer". While you don't know exactly what type of List it is (could be List<Integer>, List<Number>, List<Object>) you do know for sure that whatever it is, an Integer can be added to it.

Finally, new ArrayList<?>() isn't legal because when you're creating an instance of a paramterized class like ArrayList, you have to give a specific type parameter. You could really use whatever in your example (Object, Foo, it doesn't matter) since you'll never be able to add anything but null to it since you're assigning it directly to an ArrayList<?> reference.

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

C++ terminate called without an active exception

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.

How to enable CORS in flask

I've just faced the same issue and I came to believe that the other answers are a bit more complicated than they need to be, so here's my approach for those who don't want to rely on more libraries or decorators:

A CORS request actually consists of two HTTP requests. A preflight request and then an actual request that is only made if the preflight passes successfully.

The preflight request

Before the actual cross domain POST request, the browser will issue an OPTIONS request. This response should not return any body, but only some reassuring headers telling the browser that it's alright to do this cross-domain request and it's not part of some cross site scripting attack.

I wrote a Python function to build this response using the make_response function from the flask module.

def _build_cors_prelight_response():
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "*")
    response.headers.add("Access-Control-Allow-Methods", "*")
    return response

This response is a wildcard one that works for all requests. If you want the additional security gained by CORS, you have to provide a whitelist of origins, headers and methods.

This response will convince your (Chrome) browser to go ahead and do the actual request.

The actual request

When serving the actual request you have to add one CORS header - otherwise the browser won't return the response to the invoking JavaScript code. Instead the request will fail on the client-side. Example with jsonify

response = jsonify({"order_id": 123, "status": "shipped"}
response.headers.add("Access-Control-Allow-Origin", "*")
return response

I also wrote a function for that.

def _corsify_actual_response(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

allowing you to return a one-liner.

Final code

from flask import Flask, request, jsonify, make_response
from models import OrderModel

flask_app = Flask(__name__)

@flask_app.route("/api/orders", methods=["POST", "OPTIONS"])
def api_create_order():
    if request.method == "OPTIONS": # CORS preflight
        return _build_cors_prelight_response()
    elif request.method == "POST": # The actual request following the preflight
        order = OrderModel.create(...) # Whatever.
        return _corsify_actual_response(jsonify(order.to_dict()))
    else
        raise RuntimeError("Weird - don't know how to handle method {}".format(request.method))

def _build_cors_prelight_response():
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add('Access-Control-Allow-Headers', "*")
    response.headers.add('Access-Control-Allow-Methods', "*")
    return response

def _corsify_actual_response(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

Remove a character at a certain position in a string - javascript

It depends how easy you find the following, which uses simple String methods (in this case slice()).

_x000D_
_x000D_
var str = "Hello World";_x000D_
str = str.slice(0, 3) + str.slice(4);_x000D_
console.log(str)
_x000D_
_x000D_
_x000D_

How to dynamically add and remove form fields in Angular 2

That is the HTML code. Anyone can use this:

<div class="card-header">Contact Information</div>
          <div class="card-body" formArrayName="funds">
            <div class="row">
              <div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="row">
                  <div class="form-group col-6">
                    <label>Type of Contact</label>
                    <select class="form-control" formControlName="fundName" type="text">
                      <option value="01">Balance Fund</option>
                      <option value="02">Equity Fund</option>
                    </select> 
                  </div>
                  <div class="form-group col-12">
                    <label>Allocation</label>
                    <input class="form-control" formControlName="allocation" type="number">
                    <span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched && 
                    getContactsFormGroup(i).controls['allocation'].hasError('required')">
                        Allocation % is required! </span>
                  </div>
                  <div class="form-group col-12 text-right">
                    <button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>

jQuery click function doesn't work after ajax call?

I tested a simple solution that works for me! My javascript was in a js separate file. What I did is that I placed the javascript for the new element into the html that was loaded with ajax, and it works fine for me! This is for those having big files of javascript!!

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Find nginx version?

It seems that your nginx hasn't been installed correctly. Pay attention to the output of the installation commands:

sudo apt-get install nginx

To check the nginx version, you can use this command:

$ nginx -v
nginx version: nginx/0.8.54

$ nginx -V
nginx version: nginx/0.8.54
TLS SNI support enabled
configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module --add-module=/build/buildd/nginx-0.8.54/debian/modules/nginx-upstream-fair

For more information: http://nginxlibrary.com/check-nginx-version/

You can use -v parameter to display the Nginx version only, or use the -V parameter to display the version, along with the compiler version and configuration parameters.

IndentationError expected an indented block

You've mixed tabs and spaces. This can lead to some confusing errors.

I'd suggest using only tabs or only spaces for indentation.

Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.


As an aside, your code is more verbose than it needs to be. Instead of this:

if str_p == str_q:
    result = True
else:
    result = False
return result

Just do this:

return str_p == str_q

You also appear to have a bug on this line:

str_q = p[b+1:]

I'll leave you to figure out what the error is.

How do I get the file name from a String containing the Absolute file path?

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

HTML table with 100% width, with vertical scroll inside tbody

Try this jsfiddle. This is using jQuery and made from Hashem Qolami's answer. At first, make a regular table then make it scrollable.

const makeScrollableTable = function (tableSelector, tbodyHeight) {
  let $table = $(tableSelector);
  let $bodyCells = $table.find('tbody tr:first').children();
  let $headCells = $table.find('thead tr:first').children();
  let headColWidth = 0;
  let bodyColWidth = 0;
  
  headColWidth = $headCells.map(function () {
    return $(this).outerWidth();
  }).get();
  bodyColWidth = $bodyCells.map(function () {
    return $(this).outerWidth();
  }).get();

  $table.find('thead tr').children().each(function (i, v) {
    $(v).css("width", headColWidth[i]+"px");
    $(v).css("min-width", headColWidth[i]+"px");
    $(v).css("max-width", headColWidth[i]+"px");
  });
  $table.find('tbody tr').children().each(function (i, v) {
    $(v).css("width", bodyColWidth[i]+"px");
    $(v).css("min-width", bodyColWidth[i]+"px");
    $(v).css("max-width", bodyColWidth[i]+"px");
  });

  $table.find('thead').css("display", "block");
  $table.find('tbody').css("display", "block");

  $table.find('tbody').css("height", tbodyHeight+"px");
  $table.find('tbody').css("overflow-y", "auto");
  $table.find('tbody').css("overflow-x", "hidden");
  
};

Then you can use this function as follows:

makeScrollableTable('#test-table', 250);

How to play videos in android from assets folder or raw folder?

Try:

AssetFileDescriptor afd = getAssets().openFd(fileName);
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());

Can you target an elements parent element using event.target?

To use the parent of an element use parentElement:

function selectedProduct(event){
  var target = event.target;
  var parent = target.parentElement;//parent of "target"
}

Difference between Hashing a Password and Encrypting it

Hashing is a one-way function, meaning that once you hash a password it is very difficult to get the original password back from the hash. Encryption is a two-way function, where it's much easier to get the original text back from the encrypted text.

Plain hashing is easily defeated using a dictionary attack, where an attacker just pre-hashes every word in a dictionary (or every combination of characters up to a certain length), then uses this new dictionary to look up hashed passwords. Using a unique random salt for each hashed password stored makes it much more difficult for an attacker to use this method. They would basically need to create a new unique dictionary for every salt value that you use, slowing down their attack terribly.

It's unsafe to store passwords using an encryption algorithm because if it's easier for the user or the administrator to get the original password back from the encrypted text, it's also easier for an attacker to do the same.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

This problem can be easily solved by installing the following Individual components:

enter image description here

How do I clone a range of array elements to a new array?

Array.ConstrainedCopy will work.

public static void ConstrainedCopy (
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length
)

Accessing localhost of PC from USB connected Android mobile device

I did this on a windows computer and it worked perfectly!

Turn on USB Tethering in your mobile. Type ipconfig in the command prompt in your computer and find the ipv4 for "ethernet adapter local area connection x" (mostly the first one) Now go to your mobile browser, type that ipv4 with the port number of your web application. eg:- 192.168.40.142:1342

It worked with those simple steps!

Unable to begin a distributed transaction

I was able to resolve this issue (as others mentioned in comments) by disabling "Enable Promotion of Distributed Transactions for RPC" (i.e. setting it to False):

enter image description here

As requested by @WonderWorker, you can do this via SQL script:

EXEC master.dbo.sp_serveroption
     @server = N'[mylinkedserver]',
     @optname = N'remote proc transaction promotion',
     @optvalue = N'false'

How to print a specific row of a pandas DataFrame?

Use ix operator:

print df.ix[159220]

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

Logcat not displaying my log calls

Best solution for me was restart adb server (while I have Enabled ADB integration in Android studio - Tools - Android - checked). To do this quickly I created adbr.bat file inside android-sdk\platform-tools directory (where is adb.exe located) with this inside:

adb kill-server
adb start-server

Because I have this folder in PATH system variable, always when I need restart adb from Android studio, I can write only into terminal adbr and it is done.

Another option to do this is through Android Device Monitor in Devices tab - Menu after click on small arrow right - Reset adb.

How do I get the HTTP status code with jQuery?

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

How do I find out my MySQL URL, host, port and username?

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

AngularJS dynamic routing

Ok solved it.

Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting

In my app.js routing config:

$routeProvider.when('/pages/:name', {
    templateUrl: '/pages/home.html', 
    controller: CMSController 
});

Then in my CMS controller:

function CMSController($scope, $route, $routeParams) {

    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";

    $.get($route.current.templateUrl, function (data) {
        $scope.$apply(function () {
            $('#views').html($compile(data)($scope));
        });
    });
    ...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];

With #views being my <div id="views" ng-view></div>

So now it works with standard routing and dynamic routing.

To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio into my browser and hey presto portfolio.html was displayed....

Updated Added $apply and $compile to the html so that dynamic content can be injected.

Regular expression that matches valid IPv6 addresses

InetAddressUtils has all the patterns defined. I ended-up using their pattern directly, and am pasting it here for reference:

private static final String IPV4_BASIC_PATTERN_STRING =
        "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
         "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255

private static final Pattern IPV4_PATTERN =
    Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");

private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros
        Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$");

private static final Pattern IPV6_STD_PATTERN =
    Pattern.compile(
            "^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$");

private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
    Pattern.compile(
            "^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields
             "::" +
             "(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields 

Flatten an irregular list of lists

def nested_list(depth):
    l = [depth]
    for i in range(depth-1, 0, -1):
        l = [i, l]
    return l

nested_list(10)

[1, [2, [3, [4, [5, [6, [7, [8, [9, [10]]]]]]]]]]

def Flatten(ul):
    fl = []
    for i in ul:
        if type(i) is list:
            fl += Flatten(i)
        else:
            fl += [i]
    return fl

Flatten(nested_list(10))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Benchmarking

l = nested_list(100)

https://stackoverflow.com/a/2158532

import collections

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el
%%timeit -n 1000
list(flatten(l))

320 µs ± 14.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit -n 1000
Flatten(l)

60 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

list(flatten(l)) == Flatten(l)

True

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

Installing libffi-dev and re-installing python3.7 fixed the problem for me.

to cleanly build py 3.7 libffi-dev is required or else later stuff will fail

If using RHEL/Fedora:

yum install libffi-devel

or

sudo dnf install libffi-devel

If using Debian/Ubuntu:

sudo apt-get install libffi-dev

How can I mix LaTeX in with Markdown?

Perhaps mathJAX is the ticket. It's built on jsMath, a 2004 vintage JavaScript library.

As of 5-Feb-2015 I'd switch to recommend KaTeX - most performant Javascript LaTeX library from Khan Academy.

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

Forbidden You don't have permission to access /wp-login.php on this server

This should work :

The instructions says that you add a separate .htaccess containing the lines above to the wp-admin folder - and leave the main .htaccess, in the root, alone.

if that don't help , you can try this:

copy the .htaccess file as is from the wp-admin and placed it in the root folder and bingo! It should work ! if you face new error after this let us know.

for reference you can look here as well:

http://wordpress.org/support/topic/you-dont-have-permission-to-access-blogwp-loginphp-on-this-server

Check using this:

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

Adding a month to a date in T SQL

select * from Reference where reference_dt = DATEADD(mm, 1, reference_dt)