Programs & Examples On #Hcluster

z-index not working with position absolute

The second div is position: static (the default) so the z-index does not apply to it.

You need to position (set the position property to anything other than static, you probably want relative in this case) anything you want to give a z-index to.

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

text-align: right; not working for <label>

As stated in other answers, label is an inline element. However, you can apply display: inline-block to the label and then center with text-align.

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;
}

Why display: inline-block and not display: inline? For the same reason that you can't align label, it's inline.

Why display: inline-block and not display: block? You could use display: block, but it will be on another line. display: inline-block combines the properties of inline and block. It's inline, but you can also give it a width, height, and align it.

Sort array of objects by single key with date value

  • Use Array.sort() to sort an array
  • Clone array using spread operator () to make the function pure
  • Sort by desired key (updated_at)
  • Convert date string to date object
  • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations
const input = [
  {
    updated_at: '2012-01-01T06:25:24Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-09T11:25:13Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-05T04:13:24Z',
    foo: 'bar',
  }
];

const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
{
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}

or you can also use SqlQuery

using (var entity = new FunctionsContext())
{
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5
            };

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

While loop in batch

A while loop can be simulated in cmd.exe with:

:still_more_files
    if %countfiles% leq 21 (
        rem change countfile here
        goto :still_more_files
    )

For example, the following script:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set /a "x = 0"

:more_to_process
    if %x% leq 5 (
        echo %x%
        set /a "x = x + 1"
        goto :more_to_process
    )

    endlocal

outputs:

0
1
2
3
4
5

For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:

    @echo off
    set backupdir=c:\test

:more_files_to_process
    for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
    if %num% gtr 20 (
        cscript /nologo c:\deletefile.vbs %backupdir%
        goto :more_files_to_process
    )

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Try this:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Or this:

yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 

How can I use pickle to save a dict?

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normally it's preferable to use the cPickle implementation

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

UIDevice uniqueIdentifier deprecated - What to do now?

You may want to consider using OpenUDID which is a drop-in replacement for the deprecated UDID.

Basically, to match the UDID, the following features are required:

  1. unique or sufficiently unique (a low probability collision is probably very acceptable)
  2. persistence across reboots, restores, uninstalls
  3. available across apps of different vendors (useful to acquire users via CPI networks) -

OpenUDID fulfills the above and even has a built-in Opt-Out mechanism for later consideration.

Check http://OpenUDID.org it points to the corresponding GitHub. Hope this helps!

As a side note, I would shy away from any MAC address alternative. While the MAC address appears like a tempting and universal solution, be sure that this low hanging fruit is poisoned. The MAC address is very sensitive, and Apple may very well deprecate access to this one before you can even say "SUBMIT THIS APP"... the MAC network address is used to authenticate certain devices on private lans (WLANs) or other virtual private networks (VPNs). .. it's even more sensitive than the former UDID!

Display progress bar while doing some work in C#?

For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls

List of Stored Procedures/Functions Mysql Command Line

If you want to list Store Procedure for Current Selected Database,

SHOW PROCEDURE STATUS WHERE Db = DATABASE();

it will list Routines based on current selected Database

UPDATED to list out functions in your database

select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="FUNCTION";

to list out routines/store procedures in your database,

select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="PROCEDURE";

to list tables in your database,

select * from information_schema.TABLES WHERE TABLE_TYPE="BASE TABLE" AND TABLE_SCHEMA="YOUR DATABASE NAME";

to list views in your database,

method 1:

select * from information_schema.TABLES WHERE TABLE_TYPE="VIEW" AND TABLE_SCHEMA="YOUR DATABASE NAME";

method 2:

select * from information_schema.VIEWS WHERE TABLE_SCHEMA="YOUR DATABASE NAME";

cleanest way to skip a foreach if array is empty

If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:

foreach (($result ? $result : array()) as $item)
    echo $item;

Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

It looks like you added a dependency on a Paypal library but did not include that library in your project:

Caused by: java.lang.ClassNotFoundException: com.paypal.exception.SSLConfigurationException

I'm not sure which jar, but it is most likely paypal-core.jar. Try adding it under WEB-INF/lib.

Mysql password expired. Can't connect

This work for me:

Source: https://www.diariodeunprogramador.net/fallo-al-conectar-mysql-your-password-expired/

Login as root:

mysql -u root -p

and then you deactivate the automatic expiration of passwords of all the users:

SET GLOBAL default_password_lifetime = 0;

How to convert list of key-value tuples into dictionary?

This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required

THAT is your actual question.

The answer is that the elements of your list are not what you think they are. If you type myList[0] you will find that the first element of your list is not a two-tuple, e.g. ('A', 1), but rather a 1916-length iterable.

Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]), all you need to do is dict(myList).

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Just do it Build -> Clean Project. I think this will solve your problem.

When should we call System.exit in Java

In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.

When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:

System.exit(0);
System.out.println("This line will never be reached");

Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".

It's very rare to be worth calling System.exit() IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.

Validate that end date is greater than start date with jQuery

So I needed this rule to be optional and none of the above suggestions are optional. If I call the method it is showing as required even if I set it to needing a value.

This is my call:

  $("#my_form").validate({
    rules: {
      "end_date": {
        required: function(element) {return ($("#end_date").val()!="");},
        greaterStart: "#start_date"
      }
    }
  });//validate()

My addMethod is not as robust as Mike E.'s top rated answer, but I'm using the JqueryUI datepicker to force a date selection. If someone can tell me how to make sure the dates are numbers and have the method be optional that would be great, but for now this method works for me:

jQuery.validator.addMethod("greaterStart", function (value, element, params) {
    return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

PHP is_numeric or preg_match 0-9 validation

is_numeric would accept "-0.5e+12" as a valid ID.

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

This one uses the defineProperty with a nice side-effect causing global variable!

_x000D_
_x000D_
var _a = 1_x000D_
_x000D_
Object.defineProperty(this, "a", {_x000D_
  "get": () => {_x000D_
    return _a++;_x000D_
  },_x000D_
  configurable: true_x000D_
});_x000D_
_x000D_
console.log(a)_x000D_
console.log(a)_x000D_
console.log(a)
_x000D_
_x000D_
_x000D_

Get difference between two lists

temp3 = [item for item in temp1 if item not in temp2]

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Check if a div does NOT exist with javascript

There's an even better solution. You don't even need to check if the element returns null. You can simply do this:

if (document.getElementById('elementId')) {
  console.log('exists')
}

That code will only log exists to console if the element actually exists in the DOM.

How do I print debug messages in the Google Chrome JavaScript Console?

Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....

You can write a script which creates console functions if they don't exist:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log;  // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log

Then, use any of the following:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

Android Gradle Apache HttpClient does not exist?

Perfect Answer by Jinu and Daniel

Adding to this I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)

compile ('org.apache.httpcomponents:httpmime:4.3'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'

else if your compileSdkVersion is 23 then use

android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    }
}

WebService Client Generation Error with JDK8

Another alternative is to update wsimport.sh shell script by adding the following:

The wsimport.sh is located in this directory:

jaxws-ri.2.2.28/bin

exec "$JAVA" $WSIMPORT_OPTS -Djavax.xml.accessExternalSchema=all -jar "$JAXWS_HOME/lib/jaxws-tools.jar" "$@"

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

How do I get out of 'screen' without typing 'exit'?

Ctrl+a followed by k will "kill" the current screen session.

link button property to open in new tab?

  1. LinkButton executes HTTP POST operation, you cant change post target here.
  2. Not all the browsers support posting form to a new target window.
  3. In order to have it post, you have to change target of your "FORM".
  4. You can use some javascript workaround to change your POST target, by changing form's target attribute, but browser will give a warning to user (IE Does), that this page is trying to post data on a new window, do you want to continue etc.

Try to find out ID of your form element in generated aspx, and you can change target like...

getElementByID('theForm').target = '_blank' or 'myNewWindow'

jquery to change style attribute of a div class

Style is an attribute so css won't work for it.U can use attr

Change:

$('.handle').css({'style':'left: 300px'});

T0:

$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override GetWebRequest:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
  System.Net.WebRequest request = base.GetWebRequest(uri);
  request.Headers.Add("myheader", "myheader_value");
  return request;
}

Make sure you remove the DebuggerStepThroughAttribute attribute if you want to step into it.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Interestingly virtually all answers revolve around XPath's function contains(), neglecting the fact it is case sensitive - contrary to the OP's ask.

If you need case insensitivity, that is achievable in XPath 1.0 (the version contemporary browsers support), though it's not pretty - by using the translate() function. It substitutes a source character to its desired form, by using a translation table.

Constructing a table of all upper case characters will effectively transform the node's text to its lower() form - allowing case-insensitive matching (here's just the prerogative):

[
  contains(
    translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
    'my button'
  )
]
# will match a source text like "mY bUTTon"

The full Python call:

driver.find_elements_by_xpath("//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ?', 'abcdefghijklmnopqrstuvwxyz?'), 'my button')]")

Naturally this approach has its drawbacks - as given, it'll work only for Latin text; if you want to cover Unicode characters - you'll have to add them to the translation table. I've done that in the sample above - the last character is the Cyrillic symbol "?".


And if we lived in a world where browsers supported XPath 2.0 and up (, but not happening any time soon ??), we could having used the functions lower-case() (yet, not fully locale-aware), and matches (for regex searches, with the case-insensitive ('i') flag).

Oracle SQL Developer: Unable to find a JVM

If you have a 64-bit version of SQL Developer, but for some reason your default JDK is a 32-bit JDK (e.g. if you develop an Eclipse RCP application which requires a 32-bit JDK), then you have to set the value of the SetJavaHome property in the product.conf file to a 64-bit version of JDK in order to run the SQL Developer. For example:

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

The solution described above worked in my case. The solutions of @evgenyl and @FGreg did not work in my case.

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

What is the quickest way to HTTP GET in Python?

For python >= 3.6, you can use dload:

import dload
t = dload.text(url)

For json:

j = dload.json(url)

Install:
pip install dload

EditText underline below text property

It's actually fairly easy to set the underline color of an EditText programmatically (just one line of code).

To set the color:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

To remove the color:

editText.getBackground().clearColorFilter();

Note: when the EditText has focus on, the color you set won't take effect, instead, it has a focus color.

API Reference:

Drawable#setColorFilter

Drawable#clearColorFilter

How can I get the index from a JSON object with value?

You can use Array.findIndex.

_x000D_
_x000D_
var data= [{
  "name": "placeHolder",
  "section": "right"
}, {
  "name": "Overview",
  "section": "left"
}, {
  "name": "ByFunction",
  "section": "left"
}, {
  "name": "Time",
  "section": "left"
}, {
  "name": "allFit",
  "section": "left"
}, {
  "name": "allbMatches",
  "section": "left"
}, {
  "name": "allOffers",
  "section": "left"
}, {
  "name": "allInterests",
  "section": "left"
}, {
  "name": "allResponses",
  "section": "left"
}, {
  "name": "divChanged",
  "section": "right"
}];
var index = data.findIndex(obj => obj.name=="allInterests");

console.log(index);
_x000D_
_x000D_
_x000D_

nginx error "conflicting server name" ignored

I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled, it may have left a temp file e.g. default~ (watch the ~).

Depending on your editor, the file could be named .save or something like it. Just run $ ls -lah to see which files are unintended to be there and remove them (Thanks @Tisch for this).

Delete this file, and it will solve your problem.

How can I set the PATH variable for javac so I can manually compile my .java works?

Typing the SET PATH command into the command shell every time you fire it up could get old for you pretty fast. Three alternatives:

  1. Run javac from a batch (.CMD) file. Then you can just put the SET PATH into that file before your javac execution. Or you could do without the SET PATH if you simply code the explicit path to javac.exe
  2. Set your enhanced, improved PATH in the "environment variables" configuration of your system.
  3. In the long run you'll want to automate your Java compiling with Ant. But that will require yet another extension to PATH first, which brings us back to (1) and (2).

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

How to remove leading zeros from alphanumeric text?

Without using Regex or substring() function on String which will be inefficient -

public static String removeZero(String str){
        StringBuffer sb = new StringBuffer(str);
        while (sb.length()>1 && sb.charAt(0) == '0')
            sb.deleteCharAt(0);
        return sb.toString();  // return in String
    }

Creating a list/array in excel using VBA to get a list of unique names in a column

You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:

Option Explicit

Sub GetUnique()

Dim rng As Range
Dim myarray, myunique
Dim i As Integer

ReDim myunique(1)

With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
    myarray = Application.Transpose(rng)
    For i = LBound(myarray) To UBound(myarray)
        If IsError(Application.Match(myarray(i), myunique, 0)) Then
            myunique(UBound(myunique)) = myarray(i)
            ReDim Preserve myunique(UBound(myunique) + 1)
        End If
    Next
End With

For i = LBound(myunique) To UBound(myunique)
    Debug.Print myunique(i)
Next

End Sub

This uses array instead of range.
It also uses Match function instead of a nested For Loop.
I didn't have the time to check the time difference though.
So I leave the testing to you.

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.

IIS: Idle Timeout vs Recycle

From here:

One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.

Also check Why is the IIS default app pool recycle set to 1740 minutes?

If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.

Why I can't access remote Jupyter Notebook server?

Have you configured the jupyter_notebook_config.py file to allow external connections?

By default, Jupyter Notebook only accepts connections from localhost (eg, from the same computer that its running on). By modifying the NotebookApp.allow_origin option from the default ' ' to '*', you allow Jupyter to be accessed externally.

c.NotebookApp.allow_origin = '*' #allow all origins

You'll also need to change the IPs that the notebook will listen on:

c.NotebookApp.ip = '0.0.0.0' # listen on all IPs


Also see the details in a subsequent answer in this thread.

Documentation on the Jupyter Notebook config file.

How to refresh token with Google API client?

Sometimes Refresh Token i not generated by using $client->setAccessType ("offline");.

Try this:

$client->setAccessType ("offline");
$client->setApprovalPrompt ("force"); 

How do you detect/avoid Memory leaks in your (Unmanaged) code?

I would recommend using Memory Validator from software verify. This tool proved itself to be of invaluable help to help me track down memory leaks and to improve the memory management of the applications i am working on.

A very complete and fast tool.

jQuery Mobile Page refresh mechanism

Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html

$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )

$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?

Important: Create vs. refresh: An important distinction

Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.

For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.

$.mobile.refresh() doesn't exist i guess

So what are you using for your results? A listview? Then you can update it by doing:

$('ul').listview('refresh');

Example: http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/

Otherwise you can do:

$('#result').live("pageinit", function(){ // or pageshow
    // your dom manipulations here
});

MySQL select rows where left join is null

Here is a query that returns only the rows where no correspondance has been found in both columns user_one and user_two of table2:

SELECT T1.*
FROM table1 T1
LEFT OUTER JOIN table2 T2A ON T2A.user_one = T1.id
LEFT OUTER JOIN table2 T2B ON T2B.user_two = T1.id
WHERE T2A.user_one IS NULL
    AND T2B.user_two IS NULL

There is one jointure for each column (user_one and user_two) and the query only returns rows that have no matching jointure.

Hope this will help you.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Character Limit in HTML

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

// !!! THIS WILL NOT WORK !!!
ref
  .orderBy('genre')
  .startAt('comedy').endAt('comedy')
  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 
      console.log(snapshot.val()); 
  });

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

ref
  .orderBy('genre')
  .equalTo('comedy')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {
          console.log(movie);
      }
  });

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

ref
  .orderBy('genre_lead')
  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

ref
  .orderBy('genre_year')
  .startAt('comedy_1990')
  .endAt('comedy_2000')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

  "movies"
      // the same structure you have today
  "by_genre"
      "comedy"
          "by_lead"
              "Jack Nicholson"
                  "movie1"
              "Jim Carrey"
                  "movie3"
      "Horror"
          "by_lead"
              "Jack Nicholson"
                  "movie2"
      

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063


If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

Disable beep of Linux Bash on Windows 10

You need add following lines to bash and vim config,

1) Turn off bell for bash

vi ~/.inputrc
set bell-style none

2) Turn off bell for vi

vi ~/.vimrc
set visualbell
set t_vb=

Setting the visual bell turns off the audio bell and clearing the visual bell length deactivates flashing.

Set Background color programmatically

This must work:

you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file

View someView = findViewById(R.id.screen);

someView.setBackgroundColor(getResources().getColor(R.color.WHITE));

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

How can I write to the console in PHP?

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

How to initialize List<String> object in Java?

Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information - Yes you can actually do, List list = new List(); But at the cost of writing implementations of all the methods of Interfaces. The notion is not simply List list = new List(); but

List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }

..... and So on (Cant write all methods.)

This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.

How to check if a date is in a given range?

$startDatedt = strtotime($start_date)
$endDatedt = strtotime($end_date)
$usrDatedt = strtotime($date_from_user)

if( $usrDatedt >= $startDatedt && $usrDatedt <= $endDatedt)
{
   //..falls within range
}

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

Read .csv file in C

A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// adjust BUFFER_SIZE to suit longest line 
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1

// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP          0
#define IMIE        1
#define NAZWISKo    2
#define ULICA       3
#define NUMER       4
#define KOD         5
#define MIEJSCOw    6
#define TELEFON     7
#define EMAIL       8
#define DATA_UR     9

long loadFile(FILE *pFile, long *errcount);
static int  loadValues(char *line, long lineno);
static char delim;

long loadFile(FILE *pFile, long *errcount){

    char sInputBuf [BUFFER_SIZE];
    long lineno = 0L;

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

        // load line into static buffer
        if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
            break;

        // skip first line (headers)
        if(++lineno==1)
            continue;

        // jump over empty lines
        if(strlen(sInputBuf)==0)
            continue;
        // set pFields array pointers to null-terminated string fields in sInputBuf
        if(loadValues(sInputBuf,lineno)==RET_FAIL){
           (*errcount)++;
            if(*errcount > MAXERRS)
                break;
        } else {    
            // On return pFields array pointers point to loaded fields ready for load into DB or whatever
            // Fields can be accessed via pFields, e.g.
            printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
        }
    }
    return lineno;
}


static int  loadValues(char *line, long lineno){
    if(line == NULL)
        return RET_FAIL;

    // chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR and LF from end of line
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
        *(line + strlen(line)-1) = '\0';
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
        *(line + strlen(line)-1) = '\0';

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    pFields[fld]=cptr;
    while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
        if(ch == '"') {
            if(! inquote)
                pFields[fld]=cptr+1;
            else {
                *cptr = '\0';               // zero out " and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim && ! inquote){
            *cptr = '\0';                   // end of field, null terminate it
            pFields[++fld]=cptr+1;
        }
        cptr++;
    }   
    if(fld > NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;
    } else if (fld < NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;    
    }
    return RET_OK;
}

int main(int argc, char **argv)
{
   FILE *fp;
   long errcount = 0L;
   long lines = 0L;

   if(argc!=3){
       printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
       return (RET_FAIL);
   }   
   if((delim=argv[2][0])=='\0'){
       fprintf(stderr,"delimiter must be specified\n");
       return (RET_FAIL);
   }
   fp = fopen(argv[1] , "r");
   if(fp == NULL) {
      fprintf(stderr,"Error opening file: %d\n",errno);
      return(RET_FAIL);
   }
   lines=loadFile(fp,&errcount);
   fclose(fp);
   printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
   if(errcount>0)
        return(RET_FAIL);
    return(RET_OK); 
}

How do you query for "is not null" in Mongo?

Thanks for providing a solution, I noticed in MQL, sometimes $ne:null doesn't work instead we need to use syntax $ne:"" i.e. in the context of above example we would need to use db.mycollection.find({"IMAGE URL":{"$ne":""}}) - Not sure why this occurs, I have posted this question in the MongoDB forum.

following is the snapshot showing example:

enter image description here

Converting xml to string using C#

   public string GetXMLAsString(XmlDocument myxml)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
               myxml.WriteTo(xmlTextWriter);
               return stringWriter.ToString();
            }

        }    
}

Count the items from a IEnumerable<T> without iterating?

The System.Linq.Enumerable.Count extension method on IEnumerable<T> has the following implementation:

ICollection<T> c = source as ICollection<TSource>;
if (c != null)
    return c.Count;

int result = 0;
using (IEnumerator<T> enumerator = source.GetEnumerator())
{
    while (enumerator.MoveNext())
        result++;
}
return result;

So it tries to cast to ICollection<T>, which has a Count property, and uses that if possible. Otherwise it iterates.

So your best bet is to use the Count() extension method on your IEnumerable<T> object, as you will get the best performance possible that way.

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

How to check if a float value is a whole number

Just a side info, is_integer is doing internally:

import math
isInteger = (math.floor(x) == x)

Not exactly in python, but the cpython implementation is implemented as mentioned above.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

How do I compare two hashes?

I developed this to compare if two hashes are equal

def hash_equal?(hash1, hash2)
  array1 = hash1.to_a
  array2 = hash2.to_a
  (array1 - array2 | array2 - array1) == []
end

The usage:

> hash_equal?({a: 4}, {a: 4})
=> true
> hash_equal?({a: 4}, {b: 4})
=> false

> hash_equal?({a: {b: 3}}, {a: {b: 3}})
=> true
> hash_equal?({a: {b: 3}}, {a: {b: 4}})
=> false

> hash_equal?({a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}})
=> true
> hash_equal?({a: {b: {c: {d: {e: {f: {g: {marino: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 2}}}}}}}})
=> false

Stop Visual Studio from launching a new browser window when starting debug?

While there are several excellent answers, ranging from usual suspects to newer solutions, I would like to provide one more to the fray that addresses what you should do when you are working on a solution with multiple projects.

Before I arrived at this solution, I kept looking at bindingInformation in the applicationhost.config of the solution, tirelessly looking for any hint of why things were simply not working.

Turns out, the simple thing that I overlooked was that different projects have individual settings too.

So, besides Project > {Project-Name} Properties... > Web > Start Action on my Backend Project, I also had to Go to Website > Start Options... > Start Action on my Frontend Project. Once there, I selected Don't open a page. Wait for a request from an external application and have been happy ever since!

Backend Settings Frontend Settings

How do I force files to open in the browser instead of downloading (PDF)?

Just open Adobe Reader, menu ? Edit ? Preferences ? Internet, then change to browser mode or for detailed instructions on different browsers try Display PDF in browser | Acrobat, Acrobat Reader.

Why is "forEach not a function" for this object?

If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object

Ex:

import each from 'foreach-object';
   
const object = {
   firstName: 'Arosha',
   lastName: 'Sum',
   country: 'Australia'
};
   
each(object, (value, key, object) => {
   console.log(key + ': ' + value);
});
   
// Console log output will be:
//      firstName: Arosha
//      lastName: Sum
//      country: Australia

Failed to Connect to MySQL at localhost:3306 with user root

It worked for me this way:

Step1: Open System Preference > MySQL > Initialize Database.

Step2: Put password you used while installing MySQL.

Step3: Start MySQL server.

Step4: Come back to MySQL Workbench and double connect/ create a new one.

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

A reference to the dll could not be added

I needed to change architecture to x86 from x64 in configuration manager and copy my 32 bit dll (C language - pcProxAPI.dll) into new folder this created.. This is on top of the steps described by "Sashus" below.

C:\Projects..\bin\x86\Debug

Synchronization vs Lock

Lock and synchronize block both serves the same purpose but it depends on the usage. Consider the below part

void randomFunction(){
.
.
.
synchronize(this){
//do some functionality
}

.
.
.
synchronize(this)
{
// do some functionality
}


} // end of randomFunction

In the above case , if a thread enters the synchronize block, the other block is also locked. If there are multiple such synchronize block on the same object, all the blocks are locked. In such situations , java.util.concurrent.Lock can be used to prevent unwanted locking of blocks

Saving changes after table edit in SQL Server Management Studio

To work around this problem, use SQL statements to make the changes to the metadata structure of a table.

This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.

Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"

What do I use on linux to make a python program executable

I do the following:

  1. put #! /usr/bin/env python3 at top of script
  2. chmod u+x file.py
  3. Change .py to .command in file name

This essentially turns the file into a bash executable. When you double-click it, it should run. This works in Unix-based systems.

How do I declare class-level properties in Objective-C?

I'm using this solution:

@interface Model
+ (int) value;
+ (void) setValue:(int)val;
@end

@implementation Model
static int value;
+ (int) value
{ @synchronized(self) { return value; } }
+ (void) setValue:(int)val
{ @synchronized(self) { value = val; } }
@end

And i found it extremely useful as a replacement of Singleton pattern.

To use it, simply access your data with dot notation:

Model.value = 1;
NSLog(@"%d = value", Model.value);

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS for Visual Studio Community 2015.

Then run the following (substituting the variable on the right-hand side if yours has a different name):

set VS100COMNTOOLS=%VS140COMNTOOLS%

This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.

For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

Checking if a number is an Integer in Java

// in C language.. but the algo is same

#include <stdio.h>

int main(){
  float x = 77.6;

  if(x-(int) x>0)
    printf("True! it is float.");
  else
    printf("False! not float.");        

  return 0;
}

How do I append one string to another in Python?

If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.

The end result is that the operation is amortized O(n).

e.g.

s = ""
for i in range(n):
    s+=str(i)

used to be O(n^2), but now it is O(n).

From the source (bytesobject.c):

void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
    PyBytes_Concat(pv, w);
    Py_XDECREF(w);
}


/* The following function breaks the notion that strings are immutable:
   it changes the size of a string.  We get away with this only if there
   is only one module referencing the object.  You can also think of it
   as creating a new string object and destroying the old one, only
   more efficiently.  In any case, don't use this if the string may
   already be known to some other part of the code...
   Note that if there's not enough memory to resize the string, the original
   string object at *pv is deallocated, *pv is set to NULL, an "out of
   memory" exception is set, and -1 is returned.  Else (on success) 0 is
   returned, and the value in *pv may or may not be the same as on input.
   As always, an extra byte is allocated for a trailing \0 byte (newsize
   does *not* include that), and a trailing \0 byte is stored.
*/

int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
    register PyObject *v;
    register PyBytesObject *sv;
    v = *pv;
    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
        *pv = 0;
        Py_DECREF(v);
        PyErr_BadInternalCall();
        return -1;
    }
    /* XXX UNREF/NEWREF interface should be more symmetrical */
    _Py_DEC_REFTOTAL;
    _Py_ForgetReference(v);
    *pv = (PyObject *)
        PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
    if (*pv == NULL) {
        PyObject_Del(v);
        PyErr_NoMemory();
        return -1;
    }
    _Py_NewReference(*pv);
    sv = (PyBytesObject *) *pv;
    Py_SIZE(sv) = newsize;
    sv->ob_sval[newsize] = '\0';
    sv->ob_shash = -1;          /* invalidate cached hash value */
    return 0;
}

It's easy enough to verify empirically.

$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'"
1000000 loops, best of 3: 1.85 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(100):s+='a'"
10000 loops, best of 3: 16.8 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
10000 loops, best of 3: 158 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
1000 loops, best of 3: 1.71 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 14.6 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'"
10 loops, best of 3: 173 msec per loop

It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .

$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'"
10000 loops, best of 3: 90.8 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'"
1000 loops, best of 3: 896 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
100 loops, best of 3: 9.03 msec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
10 loops, best of 3: 89.5 msec per loop

So far so good, but then,

$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 12.8 sec per loop

ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.

What are .tpl files? PHP, web design

Templates. I think that is Smarty syntax.

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

What's the difference between Docker Compose vs. Dockerfile

Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.

Think of Dockerfile as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:

  • We need a Debian linux
  • add an apache web server
  • we need postgresql as well
  • install midnight commander
  • when all done, copy all *.php, *.jpg, etc. files of our project into the webroot of the webserver (/var/www)

By contrast, think of docker-compose.yml as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,

  • it has access to a shared folder from another computer,
  • it's port 80 is the same as the port 8000 of the host computer,
  • and so on.

(This is not a precise explanation but good enough to start with.)

Suppress warning messages using mysql from within Terminal, but password written in bash script

the best solution is to use alias:

alias [yourapp]-mysql="mysql -u root -psomepassword -P3306 -h 127.0.0.1"

example, put this in your script:

alias drupal-mysql="mysql -u root -psomepassword -P3306 -h 127.0.0.1"

then later in your script to load a database:

drupal-mysql database_name < database_dump.sql

to run a statement:

drupal-mysql -e "EXEC SOMESTATEMENT;"

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

Passing arguments forward to another javascript function

Use .apply() to have the same access to arguments in function b, like this:

function a(){
    b.apply(null, arguments);
}
function b(){
   alert(arguments); //arguments[0] = 1, etc
}
a(1,2,3);?

You can test it out here.

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

How to see the changes between two commits without commits in-between?

Let's say you have this

A
|
B    A0
|    |
C    D
\   /
  |
 ...

And you want to make sure that A is the same as A0.

This will do the trick:

$ git diff B A > B-A.diff
$ git diff D A0 > D-A0.diff
$ diff B-A.diff D-A0.diff

Checking version of angular-cli that's installed?

Simple run the following commands:

ng --version 

OR

 ng -v

Output on terminal:

      / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
            |___/


Angular CLI: 6.0.8
Node: 10.15.0
OS: linux x64 

How to get cumulative sum

The latest version of SQL Server (2012) permits the following.

SELECT 
    RowID, 
    Col1,
    SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

or

SELECT 
    GroupID, 
    RowID, 
    Col1,
    SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.

Thanks to Peso, who commented on the SQL Team thread referred to in another answer.

How can I check if the array of objects have duplicate property values?

You can use map to return just the name, and then use this forEach trick to check if it exists at least twice:

var areAnyDuplicates = false;

values.map(function(obj) {
    return obj.name;
}).forEach(function (element, index, arr) {
    if (arr.indexOf(element) !== index) {
        areAnyDuplicates = true;
    }
});

Fiddle

How to change default timezone for Active Record in Rails?

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

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

Google Chrome Printing Page Breaks

I've used the following approach successfully in all major browsers including Chrome:

<!DOCTYPE html>

<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>Paginated HTML</title>
    <style type="text/css" media="print">
      div.page
      {
        page-break-after: always;
        page-break-inside: avoid;
      }
    </style>
  </head>
  <body>
    <div class="page">
      <h1>This is Page 1</h1>
    </div>
    <div class="page">
      <h1>This is Page 2</h1>
    </div>
    <div class="page">
      <h1>This is Page 3</h1>
    </div>
  </body>
</html>

This is a simplified example. In the real code, each page div contains many more elements.

Ruby function to remove all white spaces?

I'm a bit late to the game, but I remove trailing and leading whitespaces by using strip!. If you have an array, such as I did, I needed to iterate through the array and save it after the instance ended. The ! took care of this. This removed all whitespaces at the end or the beginning, not just the first leading or the last trailing.

For example:

array = ["hello ","   Melanie", "is", " new ", "to  ", " programming"]
array.each do |i|
  i.strip!
end

This would output to: ["hello","Melanie", "is", "new ", "to", "programming"]. I further explored/shared this in a video I made to highlight this code for similar question I had.

I'm newer to programming and using strip did not work as it didn't save it to the array after the loop ended.

Merge up to a specific commit

Sure, being in master branch all you need to do is:

git merge <commit-id>

where commit-id is hash of the last commit from newbranch that you want to get in your master branch.

You can find out more about any git command by doing git help <command>. It that case it's git help merge. And docs are saying that the last argument for merge command is <commit>..., so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

Is there such a thing as min-font-size and max-font-size?

CSS min() and max() have fairly good usage rates in 2020.

The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).

font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);

I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.

Possible to change where Android Virtual Devices are saved?

Based on official documentation https://developer.android.com/studio/command-line/variables.html you should change ANDROID_AVD_HOME environment var:

Emulator Environment Variables

By default, the emulator stores configuration files under $HOME/.android/ and AVD data under $HOME/.android/avd/. You can override the defaults by setting the following environment variables. The emulator -avd command searches the avd directory in the order of the values in $ANDROID_AVD_HOME, $ANDROID_SDK_HOME/.android/avd/, and $HOME/.android/avd/. For emulator environment variable help, type emulator -help-environment at the command line. For information about emulator command-line options, see Control the Emulator from the Command Line.

  • ANDROID_EMULATOR_HOME: Sets the path to the user-specific emulator configuration directory. The default location is
    $ANDROID_SDK_HOME/.android/.
  • ANDROID_AVD_HOME: Sets the path to the directory that contains all AVD-specific files, which mostly consist of very large disk images. The default location is $ANDROID_EMULATOR_HOME/avd/. You might want to specify a new location if the default location is low on disk space.

After change or set ANDROID_AVD_HOME you will have to move all content inside ~user/.android/avd/ to your new location and change path into ini file of each emulator, just replace it with your new path

How to convert JSONObjects to JSONArray?

To deserialize the response need to use HashMap:

String resp = ...//String output from your source

Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);

class TheResponse{
 HashMap<String,Song> songs;
}

class Song{
  String id;
  String pos;
}

Check if an array is empty or exists

If you do not have a variable declared as array you can create a check:

if(x && x.constructor==Array && x.length){
   console.log("is array and filed");
}else{
    var x= [];
    console.log('x = empty array');
}

This checks if variable x exists and if it is, checks if it is a filled array. else it creates an empty array (or you can do other stuff);

If you are certain there is an array variable created there is a simple check:

var x = [];

if(!x.length){
    console.log('empty');
} else {
    console.log('full');
}

You can check my fiddle here with shows most possible ways to check array.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

, by mistake wrong configuration which others may have

xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

i.e., extra "/spring-tx-3.1.xsd"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

in other words what is there in xmlns(namespace) should have proper mapping in schemaLocation (namespace vs schema).

namespace here is : http://www.springframework.org/schema/tx

schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

Read large files in Java

Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.

Detect Route Change with react-router

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

and then in AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

From the history docs:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

How to remove the URL from the printing page?

If you set the margin for a page using the code below the header and footers are omitted from the printed page. I have tested this in FireFox and Chrome.

<style media="print">
 @page {
  size: auto;
  margin: 0;
       }
</style>

Git in Visual Studio - add existing project?

Just right click on your solution and select Add to source control. Then select Git.

Now your projects has been added to a local source control. Right click on one of your files and select Commit.

Then enter a commit message and select Commit. Then select Sync to synchronise your project with GitHub. It requires having a Git repository. Go to GitHub, create a new repository, copy the repository link, and add it to your remote source control server. Select Publish.

That's all.

Concatenate two slices in Go

I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).

This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.

To demonstrate, see this example:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground):

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]

We created a "backing" array a with length 10. Then we create the x destination slice by slicing this a array, y slice is created using the composite literal []int{3, 4}. Now when we append y to x, the result is the expected [1 2 3 4], but what may be surprising is that the backing array a also changed, because capacity of x is 10 which is sufficient to append y to it, so x is resliced which will also use the same a backing array, and append() will copy elements of y into there.

If you want to avoid this, you may use a full slice expression which has the form

a[low : high : max]

which constructs a slice and also controls the resulting slice's capacity by setting it to max - low.

See the modified example (the only difference is that we create x like this: x = a[:2:2]:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground)

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]

As you can see, we get the same x result but the backing array a did not change, because capacity of x was "only" 2 (thanks to the full slice expression a[:2:2]). So to do the append, a new backing array is allocated that can store the elements of both x and y, which is distinct from a.

File uploading with Express 4.0: req.files undefined

Here is what i found googling around:

var fileupload = require("express-fileupload");
app.use(fileupload());

Which is pretty simple mechanism for uploads

app.post("/upload", function(req, res)
{
    var file;

    if(!req.files)
    {
        res.send("File was not found");
        return;
    }

    file = req.files.FormFieldName;  // here is the field name of the form

    res.send("File Uploaded");


});

How to Change Font Size in drawString Java

code example below:

g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Remove Trailing Spaces and Update in Columns in SQL Server

Example:

SELECT TRIM('   Sample   ');

Result: 'Sample'

UPDATE TableName SET ColumnName = TRIM(ColumnName)

Swift: print() vs println() vs NSLog()

If you're using Swift 2, now you can only use print() to write something to the output.

Apple has combined both println() and print() functions into one.

Updated to iOS 9

By default, the function terminates the line it prints by adding a line break.

print("Hello Swift")

Terminator

To print a value without a line break after it, pass an empty string as the terminator

print("Hello Swift", terminator: "")

Separator

You now can use separator to concatenate multiple items

print("Hello", "Swift", 2, separator:" ")

Both

Or you could combine using in this way

print("Hello", "Swift", 2, separator:" ", terminator:".")

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

Conversion between UTF-8 ArrayBuffer and String

If you are doing this in browser there are no character encoding libraries built-in, but you can get by with:

function pad(n) {
    return n.length < 2 ? "0" + n : n;
}

var array = new Uint8Array(data);
var str = "";
for( var i = 0, len = array.length; i < len; ++i ) {
    str += ( "%" + pad(array[i].toString(16)))
}

str = decodeURIComponent(str);

Here's a demo that decodes a 3-byte UTF-8 unit: http://jsfiddle.net/Z9pQE/

Replace a string in a file with nodejs

You can also use the 'sed' function that's part of ShellJS ...

 $ npm install [-g] shelljs


 require('shelljs/global');
 sed('-i', 'search_pattern', 'replace_pattern', file);

Visit ShellJs.org for more examples.

SQLite table constraint - unique on multiple columns

Be careful how you define the table for you will get different results on insert. Consider the following



CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title') 
    ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title');

$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title') 
   ...>     ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id          a           b               
----------  ----------  ----------------
1           Alice       Some other title
2           Bob         Palindromic guy 
3           Charles     chucky cheese   
sqlite> select * from t2;
id          a           b              
----------  ----------  ---------------
2           Bob         Palindromic guy
3           Charles     chucky cheese  
4           Alice       Some other titl
sqlite> 

While the insert/update effect is the same, the id changes based on the table definition type (see the second table where 'Alice' now has id = 4; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.

flutter remove back button on appbar

If navigating to another page . Navigator.pushReplacement() can be used. It can be used If you're navigating from login to home screen. Or you can use .
AppBar(automaticallyImplyLeading: false)

How to do if-else in Thymeleaf?

<div th:switch="${user.role}"> 
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p> 
</div>


<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>

Change value of input and submit form in JavaScript

You're trying to access an element based on the name attribute which works for postbacks to the server, but JavaScript responds to the id attribute. Add an id with the same value as name and all should work fine.

<form name="myform" id="myform" action="action.php">
  <input type="hidden" name="myinput" id="myinput" value="0" />
  <input type="text" name="message" id="message" value="" />
  <input type="submit" name="submit" id="submit" onclick="DoSubmit()" />
</form>

function DoSubmit(){
  document.getElementById("myinput").value = '1';
  return true;
}

What is a stack pointer used for in microprocessors?

A stack pointer is a small register that stores the address of the top of stack. It is used for the purpose of pointing address of the top of the stack.

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

Multi-line strings in PHP

$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml

How do I make an asynchronous GET request in PHP?

Here's an adaptation of the accepted answer for performing a simple GET request.

One thing to note if the server does any url rewriting, this will not work. You'll need to use a more full featured http client.

  /**
   * Performs an async get request (doesn't wait for response)
   * Note: One limitation of this approach is it will not work if server does any URL rewriting
   */
  function async_get($url)
  {
      $parts=parse_url($url);

      $fp = fsockopen($parts['host'],
          isset($parts['port'])?$parts['port']:80,
          $errno, $errstr, 30);

      $out = "GET ".$parts['path']." HTTP/1.1\r\n";
      $out.= "Host: ".$parts['host']."\r\n";
      $out.= "Connection: Close\r\n\r\n";
      fwrite($fp, $out);
      fclose($fp);
  }

Get the value in an input text box

You can simply set the value in text box.

First, you get the value like

var getValue = $('#txt_name').val();

After getting a value set in input like

$('#txt_name').val(getValue);

Best way of invoking getter by reflection

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

.ps1 cannot be loaded because the execution of scripts is disabled on this system

I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.

For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:

x86

Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned

x64

Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned

You can check mode using

In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess

I hope this help you.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo

in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how

cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

if the directory /var/mysql doesnt exist, we must create it with

sudo mkdir /var/mysql

Entity Framework Code First - two Foreign Keys from same table

Try this:

public class Team
{
    public int TeamId { get; set;} 
    public string Name { get; set; }

    public virtual ICollection<Match> HomeMatches { get; set; }
    public virtual ICollection<Match> AwayMatches { get; set; }
}

public class Match
{
    public int MatchId { get; set; }

    public int HomeTeamId { get; set; }
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}


public class Context : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HomeTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HomeTeamId)
                    .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
    }
}

Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

nginx showing blank PHP pages

In case anyone is having this issue but none of the above answers solve their problems, I was having this same issue and had the hardest time tracking it down since my config files were correct, my ngnix and php-fpm jobs were running fine, and there were no errors coming through any error logs.

Dumb mistake but I never checked the Short Open Tag variable in my php.ini file which was set to short_open_tag = Off. Since my php files were using <? instead of <?php, the pages were showing up blank. Short Open Tag should have been set to On in my case.

Hope this helps someone.

How do you add swap to an EC2 instance?

Try swapspace http://pqxx.org/development/swapspace/

Most distros have it packaged.

On EC2 you might want to change "swappath" to /mnt or high-iops disk.

How do you make strings "XML safe"?

I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below

function isInCharacterRange(int $r): bool {
    return $r == 0x09 ||
            $r == 0x0A ||
            $r == 0x0D ||
            $r >= 0x20 && $r <= 0xDF77 ||
            $r >= 0xE000 && $r <= 0xFFFD ||
            $r >= 0x10000 && $r <= 0x10FFFF;
}

function xml(string $s, bool $escapeNewline = true): string {
    $w = '';

    $Last = 0;
    $l = strlen($s);
    $i = 0;

    while ($i < $l) {
        $r = mb_substr(substr($s, $i), 0, 1);
        $Width = strlen($r);
        $i += $Width;
        switch ($r) {
            case '"':
                $esc = '&#34;';
                break;
            case "'":
                $esc = '&#39;';
                break;
            case '&':
                $esc = '&amp;';
                break;
            case '<':
                $esc = '&lt;';
                break;
            case '>':
                $esc = '&gt;';
                break;
            case "\t":
                $esc = '&#x9;';
                break;
            case "\n":
                if (!$escapeNewline) {
                    continue 2;
                }
                $esc = '&#xA;';
                break;
            case "\r":
                $esc = '&#xD;';
                break;
            default:
                if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
                    $esc = "\u{FFFD}";
                    break;
                }

                continue 2;
        }
        $w .= substr($s, $Last, $i - $Last - $Width) . $esc;
        $Last = $i;
    }
    $w .= substr($s, $Last);
    return $w;
}

Note you'll need at least PHP7.2 because of the mb_ord usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!

For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

Converting std::__cxx11::string to std::string

If you can recompile all incompatible libs you use, do it with compiler option

-D_GLIBCXX_USE_CXX11_ABI=1

and then rebuild your project. If you can't do so, add to your project's makefile compiler option

-D_GLIBCXX_USE_CXX11_ABI=0

The define

#define _GLIBCXX_USE_CXX11_ABI 0/1

is also good but you probably need to add it to all your files while compiler option do it for all files at once.

Regex match everything after question mark?

str.replace(/^.+?\"|^.|\".+/, '');

This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.

Even for me it is a bit confusing, but ill try to explain it. ^.+? (not anything OPTIONAL) till first " then | Or/stop (still researching what it really means) till/at ^. has selected nothing until before the 2nd " using (| stop/at). And select all that comes after with .+.

Most efficient way to concatenate strings?

The StringBuilder.Append() method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join() is even more efficient than StringBuilder.

StringBuilder sb = new StringBuilder();
sb.Append(someString);

The only problem with String.Join is that you have to concatenate the strings with a common delimiter.

Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty.

string key = String.Join("_", new String[] 
{ "Customers_Contacts", customerID, database, SessionID });

Using pip behind a proxy with CNTLM

Under Windows dont forget to set

SET HTTPS_PROXY=<proxyHost>:<proxyPort>

what I needed to set for

pip install pep8

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Can I dispatch an action in reducer?

You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!

How do pointer-to-pointer's work in C? (and when might you use them?)

I like this "real world" code example of pointer to pointer usage, in Git 2.0, commit 7b1004b:

Linus once said:

I actually wish more people understood the really core low-level kind of coding. Not big, complex stuff like the lockless name lookup, but simply good use of pointers-to-pointers etc.
For example, I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like:


   if (prev)
     prev->next = entry->next;
   else
     list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common.

People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing a

*pp =  entry->next

pointers

Applying that simplification lets us lose 7 lines from this function even while adding 2 lines of comment.

- struct combine_diff_path *p, *pprev, *ptmp;
+ struct combine_diff_path *p, **tail = &curr;

Chris points out in the comments to the 2016 video "Linus Torvalds's Double Pointer Problem".


kumar points out in the comments the blog post "Linus on Understanding Pointers", where Grisha Trubetskoy explains:

Imagine you have a linked list defined as:

   typedef struct list_entry {
       int val;
       struct list_entry *next;
   } list_entry;

You need to iterate over it from the beginning to end and remove a specific element whose value equals the value of to_remove.
The more obvious way to do this would be:

   list_entry *entry = head; /* assuming head exists and is the first entry of the list */
   list_entry *prev = NULL;
   
   while (entry) { /* line 4 */
       if (entry->val == to_remove)     /* this is the one to remove ; line 5 */
           if (prev)
              prev->next = entry->next; /* remove the entry ; line 7 */
           else
               head = entry->next;      /* special case - first entry ; line 9 */
   
       /* move on to the next entry */
       prev = entry;
       entry = entry->next;
   }

What we are doing above is:

  • iterating over the list until entry is NULL, which means we’ve reached the end of the list (line 4).
  • When we come across an entry we want removed (line 5),
  • we assign the value of current next pointer to the previous one,
  • thus eliminating the current element (line 7).

There is a special case above - at the beginning of the iteration there is no previous entry (prev is NULL), and so to remove the first entry in the list you have to modify head itself (line 9).

What Linus was saying is that the above code could be simplified by making the previous element a pointer to a pointer rather than just a pointer.
The code then looks like this:

   list_entry **pp = &head; /* pointer to a pointer */
   list_entry *entry = head;

   while (entry) {
       if (entry->val == to_remove)
           *pp = entry->next;
       else
            pp = &entry->next;
       entry = entry->next;
   }

The above code is very similar to the previous variant, but notice how we no longer need to watch for the special case of the first element of the list, since pp is not NULL at the beginning. Simple and clever.

Also, someone in that thread commented that the reason this is better is because *pp = entry->next is atomic. It is most certainly NOT atomic.
The above expression contains two dereference operators (* and ->) and one assignment, and neither of those three things is atomic.
This is a common misconception, but alas pretty much nothing in C should ever be assumed to be atomic (including the ++ and -- operators)!

Get MIME type from filename extension

Inspired by Samuel's answer, I wrote an improved version:

  • Also works when extension is uppercase.
  • Take filename as input, handle files without extensions gracefully.
  • Don't include "." in keys.
  • List from Apache, for which I wrote a small transformation script.

The resulting source code is over 30K characters so I can't post it here, check it on Github.

How to check if a variable is null or empty string or all whitespace in JavaScript?

A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

function isEmptyOrSpaces(str){
    return str === null || str.match(/^ *$/) !== null;
}

...then:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
    // error 
}

* EDIT * Please note that op specifically states:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

AES Encryption for an NSString on the iPhone

Please use the below mentioned URL to encrypt string using AES excryption with 
key and IV values.

https://github.com/muneebahmad/AESiOSObjC

How to pass variables from one php page to another without form?

You want sessions if you have data you want to have the data held for longer than one page.

$_GET for just one page.

<a href='page.php?var=data'>Data link</a>

on page.php

<?php
echo $_GET['var'];
?>

will output: data

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Run/install/debug Android applications over Wi-Fi?

  1. In Device Settigs-> "Developer options" -> "Revoke USB debugging authorizations".
  2. Connect the device via USB and make sure debugging is working.
  3. adb tcpip 5555
  4. adb connect <DEVICE_IP_ADDRESS>:5555
  5. Disconnect USB
  6. adb devices

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

JUnit tests pass in Eclipse but fail in Maven Surefire

[I am not sure that this is an answer to the original question, since the stacktrace here looks slightly different, but it may be useful to others.]

You can get tests failing in Surefire when you are also running Cobertura (to get code coverage reports). This is because Cobertura requires proxies (to measure code use) and there is some kind of conflict between those and Spring proxies. This only occurs when Spring uses cglib2, which would be the case if, for example, you have proxy-target-class="true", or if you have an object that is being proxied that does not implement interfaces.

The normal fix to this is to add an interface. So, for example, DAOs should be interfaces, implemented by a DAOImpl class. If you autowire on the interface, everything will work fine (because cglib2 is no longer required; a simpler JDK proxy to the interface can be used instead and Cobertura works fine with this).

However, you cannot use interfaces with annotated controllers (you will get a runtime error when trying to use the controller in a servlet) - I do not have a solution for Cobertura + Spring tests that autowire controllers.

Attach a body onload event with JS

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

Dynamically allocating an array of objects

  1. Use array or common container for objects only if they have default and copy constructors.

  2. Store pointers otherwise (or smart pointers, but may meet some issues in this case).

PS: Always define own default and copy constructors otherwise auto-generated will be used

How to change my Git username in terminal?

You probably need to update the remote URL since github puts your username in it. You can take a look at the original URL by typing

git config --get remote.origin.url

Or just go to the repository page on Github and get the new URL. Then use

git remote set-url origin https://{new url with username replaced}

to update the URL with your new username.

Combining Two Images with OpenCV

For those who are looking to combine 2 color images into one, this is a slight mod on Andrey's answer which worked for me :

img1 = cv2.imread(imageFile1)
img2 = cv2.imread(imageFile2)

h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]

#create empty matrix
vis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)

#combine 2 images
vis[:h1, :w1,:3] = img1
vis[:h2, w1:w1+w2,:3] = img2

What is the most efficient way to store a list in the Django models?

A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:

The "list" would be stored in your Django model like so:

class MyModel(models.Model):
    myList = models.TextField(null=True) # JSON-serialized (text) version of your list

In your view/controller code:

Storing the list in the database:

import simplejson as json # this would be just 'import json' in Python 2.7 and later
...
...

myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)
myModel.save()

Retrieving the list from the database:

jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)

Conceptually, here's what's going on:

>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>

How can I convert a string to upper- or lower-case with XSLT?

<xsl:variable name="upper">UPPER CASE</xsl:variable>
<xsl:variable name="lower" select="translate($upper,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')"/>
<xsl:value-of select ="$lower"/>

//displays UPPER CASE as upper case

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

In-memory size of a Python structure

Try memory profiler. memory profiler

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

App can't be opened because it is from an unidentified developer

Open terminal, go to extracted folder of eclipse and run the following command:

./eclipse -clean

How to store decimal values in SQL Server?

The settings for Decimal are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.

So if you put PI into a Decimal(18,0) it will be recorded as 3?

If you put PI into a Decimal(18,2) it will be recorded as 3.14?

If you put PI into Decimal(18,10) be recorded as 3.1415926535.

What is the difference between bindParam and bindValue?

For the most common purpose, you should use bindValue.

bindParam has two tricky or unexpected behaviors:

  • bindParam(':foo', 4, PDO::PARAM_INT) does not work, as it requires passing a variable (as reference).
  • bindParam(':foo', $value, PDO::PARAM_INT) will change $value to string after running execute(). This, of course, can lead to subtle bugs that might be difficult to catch.

Source: http://php.net/manual/en/pdostatement.bindparam.php#94711

Actionbar notification count icon (badge) like Google has

Try looking at the answers to these questions, particularly the second one which has sample code:

How to implement dynamic values on menu item in Android

How to get text on an ActionBar Icon?

From what I see, You'll need to create your own custom ActionView implementation. An alternative might be a custom Drawable. Note that there appears to be no native implementation of a notification count for the Action Bar.

EDIT: The answer you were looking for, with code: Custom Notification View with sample implementation

bash assign default value

Use a colon:

: ${A:=hello}

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

Mocking python function based on input arguments

You can also use partial from functools if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:

def mock_year(year):
    return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))

This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.

if variable contains

The fastest way to check if a string contains another string is using indexOf:

if (code.indexOf('ST1') !== -1) {
    // string code has "ST1" in it
} else {
    // string code does not have "ST1" in it
}

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

Anaconda-Navigator - Ubuntu16.04

In my case, I don't need to set up anything further after installing Anaconda on Ubuntu

here is my screenshot for the version info. enter image description here

Formatting Numbers by padding with leading zeros in SQL Server

As clean as it could get and give scope of replacing with variables:

Select RIGHT(REPLICATE('0',6) + EmployeeID, 6) from dbo.RequestItems
WHERE ID=0

SQL Server 2005 Using DateAdd to add a day to a date

Select getdate() -- 2010-02-05 10:03:44.527

-- To get all date format
select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'
Union
select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'
Union
select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'
Union
select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007
Union
select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007
union
select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010
union
select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'
union
select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205
union
select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010


SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14
SELECT convert(varchar, getdate(), 23) -- 2010-02-05
SELECT convert(varchar, getdate(), 24) -- 10:24:20
SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913
SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990


---==================================
-- To get the time
select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53

select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223
SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM
----=============================================
SELECT getdate()+1
SELECT month(getdate())+1
SELECT year(getdate())+1

Adding a dictionary to another

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

Note: this throws an exception on a duplicate key.


Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(throws on duplicate keys for dictionaries)

Hibernate Error executing DDL via JDBC Statement

you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect

cheers.

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

How to use Git for Unity3D source control?

I wanted to add a very simple workflow from someone who has been frustrated with git in the past. There are several ways to use git, probably the most common for unity are GitHub Desktop, Git Bash and GitHub Unity

https://assetstore.unity.com/packages/tools/version-control/github-for-unity-118069.

Essentially they all do the same thing but its user choice. You can have git for large file setup which allows 1GB free large file storage with additional storage available in data packs for $4/mo for 50GB, and this will allow you to push files >100mb to remote repositories (it stores the actual files on a server and in your repo a pointer)

https://git-lfs.github.com/

If you don't want to setup lfs for whatever reason you can scan your projects for files > 128 mb in windows by typing size:large in the directory where you have your project. This can be handy to search for large files, although there may be some files between 100mb and 128mb that get missed.

enter image description here

The general format of git bash is

git add . (adds files to be commited)

git commit -m 'message' (commits the files with a message, they are still on your pc and not in the remote repo, basically they have been 'versioned' as a new commit)

git push (push files to the repository)

The disadvantage of git bash for unity projects is that if there is a file > 100mb, you won't get an error until you push. You then have to undo your commit by resetting your head to the previous commit. Kind of a hassle, especially if you are new with git bash.

The advantage of GitHub Desktop, is BEFORE you commit files with 100mb it will give you a popup error message. You can then shrink those files or add them to a .gitignore file.

To use a .gitignore file, create a file called .gitignore in your local repository root directory. Simply add the files one line at a time you would like to omit. SharedAssets and other non-Asset folder files can usually be omitted and will automatically repopulate in the editor (packages can be re-imported etc). You can also use wildcards to exclude file types.

If other people are using your GitHub repo and you want to clone or pull you have those options available to you as well on GitHub desktop or Git bash.

I did not mention much about Unity GitHub package where you can use GitHub in the editor because personally I did not find the interface very useful, and I don't think overall its going to help anyone get familiar with git, but this is just my preference.

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

Testing if a list of integer is odd or even

        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }

How to delete files recursively from an S3 bucket

With the latest aws-cli python command line tools, to recursively delete all the files under a folder in a bucket is just:

aws s3 rm --recursive s3://your_bucket_name/foo/

Or delete everything under the bucket:

aws s3 rm --recursive s3://your_bucket_name

If what you want is to actually delete the bucket, there is one-step shortcut:

aws s3 rb --force s3://your_bucket_name

which will remove the contents in that bucket recursively then delete the bucket.

Note: the s3:// protocol prefix is required for these commands to work

Tab space instead of multiple non-breaking spaces ("nbsp")?

It depends on which character set you want to use.

There's no tab entity defined in ISO-8859-1 HTML - but there are a couple of whitespace characters other than &nbsp; such as &thinsp;, &ensp;,and &emsp;.

In ASCII, &#09; is a tab.

Here is a complete listing of HTML entities and a useful discussion of whitespace on Wikipedia.

jQuery & CSS - Remove/Add display:none

i'd suggest adding a class to display/hide elements:

.hide { display:none; }

and then use jquery's .toggleClass() to show/hide the element:

$(".news").toggleClass("hide");

How to use Python's pip to download and keep the zipped files for a package?

The --download-cache option should do what you want:

pip install --download-cache="/pth/to/downloaded/files" package

However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz files were there.

The --download option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download option did not download dependencies.)

pip install package --download="/pth/to/downloaded/files"

The pip documentation outlines using --download for fast & local installs.

How can I check if a value is of type Integer?

Try maybe this way

try{
    double d= Double.valueOf(someString);
    if (d==(int)d){
        System.out.println("integer"+(int)d);
    }else{
        System.out.println("double"+d);
    }
}catch(Exception e){
    System.out.println("not number");
}

But all numbers outside Integers range (like "-1231231231231231238") will be treated as doubles. If you want to get rid of that problem you can try it this way

try {
    double d = Double.valueOf(someString);
    if (someString.matches("\\-?\\d+")){//optional minus and at least one digit
        System.out.println("integer" + d);
    } else {
        System.out.println("double" + d);
    }
} catch (Exception e) {
    System.out.println("not number");
}

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

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image