Programs & Examples On #Dotty

Run react-native on android emulator

I had a similar problem, and after spending so much time and lots of searching about this issue the only trick worked for me:

  1. Please Install the Required SDKs as shown in this figure

Configure Required SDKs Configure Required SDKs

  1. If You have already installed it, so you must have to update the following SDKs:
    • Android SDK Tool (update it to latest version)
    • Android SDK Platform-tools (update it to latest version)
    • Android SDK Build-tools (update it to latest version)
    • Android Support Repository under Extra folder (update it to latest version)
  2. You Must have at least Installed the Same version Android API as the installed Android SDK Build-tools & Android SDK Platform-tools version as shown in the Configure Required SDKs figure above.

Note: Local Maven repository for Support Libraries which is listed as the SDK requirement in the official docs of React-native is now named as Android Support Repository in the SDK Manager .

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

How to scroll UITableView to specific position

finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{    
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{  
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {         
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault    
                                       reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * theCell = (UITableViewCell *)[tableView     
                                              cellForRowAtIndexPath:indexPath];

    CGPoint tableViewCenter = [tableView contentOffset];
    tableViewCenter.y += myTable.frame.size.height/2;

    [tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
    [tableView reloadData]; 
 }

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

A picture is worth a thousand words:

PHP Double Equals == equality chart:

enter image description here

PHP Triple Equals === Equality chart:

enter image description here

Source code to create these images:

https://github.com/sentientmachine/php_equality_charts

Guru Meditation

Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.

  1. NAN != NAN but NAN == true.

  2. == will convert left and right operands to numbers if left is a number. So 123 == "123foo", but "123" != "123foo"

  3. A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.

  4. == is not transitive because "0"== 0, and 0 == "" but "0" != ""

  5. PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==.

  6. "6" == " 6", "4.2" == "4.20", and "133" == "0133" but 133 != 0133. But "0x10" == "16" and "1e3" == "1000" exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.

  7. False == 0, "", [] and "0".

  8. If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity.

  9. A fresh class is == to 1.

  10. False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.

Hope:

If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise == to anything or, or can be surprise casted against your will and != to something of which it should obviously be equal.

Anywhere you use == in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.

Trigger Change event when the Input value changed programmatically?

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

Angular 2 http post params and body

Yes the problem is here. It's related to your syntax.

Try using this

return this.http.post(this.BASE_URL, params, options)
  .map(data => this.handleData(data))
  .catch(this.handleError);

instead of

return this.http.post(this.BASE_URL, params, options)
  .map(this.handleData)
  .catch(this.handleError);

Also, the second parameter is supposed to be the body, not the url params.

django - get() returned more than one topic

get() returns a single object. If there is no existing object to return, you will receive <class>.DoesNotExist. If your query returns more than one object, then you will get MultipleObjectsReturned. You can check here for more details about get() queries.

Similarly, Django will complain if more than one item matches the get() query. In this case, it will raise MultipleObjectsReturned, which again is an attribute of the model class itself.

M2M will return any number of query that it is related to. In this case you can receive zero, one or more items with your query.

In your models you can us following:

for _topic in topic.objects.all():
    _topic.learningobjective_set.all()

you can use _set to execute a select query on M2M. In above case, you will filter all learningObjectives related to each topic

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

Generate random colors (RGB)

color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]

Centering Bootstrap input fields

Try applying this style to your div class="input-group":

text-align:center;

View it: Fiddle.

Namespace for [DataContract]

First, I add the references to my Model, then I use them in my code. There are two references you should add:

using System.ServiceModel;
using System.Runtime.Serialization;

then, this problem was solved in my program. I hope this answer can help you. Thanks.

How to print full stack trace in exception?

Recommend to use LINQPad related nuget package, then you can use exceptionInstance.Dump().

enter image description here

For .NET core:

  • Install LINQPad.Runtime

For .NET framework 4 etc.

  • Install LINQPad

Sample code:

using System;
using LINQPad;

namespace csharp_Dump_test
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                dosome();
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }

        private static void dosome()
        {
            throw new Exception("Unable.");
        }
    }
}

Running result: enter image description here

LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.

Generate random numbers uniformly over an entire range

[edit] Warning: Do not use rand() for statistics, simulation, cryptography or anything serious.

It's good enough to make numbers look random for a typical human in a hurry, no more.

See @Jefffrey's reply for better options, or this answer for crypto-secure random numbers.


Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:

((double) rand() / (RAND_MAX+1)) * (max-min+1) + min

Note: make sure RAND_MAX+1 does not overflow (thanks Demi)!

The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.

This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.


The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found LFSR to be excellent and darn simple to implement, given its properties are OK for you.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had the same problem. SSMS launches the 32bit version of the import and export wizard which has this issue. Try launching the 64bit version application and it should work fine.

What's the best way to get the last element of an array without deleting it?

I think this is a slight improvement on all the existing answers:

$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
  • Performs better than end() or solutions using array_keys(), especially with large arrays
  • Won't modify the array's internal pointer
  • Won't try to access an undefined offset for empty arrays
  • Will work as expected for empty arrays, indexed arrays, mixed arrays, and associative arrays

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

Calling a PHP function from an HTML form in the same file

Use SAJAX or switch to JavaScript

Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.

Is it possible to add dynamically named properties to JavaScript object?

Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

//Call the method to add properties to any object
defineProp( data, "PropertyA",  1 );
defineProp( data, "PropertyB",  2 );
defineProp( data, "PropertyC",  3 );

reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

Only local connections are allowed Chrome and Selenium webdriver

I was also getting the same issue. I resolved this issue by updating the chromedriver. So if anyone is facing same issue with chrome browser just update your chromedriver.

How to customize the background color of a UITableViewCell?

Customizing the background of a table view cell eventually becomes and "all or nothing" approach. It's very difficult to change the color or image used for the background of a content cell in a way that doesn't look strange.

The reason is that the cell actually spans the width of the view. The rounded corners are just part of its drawing style and the content view sits in this area.

If you change the color of the content cell you will end up with white bits visible at the corners. If you change the color of the entire cell, you will have a block of color spanning the width of the view.

You can definitely customize a cell, but it's not quite as easy as you may think at first.

Convert tabs to spaces in Notepad++

To convert existing tabs to spaces, press Edit->Blank Operations->TAB to Space.

If in the future you want to enter spaces instead of tab when you press tab key:

  1. Go to Settings->Preferences...->Language (since version 7.1) or Settings->Preferences...->Tab Settings (previous versions)
  2. Check Replace by space
  3. (Optional) You can set the number of spaces to use in place of a Tab by changing the Tab size field.

Screenshot of Replace by space

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

How to trim whitespace from a Bash variable?

# Trim whitespace from both ends of specified parameter

trim () {
    read -rd '' $1 <<<"${!1}"
}

# Unit test for trim()

test_trim () {
    local foo="$1"
    trim foo
    test "$foo" = "$2"
}

test_trim hey hey &&
test_trim '  hey' hey &&
test_trim 'ho  ' ho &&
test_trim 'hey ho' 'hey ho' &&
test_trim '  hey  ho  ' 'hey  ho' &&
test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
test_trim $'\n' '' &&
test_trim '\n' '\n' &&
echo passed

get current page from url

Request.Url.Segments.Last()

Another option.

Android Studio - Device is connected but 'offline'

I also recently had this problem and I solved it by rebooting Android Studio. But my friend had to have the original cable for his device, no other cables worked.

How to change port for jenkins window service when 8080 is being used

For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.

e.g. map docker container internal jenkins GUI port 8080 to port 9090 external

docker run -it -d --name jenkins42 --restart always \
   -p <ip>:9090:8080 <image>

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

How to put a UserControl into Visual Studio toolBox

I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.

Solution:

  1. From Solution Explorer I Right-Clicked the offending user control file and selected Exclude From Project
  2. Rebuild the solution
  3. Right-Click the user control and select Include in Project (assuming you have the Show All Files enabled in the Solution Explorer)

Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.

Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)

Extending String prototype:

String.prototype.b64encode = function() { 
    return btoa(unescape(encodeURIComponent(this))); 
};
String.prototype.b64decode = function() { 
    return decodeURIComponent(escape(atob(this))); 
};

Usage:

var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );

NOTE:

As stated in the comments, using unescape is not recommended as it may be removed in the future:

Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.

Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

New Line Issue when copying data from SQL Server 2012 to Excel

Seeing as this isn't already mentioned here and it's how I got around the issue...

Right click the target database and choose Tasks > Export data and follow that through. One of the destinations on the 'Choose a destination' screen is Microsoft Excel and there's a step that will accept your query.

It's the SQL Server Import and Export wizard. It's a lot more long-winded than the simple Copy with headers option that I normally use but, save jumping through a lot more hoops, when you have a lot of data to get into excel it's a worthy option.

SQL Server: use CASE with LIKE

You can also do like this

select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end  +  ' %'

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

Removing rounded corners from a <select> element in Chrome/Webkit

Solution with custom right drop-down arrow, uses only css (no images)

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -webkit-border-radius: 0px;_x000D_
  background-image: linear-gradient(45deg, transparent 50%, gray 50%), linear-gradient(135deg, gray 50%, transparent 50%);_x000D_
  background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
  background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
  background-repeat: no-repeat;_x000D_
_x000D_
  -moz-appearance: none;_x000D_
  display: block;_x000D_
  padding: 0.3rem;_x000D_
  height: 2rem;_x000D_
  width: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <h4>Example</h4>_x000D_
  <select>_x000D_
    <option></option>_x000D_
    <option>Hello</option>_x000D_
    <option>World</option>_x000D_
  </select>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

MongoDB running but can't connect using shell

Not so much an answer but more of an FYI:I've just hit this and found this question as a result of searching. Here is the details of my experience:

Shell error

markdsievers@ip-xx-xx-xx-xx:~$ mongo
MongoDB shell version: 2.0.1
connecting to: test
Wed Dec 21 03:36:13 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017
Wed Dec 21 03:36:13 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [1] server [127.0.0.1:27017] 
Wed Dec 21 03:36:13 DBClientCursor::init call() failed
Wed Dec 21 03:36:13 Error: Error during mongo startup. :: caused by :: DBClientBase::findN: transport error: 127.0.0.1 query: { whatsmyuri: 1 } shell/mongo.js:84
exception: connect failed

Mongo logs reveal

Wed Dec 21 03:35:04 [initandlisten] connection accepted from 127.0.0.1:50273 #6612
Wed Dec 21 03:35:04 [initandlisten] connection refused because too many open connections: 819

This perhaps indicates the other answer (JaKi) was experiencing the same thing, where some connections were purged and access made possible again for the shell (other clients)

Responsive width Facebook Page Plugin

Don't forget the data-href field! For me comments were working without it but were not responsive. And of course data-width='100%'

How to extend an existing JavaScript array with another array, without creating a new array

I like the a.push.apply(a, b) method described above, and if you want you can always create a library function like this:

Array.prototype.append = function(array)
{
    this.push.apply(this, array)
}

and use it like this

a = [1,2]
b = [3,4]

a.append(b)

Checkbox Check Event Listener

If you have a checkbox in your html something like:

<input id="conducted" type = "checkbox" name="party" value="0">

and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:

checkbox = document.getElementById('conducted');

checkbox.addEventListener('change', e => {

    if(e.target.checked){
        //do something
    }

});

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

How to get first N elements of a list in C#?

To take first 5 elements better use expression like this one:

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);

or

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);

It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.

class MyList : IEnumerable<int>
{

    int maxCount = 0;

    public int RequestCount
    {
        get;
        private set;
    }
    public MyList(int maxCount)
    {
        this.maxCount = maxCount;
    }
    public void Reset()
    {
        RequestCount = 0;
    }
    #region IEnumerable<int> Members

    public IEnumerator<int> GetEnumerator()
    {
        int i = 0;
        while (i < maxCount)
        {
            RequestCount++;
            yield return i++;
        }
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    #endregion
}
class Program
{
    static void Main(string[] args)
    {
        var list = new MyList(15);
        list.Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 5;

        list.Reset();
        list.OrderBy(q => q).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 15;

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
    }
}

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Change div height on button click

_x000D_
_x000D_
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
  myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
  myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar1);_x000D_
    }_x000D_
}_x000D_
function w2(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar2);_x000D_
    }_x000D_
}
_x000D_
<html>_x000D_
  <head>    _x000D_
  </head>_x000D_
_x000D_
<body >_x000D_
    <button type="button" onClick = "wm1()">200px</button>_x000D_
    <button type="button" onClick = "wm2()">50px</button>_x000D_
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
  _x000D_
  <div id="demo"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Import Script from a Parent Directory

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
    +-- __init__.py
    +-- moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

Using Page_Load and Page_PreRender in ASP.Net

The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.

JavaFX Application Icon

I tried this and it works:

stage.getIcons().add(new Image(getClass().getResourceAsStream("../images/icon.png")));

Extracting .jar file with command line

From the docs:

To extract the files from a jar file, use x, as in:

C:\Java> jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

The folder where jar is probably isn't C:\Java for you, on my Windows partition it's:

C:\Program Files (x86)\Java\jdk[some_version_here]\bin

Unless the location of jar is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.

EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

TSQL Default Minimum DateTime

I think this would work...

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT ((0))
)

Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...

How to define two angular apps / modules in one page?

I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps

Hope this will help

How can I generate a random number in a certain range?

private int getRandomNumber(int min,int max) {
    return (new Random()).nextInt((max - min) + 1) + min;
}

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Because Stage is required, all one-to-many relationships where Stage is involved will have cascading delete enabled by default. It means, if you delete a Stage entity

  • the delete will cascade directly to Side
  • the delete will cascade directly to Card and because Card and Side have a required one-to-many relationship with cascading delete enabled by default again it will then cascade from Card to Side

So, you have two cascading delete paths from Stage to Side - which causes the exception.

You must either make the Stage optional in at least one of the entities (i.e. remove the [Required] attribute from the Stage properties) or disable cascading delete with Fluent API (not possible with data annotations):

modelBuilder.Entity<Card>()
    .HasRequired(c => c.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Side>()
    .HasRequired(s => s.Stage)
    .WithMany()
    .WillCascadeOnDelete(false);

Random date in C#

private Random gen = new Random();
DateTime RandomDay()
{
    DateTime start = new DateTime(1995, 1, 1);
    int range = (DateTime.Today - start).Days;           
    return start.AddDays(gen.Next(range));
}

For better performance if this will be called repeatedly, create the start and gen (and maybe even range) variables outside of the function.

Dependency Injection vs Factory Pattern

DI gives you a composition root, which is a single centralized location for wiring up your object graph. This tends to make object dependencies very explicit, because objects ask for exactly what they need and there is only one place to get it.

A composition root is a clean and straightforward separation of concerns. Objects being injected should have no dependency on the DI mechanism, whether that be a third-party container or a DIY DI. The DI should be invisible.

Factories tend to be more distributed. Different objects use different factories and the factories represent an additional layer of indirection between the objects and their actual dependencies. This additional layer adds its own dependencies to the object graph. Factories are not invisible. A Factory is a middleman.

For this reason, updating factories is more problematic: since factories are a dependency of the business logic, modifying them can have a ripple effect. A composition root is not a dependency of the business logic, so it can be modified in isolation.

The GoF mentions the difficulty of updating Abstract Factories. Part of their explanation is quoted in an answer here. Contrasting DI with Factories also has a lot in common with the question, Is ServiceLocator an anti-pattern?

Ultimately, the answer of which to choose may be opinionated; but I think it boils down to a Factory being a middleman. The question is whether that middleman pulls its weight by adding additional value beyond just supplying a product. Because if you can get that same product without the middleman, then why not cut the middleman out?

A diagram helps to illustrate the difference. DI vs Factory

Hex transparency in colors

I built this small helper method for an android app, may come of use:

 /**
 * @param originalColor color, without alpha
 * @param alpha         from 0.0 to 1.0
 * @return
 */
public static String addAlpha(String originalColor, double alpha) {
    long alphaFixed = Math.round(alpha * 255);
    String alphaHex = Long.toHexString(alphaFixed);
    if (alphaHex.length() == 1) {
        alphaHex = "0" + alphaHex;
    }
    originalColor = originalColor.replace("#", "#" + alphaHex);


    return originalColor;
}

Find non-ASCII characters in varchar columns using SQL Server

There is a user defined function available on the web 'Parse Alphanumeric'. Google UDF parse alphanumeric and you should find the code for it. This user defined function removes all characters that doesn't fit between 0-9, a-z, and A-Z.

Select * from Staging.APARMRE1 ar
where udf_parsealpha(ar.last_name) <> ar.last_name

That should bring back any records that have a last_name with invalid chars for you...though your bonus points question is a bit more of a challenge, but I think a case statement could handle it. This is a bit psuedo code, I'm not entirely sure if it'd work.

Select id, case when udf_parsealpha(ar.last_name) <> ar.last_name then 'last name'
when udf_parsealpha(ar.first_name) <> ar.first_name then 'first name'
when udf_parsealpha(ar.Address1) <> ar.last_name then 'Address1'
end, 
case when udf_parsealpha(ar.last_name) <> ar.last_name then ar.last_name
when udf_parsealpha(ar.first_name) <> ar.first_name then ar.first_name
when udf_parsealpha(ar.Address1) <> ar.last_name then ar.Address1
end
from Staging.APARMRE1 ar
where udf_parsealpha(ar.last_name) <> ar.last_name or
udf_parsealpha(ar.first_name) <> ar.first_name or
udf_parsealpha(ar.Address1) <> ar.last_name 

I wrote this in the forum post box...so I'm not quite sure if that'll function as is, but it should be close. I'm not quite sure how it will behave if a single record has two fields with invalid chars either.

As an alternative, you should be able to change the from clause away from a single table and into a subquery that looks something like:

select id,fieldname,value from (
Select id,'last_name' as 'fieldname', last_name as 'value'
from Staging.APARMRE1 ar
Union
Select id,'first_name' as 'fieldname', first_name as 'value'
from Staging.APARMRE1 ar
---(and repeat unions for each field)
)
where udf_parsealpha(value) <> value

Benefit here is for every column you'll only need to extend the union statement here, while you need to put that comparisson three times for every column in the case statement version of this script

unable to set private key file: './cert.pem' type PEM

I have a similar situation, but I use the key and the certificate in different files.

in my case you can check the matching of the key and the lock by comparing the hashes (see https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/). This helped me to identify inconsistencies.

Finish an activity from another activity

See my answer to Stack Overflow question Finish All previous activities.

What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.

Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.

Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.

Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.

SQL Server 2012 can't start because of a login failure

Short answer:
install Remote Server Administration tools on your SQL Server (it's an optional feature of Windows Server), reboot, then run SQL Server configuration manager, access the service settings for each of the services whose logon account starts with "NT Service...", clear out the password fields and restart the service. Under the covers, SQL Server Config manager will assign these virtual accounts the Log On as a Service right, and you'll be on your way.

tl;dr;

There is a catch-22 between default settings for a windows domain and default install of SQL Server 2012.

As mentioned above, default Windows domain setup will indeed prevent you from defining the "log on as a service" right via Group Policy Edit at the local machine (via GUI at least; if you install Powershell ActiveDirectory module (via Remote Server Administration tools download) you can do it by scripting.

And, by default, SQL Server 2012 setup runs services in "virtual accounts" (NT Service\ prefix, e.g, NT Service\MSSQLServer. These are like local machine accounts, not domain accounts, but you still can't assign them log on as service rights if your server is joined to a domain. SQL Server setup attempts to assign the right at install, and the SQL Server Config Management tool likewise attempts to assign the right when you change logon account.

And the beautiful catch-22 is this: SQL Server tools depend on (some component of) RSAT to assign the logon as service right. If you don't happen to have RSAT installed on your member server, SQL Server Config Manager fails silently trying to apply the setting (despite all the gaudy pre-installation verification it runs) and you end up with services that won't start.

The one hint of this requirement that I was able to find in the blizzard of SQL Server and Virtual Account doc was this: https://msdn.microsoft.com/en-us/library/ms143504.aspx#New_Accounts, search for RSAT.

Font Awesome not working, icons showing as squares

It wasn't working for me because I had Allow from none directive for the root directory in my apache config. Here's how I got it to work...

My directory structure:

root/
root/font-awesome/4.4.0/css/font-awesome.min.css
root/font-awesome/4.4.0/fonts/fontawesome-webfont.*
root/dir1/index.html

where my index.html has:

<link rel="stylesheet" href="../font-awesome/4.4.0/css/font-awesome.min.css">

I chose to continue to disallow access to my root and instead added another directory entry in my apache config for root/font-awesome/

<Directory "/path/root/font-awesome/">
    Allow from all
</Directory>

case in sql stored procedure on SQL Server

Try this

If @NewStatus  = 'InOffice' 
BEGIN
     Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'OutOffice'
BEGIN
    Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'Home'
BEGIN
    Update tblEmployee set Home = -1 where EmpID = @EmpID
END

Apache and Node.js on the Same Server


Instructions to run node server along apache2(v2.4.xx) server:

In order to pipe all requests on a particular URL to your Node.JS application create CUSTOM.conf file inside /etc/apache2/conf-available directory, and add following line to the created file:

ProxyPass /node http://localhost:8000/

Change 8000 to the prefered port number for node server.
Enable custom configurations with following command:

$> sudo a2enconf CUSTOM

CUSTOM is your newly created filename without extension, then enable proxy_http with the command:

$> sudo a2enmod proxy_http

it should enable both proxy and proxy_http modules. You can check whether module is enabled or not with:

$> sudo a2query -m MODULE_NAME

After configuration and modules enabled, you will need to restart apache server:

$> sudo service apache2 restart

Now you can execute node server. All requests to the URL/node will be handled by node server.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

How can I find the version of php that is running on a distinct domain name?

There is a possibility to find the PHP version of other domain by checking "X-Powered-By" response header in the browser through developer tools as other already mentioned it. If it is not exposed through the php.ini configuration there is no way you can get it unless you have access to the server.

More than 1 row in <Input type="textarea" />

Why not use the <textarea> tag?

?<textarea id="txtArea" rows="10" cols="70"></textarea>

Getting the closest string match

If you're doing this in the context of a search engine or frontend against a database, you might consider using a tool like Apache Solr, with the ComplexPhraseQueryParser plugin. This combination allows you to search against an index of strings with the results sorted by relevance, as determined by Levenshtein distance.

We've been using it against a large collection of artists and song titles when the incoming query may have one or more typos, and it's worked pretty well (and remarkably fast considering the collections are in the millions of strings).

Additionally, with Solr, you can search against the index on demand via JSON, so you won't have to reinvent the solution between the different languages you're looking at.

How can building a heap be O(n) time complexity?

While building a heap, lets say you're taking a bottom up approach.

  1. You take each element and compare it with its children to check if the pair conforms to the heap rules. So, therefore, the leaves get included in the heap for free. That is because they have no children.
  2. Moving upwards, the worst case scenario for the node right above the leaves would be 1 comparison (At max they would be compared with just one generation of children)
  3. Moving further up, their immediate parents can at max be compared with two generations of children.
  4. Continuing in the same direction, you'll have log(n) comparisons for the root in the worst case scenario. and log(n)-1 for its immediate children, log(n)-2 for their immediate children and so on.
  5. So summing it all up, you arrive on something like log(n) + {log(n)-1}*2 + {log(n)-2}*4 + ..... + 1*2^{(logn)-1} which is nothing but O(n).

How do I get the currently-logged username from a Windows service in .NET?

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

You will need to add System.Management under References manually.

How to create EditText accepts Alphabets only in android?

Try This

<EditText
  android:id="@+id/EditText1"
  android:text=""
  android:inputType="text|textNoSuggestions"
  android:textSize="18sp"
  android:layout_width="80dp"
  android:layout_height="43dp">
</EditText>

Other inputType can be found Here ..

Java - get pixel array from image

This worked for me:

BufferedImage bufImgs = ImageIO.read(new File("c:\\adi.bmp"));    
double[][] data = new double[][];
bufImgs.getData().getPixels(0,0,bufImgs.getWidth(),bufImgs.getHeight(),data[i]);    

How to get the full URL of a Drupal page?

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

Disable scrolling in an iPhone web application?

document.addEventListener('touchstart', function (e) {
    e.preventDefault();
});

Do not use the ontouchmove property to register the event handler as you are running at risk of overwriting an existing event handler(s). Use addEventListener instead (see the note about IE on the MDN page).

Beware that preventing default for the touchstart event on the window or document will disable scrolling of the descending areas.

To prevent the scrolling of the document but leave all the other events intact prevent default for the first touchmove event following touchstart:

var firstMove;

window.addEventListener('touchstart', function (e) {
    firstMove = true;
});

window.addEventListener('touchmove', function (e) {
    if (firstMove) {
        e.preventDefault();

        firstMove = false;
    }
});

The reason this works is that mobile Safari is using the first move to determine if body of the document is being scrolled. I have realised this while devising a more sophisticated solution.

In case this would ever stop working, the more sophisticated solution is to inspect the touchTarget element and its parents and make a map of directions that can be scrolled to. Then use the first touchmove event to detect the scroll direction and see if it is going to scroll the document or the target element (or either of the target element parents):

var touchTarget,
    touchScreenX,
    touchScreenY,
    conditionParentUntilTrue,
    disableScroll,
    scrollMap;

conditionParentUntilTrue = function (element, condition) {
    var outcome;

    if (element === document.body) {
        return false;
    }

    outcome = condition(element);

    if (outcome) {
        return true;
    } else {
        return conditionParentUntilTrue(element.parentNode, condition);
    }
};

window.addEventListener('touchstart', function (e) {
    touchTarget = e.targetTouches[0].target;
    // a boolean map indicating if the element (or either of element parents, excluding the document.body) can be scrolled to the X direction.
    scrollMap = {}

    scrollMap.left = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollLeft > 0;
    });

    scrollMap.top = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollTop > 0;
    });

    scrollMap.right = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollWidth > element.clientWidth &&
               element.scrollWidth - element.clientWidth > element.scrollLeft;
    });

    scrollMap.bottom =conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollHeight > element.clientHeight &&
               element.scrollHeight - element.clientHeight > element.scrollTop;
    });

    touchScreenX = e.targetTouches[0].screenX;
    touchScreenY = e.targetTouches[0].screenY;
    disableScroll = false;
});

window.addEventListener('touchmove', function (e) {
    var moveScreenX,
        moveScreenY;

    if (disableScroll) {
        e.preventDefault();

        return;
    }

    moveScreenX = e.targetTouches[0].screenX;
    moveScreenY = e.targetTouches[0].screenY;

    if (
        moveScreenX > touchScreenX && scrollMap.left ||
        moveScreenY < touchScreenY && scrollMap.bottom ||
        moveScreenX < touchScreenX && scrollMap.right ||
        moveScreenY > touchScreenY && scrollMap.top
    ) {
        // You are scrolling either the element or its parent.
        // This will not affect document.body scroll.
    } else {
        // This will affect document.body scroll.

        e.preventDefault();

        disableScroll = true;
    }
});

The reason this works is that mobile Safari is using the first touch move to determine if the document body is being scrolled or the element (or either of the target element parents) and sticks to this decision.

How to update a git clone --mirror?

This is the command that you need to execute on the mirror:

git remote update

Reverse the ordering of words in a string

The simplest way to do this..

          string inputStr = "My name is X Y Z";
          string outputStr = string.Empty;
          List<string> templist1 = new List<string>();
          templist1 = inputStr.Split(' ').ToList();
           for (int i = templist1.Count- 1 ; i >= 0; i--)
          {
              if (outputStr != string.Empty)
              {
                  outputStr = outputStr + " " + templist1[i];
              }
              else
              {
                  outputStr = templist1[i];
              }
          }

           Console.WriteLine("Reverse of a String is", outputStr);

        Output:
        Z Y X is name My

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I have just added this code on my partial view and solved the problem, though not very clean, it works. You have to make sure the the Ids of the objects you are rendering.

<script>
    $(document).ready(function () {
        $("#Profile_ProfileID").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#TitleID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#CityID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#GenderID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#PackageID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
    });
</script>

How to determine the last Row used in VBA including blank spaces in between

Well apart from all mentioned ones, there are several other ways to find the last row or column in a worksheet or specified range.

Function FindingLastRow(col As String) As Long

  'PURPOSE: Various ways to find the last row in a column or a range
  'ASSUMPTION: col is passed as column header name in string data type i.e. "B", "AZ" etc.

   Dim wks As Worksheet
   Dim lstRow As Long

   Set wks = ThisWorkbook.Worksheets("Sheet1") 'Please change the sheet name
   'Set wks = ActiveSheet   'or for your problem uncomment this line

   'Method #1: By Finding Last used cell in the worksheet
   lstRow = wks.Range("A1").SpecialCells(xlCellTypeLastCell).Row

   'Method #2: Using Table Range
   lstRow = wks.ListObjects("Table1").Range.Rows.Count

   'Method #3 : Manual way of selecting last Row : Ctrl + Shift + End
   lstRow = wks.Cells(wks.Rows.Count, col).End(xlUp).Row

   'Method #4: By using UsedRange
   wks.UsedRange 'Refresh UsedRange
   lstRow = wks.UsedRange.Rows(wks.UsedRange.Rows.Count).Row

   'Method #5: Using Named Range
   lstRow = wks.Range("MyNamedRange").Rows.Count

   'Method #6: Ctrl + Shift + Down (Range should be the first cell in data set)
   lstRow = wks.Range("A1").CurrentRegion.Rows.Count

   'Method #7: Using Range.Find method
   lstRow = wks.Column(col).Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

   FindingLastRow = lstRow

End Function

Note: Please use only one of the above method as it justifies your problem statement.

Please pay attention to the fact that Find method does not see cell formatting but only data, hence look for xlCellTypeLastCell if only data is important and not formatting. Also, merged cells (which must be avoided) might give you unexpected results as it will give you the row number of the first cell and not the last cell in the merged cells.

Setting environment variables on OS X

There are essentially two problems to solve when dealing with environment variables in OS X. The first is when invoking programs from Spotlight (the magnifying glass icon on the right side of the Mac menu/status bar) and the second when invoking programs from the Dock. Invoking programs from a Terminal application/utility is trivial because it reads the environment from the standard shell locations (~/.profile, ~/.bash_profile, ~/.bashrc, etc.)

When invoking programs from the Dock, use ~/.MacOSX/environment.plist where the <dict> element contains a sequence of <key>KEY</key><string>theValue</string> elements.

When invoking programs from Spotlight, ensure that launchd has been setup with all the key/value settings you require.

To solve both problems simultaneously, I use a login item (set via the System Preferences tool) on my User account. The login item is a bash script that invokes an Emacs lisp function although one can of course use their favorite scripting tool to accomplish the same thing. This approach has the added benefit that it works at any time and does not require a reboot, i.e. one can edit ~/.profile, run the login item in some shell and have the changes visible for newly invoked programs, from either the Dock or Spotlight.

Details:

Login item: ~/bin/macosx-startup

#!/bin/bash
bash -l -c "/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment"

Emacs lisp function: ~/lib/emacs/elisp/macosx/envionment-support.el

;;; Provide support for the environment on Mac OS X

(defun generate-environment ()
  "Dump the current environment into the ~/.MacOSX/environment.plist file."
  ;; The system environment is found in the global variable:
  ;; 'initial-environment' as a list of "KEY=VALUE" pairs.
  (let ((list initial-environment)
        pair start command key value)
    ;; clear out the current environment settings
    (find-file "~/.MacOSX/environment.plist")
    (goto-char (point-min))
    (setq start (search-forward "<dict>\n"))
    (search-forward "</dict>")
    (beginning-of-line)
    (delete-region start (point))
    (while list
      (setq pair (split-string (car list) "=")
            list (cdr list))
      (setq key (nth 0 pair)
            value (nth 1 pair))
      (insert "  <key>" key "</key>\n")
      (insert "  <string>" value "</string>\n")

      ;; Enable this variable in launchd
      (setq command (format "launchctl setenv %s \"%s\"" key value))
      (shell-command command))
    ;; Save the buffer.
    (save-buffer)))

NOTE: This solution is an amalgam of those coming before I added mine, particularly that offered by Matt Curtis, but I have deliberately tried to keep my ~/.bash_profile content platform independent and put the setting of the launchd environment (a Mac only facility) into a separate script.

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

Controlling Maven final name of jar artifact

In my maven ee project I am using:

<build>
    <finalName>shop</finalName>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>${maven.war.version}</version>
            <configuration><webappDirectory>${project.build.directory}/${project.build.finalName}     </webappDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>

How to use PowerShell select-string to find more than one pattern in a file?

If you want to match the two words in either order, use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'

If Failed always comes after VendorEnquiry on the line, just use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

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

VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.

http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso

Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.

How to send string from one activity to another?

For those people who use Kotlin do this instead:

  1. Create a method with a parameter containing String Object.
  2. Navigate to another Activity

For Example,


// * The Method I Mentioned Above 
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
     val intent = Intent(this, AnotherActivity::class.java)
     intent.putExtra("value", valueYouWantToParse)
     intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
     startActivity(intent)
     this.finish()
}

Then just call parseTheValue("the String that you want to parse")

e.g,

val theValue: String
 parseTheValue(theValue)

then in the other activity,

val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()

// * For testing
println(str)

Hope This Help, Happy Coding!

~ Kotlin Code Added By John Melody~

How do I change the root directory of an Apache server?

I was working with LAMP and to change the document root folder, I have edited the default file which is there in the /etc/apache2/sites-available folder.

If you want to do the same, just edit as follows:

DocumentRoot /home/username/new_root_folder
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/username/new_root_folder>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

After this, if you type "localhost" in the browser, it will load the /home/username/new_root_folder content.

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

Returning an array using C

In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.

char * returnArray(char *arr, int size) {
    char *new_arr = malloc(sizeof(char) * size);
    for(int i = 0; i < size; ++i) {
        new_arr[i] = arr[i];
    }
    return new_arr;
}

int main() {

    char arr[7]= {1,0,0,0,0,1,1};
    char *new_arr = returnArray(arr, 7);

    // don't forget to free the memory after you're done with the array
    free(new_arr);

}

Root user/sudo equivalent in Cygwin?

I landed here through google, and I actually believe I've found a way to gain a fully functioning root promt in cygwin.

Here are my steps.

First you need to rename the Windows Administrator account to "root" Do this by opening start manu and typing "gpedit.msc"

Edit the entry under Local Computer Policy > Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options > Accounts: Rename administrator account

Then you'll have to enable the account if it isn't yet enabled. Local Computer Policy > Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options > Accounts: Administrator account status

Now log out and log into the root account.

Now set an environment variable for cygwin. To do that the easy way: Right Click My Computer > Properties

Click (on the left sidebar) "Advanced system settings"

Near the bottom click the "Enviroment Variables" button

Under "System Variables" click the "New..." button

For the name put "cygwin" without the quotes. For the value, enter in your cygwin root directory. ( Mine was C:\cygwin )

Press OK and close all of that to get back to the desktop.

Open a Cygwin terminal (cygwin.bat)

Edit the file /etc/passwd and change the line

Administrator:unused:500:503:U-MACHINE\Administrator,S-1-5-21-12345678-1234567890-1234567890-500:/home/Administrator:/bin/bash

To this (your numbers, and machine name will be different, just make sure you change the highlighted numbers to 0!)

root:unused:0:0:U-MACHINE\root,S-1-5-21-12345678-1234567890-1234567890-0:/root:/bin/bash

Now that all that is finished, this next bit will make the "su" command work. (Not perfectly, but it will function enough to use. I don't think scripts will function correctly, but hey, you got this far, maybe you can find the way. And please share)

Run this command in cygwin to finalize the deal.

mv /bin/su.exe /bin/_su.exe_backup
cat > /bin/su.bat << "EOF"
@ECHO OFF
RUNAS /savecred /user:root %cygwin%\cygwin.bat
EOF
ln -s /bin/su.bat /bin/su
echo ''
echo 'All finished'

Log out of the root account and back into your normal windows user account.

After all of that, run the new "su.bat" manually by double clicking it in explorer. Enter in your password and go ahead and close the window.

Now try running the su command from cygwin and see if everything worked out alright.

How to convert std::string to lower case?

Boost provides a string algorithm for this:

#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str

Or, for non-in-place:

#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);

Android: How to create a Dialog without a title?

Use this

    Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.image_show_dialog_layout);

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In Visual Studio 2012:

Go to the project properties -> Debug -> Uncheck "Enable the Visual Studio hosting process"

In where shall I use isset() and !empty()

isset($variable) === (@$variable !== null)
empty($variable) === (@$variable == false)

IndentationError: unexpected unindent WHY?

This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

If you change "except" above to "except:", the error will go away.

Good luck.

How to jump to a particular line in a huge text file?

Since there is no way to determine the lenght of all lines without reading them, you have no choice but to iterate over all lines before your starting line. All you can do is to make it look nice. If the file is really huge then you might want to use a generator based approach:

from itertools import dropwhile

def iterate_from_line(f, start_from_line):
    return (l for i, l in dropwhile(lambda x: x[0] < start_from_line, enumerate(f)))

for line in iterate_from_line(open(filename, "r", 0), 141978):
    DoSomethingWithThisLine(line)

Note: the index is zero based in this approach.

Implementing INotifyPropertyChanged - does a better way exist?

Talk about massive overengineering. This is significantly more complex than just doing it the right way and gives little to no benefit. If your IDE supports code snippets (Visual Studio/MonoDevelop do) then you can make implementing this ridiculously simple. All you'd actually have to type is the type of the property and the property name. The extra three lines of code will be autogenerated.

How to extract numbers from a string and get an array of ints?

I found this expression simplest

String[] extractednums = msg.split("\\\\D++");

How to get a single value from FormGroup

You can get value like this

this.form.controls['your form control name'].value

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

The first things I would look for are color - like RED , when doing Red eye detection in an image - there is a certain color range to detect , some characteristics about it considering the surrounding area and such as distance apart from the other eye if it is indeed visible in the image.

1: First characteristic is color and Red is very dominant. After detecting the Coca Cola Red there are several items of interest 1A: How big is this red area (is it of sufficient quantity to make a determination of a true can or not - 10 pixels is probably not enough), 1B: Does it contain the color of the Label - "Coca-Cola" or wave. 1B1: Is there enough to consider a high probability that it is a label.

Item 1 is kind of a short cut - pre-process if that doe snot exist in the image - move on.

So if that is the case I can then utilize that segment of my image and start looking more zoom out of the area in question a little bit - basically look at the surrounding region / edges...

2: Given the above image area ID'd in 1 - verify the surrounding points [edges] of the item in question. A: Is there what appears to be a can top or bottom - silver? B: A bottle might appear transparent , but so might a glass table - so is there a glass table/shelf or a transparent area - if so there are multiple possible out comes. A Bottle MIGHT have a red cap, it might not, but it should have either the shape of the bottle top / thread screws, or a cap. C: Even if this fails A and B it still can be a can - partial.. This is more complex when it is partial because a partial bottle / partial can might look the same , so some more processing of measurement of the Red region edge to edge.. small bottle might be similar in size ..

3: After the above analysis that is when I would look at the lettering and the wave logo - because I can orient my search for some of the letters in the words As you might not have all of the text due to not having all of the can, the wave would align at certain points to the text (distance wise) so I could search for that probability and know which letters should exist at that point of the wave at distance x.

Downloading an entire S3 bucket?

It's always better to use awscli for downloading / uploading files to s3. Sync will help you to resume without any hassle.

aws s3 sync s3://bucketname/ .

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

The condition has length > 1 and only the first element will be used

Like sgibb said it was an if problem, it had nothing to do with | or ||.

Here is another way to solve your problem:

for (i in 1:nrow(trip)) {
  if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "G:C to T:A"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "G:C to C:G"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
    trip[i, 'mutType'] <- "G:C to A:T"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "A:T to T:A"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
    trip[i, 'mutType'] <- "A:T to G:C"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "A:T to C:G"
  }
}

ASP.NET GridView RowIndex As CommandArgument

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

How to add message box with 'OK' button?

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

How to move git repository with all branches from bitbucket to github?

I had the reverse use case of importing an existing repository from github to bitbucket.

Bitbucket offers an Import tool as well. The only necessary step is to add URL to repository.

It looks like:

Screenshot of the bitbucket import tool

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

The Problem is related to MySql Driver

Class.forName("com.mysql.jdbc.Driver");

Add the MySQL jdbc driver jar file in to your classpath.

Also i have this error on JDK. I build the ClassPath Properly then I put the "mysql-connector-java-5.1.25-bin" in dir "C:\Program Files\Java\jre7\lib\ext" in this dir i have my JDK. then compile and Run again then it's working fine.

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

Easiest way to use SVG in Android?

First you need to import svg files by following simple steps.

  1. Right click on drawable
  2. Click new
  3. Select Vector Asset

If image is available in your computer then select local svg file. After that select the image path and an option to change the size of the image is also available at the right side of dialog if you want to . in this way svg image is imported in your project After that for using this image use the same procedure

@drawable/yourimagename

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

Where can I find error log files?

I am using Cent OS 6.6 with Apache and for me error log files are in

/usr/local/apache/log

How can I find all *.js file in directory recursively in Linux?

Use find on the command line:

find /my/directory -name '*.js'

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Define width of .absorbing-column

Set table-layout to auto and define an extreme width on .absorbing-column.

Here I have set the width to 100% because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.

This is one of the quirky benefits of how tables behave. The table-layout: auto algorithm is mathematically forgiving.

You may even choose to define a min-width on all td elements to prevent them from becoming too narrow and the table will behave nicely.

_x000D_
_x000D_
table {_x000D_
    table-layout: auto;_x000D_
    border-collapse: collapse;_x000D_
    width: 100%;_x000D_
}_x000D_
table td {_x000D_
    border: 1px solid #ccc;_x000D_
}_x000D_
table .absorbing-column {_x000D_
    width: 100%;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

SQL How to replace values of select return?

If you want the column as string values, then:

SELECT id, name, CASE WHEN hide = 0 THEN 'false' ELSE 'true' END AS hide
  FROM anonymous_table

If the DBMS supports BOOLEAN, you can use instead:

SELECT id, name, CASE WHEN hide = 0 THEN false ELSE true END AS hide
  FROM anonymous_table

That's the same except that the quotes around the names false and true were removed.

Work with a time span in Javascript

Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.

const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60;   //     60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60;     //  3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24;        // 86,400,000

export class TimeSpan {
    private _millis: number;

    private static interval(value: number, scale: number): TimeSpan {
        if (Number.isNaN(value)) {
            throw new Error("value can't be NaN");
        }

        const tmp = value * scale;
        const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
        if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return new TimeSpan(millis);
    }

    private static round(n: number): number {
        if (n < 0) {
            return Math.ceil(n);
        } else if (n > 0) {
            return Math.floor(n);
        }

        return 0;
    }

    private static timeToMilliseconds(hour: number, minute: number, second: number): number {
        const totalSeconds = (hour * 3600) + (minute * 60) + second;
        if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return totalSeconds * MILLIS_PER_SECOND;
    }

    public static get zero(): TimeSpan {
        return new TimeSpan(0);
    }

    public static get maxValue(): TimeSpan {
        return new TimeSpan(Number.MAX_SAFE_INTEGER);
    }

    public static get minValue(): TimeSpan {
        return new TimeSpan(Number.MIN_SAFE_INTEGER);
    }

    public static fromDays(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_DAY);
    }

    public static fromHours(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_HOUR);
    }

    public static fromMilliseconds(value: number): TimeSpan {
        return TimeSpan.interval(value, 1);
    }

    public static fromMinutes(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_MINUTE);
    }

    public static fromSeconds(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_SECOND);
    }

    public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
    public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
    public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
        if (milliseconds != undefined) {
            return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
        } else {
            return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
        }
    }

    private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
        const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
        return new TimeSpan(millis);
    }

    private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
        const totalMilliSeconds = (days * MILLIS_PER_DAY) +
            (hours * MILLIS_PER_HOUR) +
            (minutes * MILLIS_PER_MINUTE) +
            (seconds * MILLIS_PER_SECOND) +
            milliseconds;

        if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }
        return new TimeSpan(totalMilliSeconds);
    }

    constructor(millis: number) {
        this._millis = millis;
    }

    public get days(): number {
        return TimeSpan.round(this._millis / MILLIS_PER_DAY);
    }

    public get hours(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
    }

    public get minutes(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
    }

    public get seconds(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
    }

    public get milliseconds(): number {
        return TimeSpan.round(this._millis % 1000);
    }

    public get totalDays(): number {
        return this._millis / MILLIS_PER_DAY;
    }

    public get totalHours(): number {
        return this._millis / MILLIS_PER_HOUR;
    }

    public get totalMinutes(): number {
        return this._millis / MILLIS_PER_MINUTE;
    }

    public get totalSeconds(): number {
        return this._millis / MILLIS_PER_SECOND;
    }

    public get totalMilliseconds(): number {
        return this._millis;
    }

    public add(ts: TimeSpan): TimeSpan {
        const result = this._millis + ts.totalMilliseconds;
        return new TimeSpan(result);
    }

    public subtract(ts: TimeSpan): TimeSpan {
        const result = this._millis - ts.totalMilliseconds;
        return new TimeSpan(result);
    }
}

How to use

Create a new TimeSpan object

From zero

    const ts = TimeSpan.zero;

From milliseconds

    const milliseconds = 10000; // 1 second

    // by using the constructor
    const ts1 = new TimeSpan(milliseconds);

    // or as an alternative you can use the static factory method
    const ts2 = TimeSpan.fromMilliseconds(milliseconds);

From seconds

    const seconds = 86400; // 1 day
    const ts = TimeSpan.fromSeconds(seconds);

From minutes

    const minutes = 1440; // 1 day
    const ts = TimeSpan.fromMinutes(minutes);

From hours

    const hours = 24; // 1 day
    const ts = TimeSpan.fromHours(hours);

From days

    const days = 1; // 1 day
    const ts = TimeSpan.fromDays(days);

From time with given hours, minutes and seconds

    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const ts = TimeSpan.fromTime(hours, minutes, seconds);

From time2 with given days, hours, minutes, seconds and milliseconds

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);

From maximal safe integer

    const ts = TimeSpan.maxValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

Add

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.add(ts2);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Subtract

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.subtract(ts2);

    console.log(ts.days);               // 0
    console.log(ts.hours);              // 23
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Getting the intervals

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 1
    console.log(ts.seconds);            // 1
    console.log(ts.milliseconds);           // 1

    console.log(ts.totalDays)           // 1.0423726967592593;
    console.log(ts.totalHours)          // 25.016944722222224;
    console.log(ts.totalMinutes)            // 1501.0166833333333;
    console.log(ts.totalSeconds)            // 90061.001;
    console.log(ts.totalMilliseconds);      // 90061001;

See also here: https://github.com/erdas/timespan

Is having an 'OR' in an INNER JOIN condition a bad idea?

You can use UNION ALL instead.

SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.MainTable AS mt Union ALL SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.OtherTable AS ot

Close/kill the session when the browser or tab is closed

Use this:

 window.onbeforeunload = function () {
    if (!validNavigation) {
        endSession();
    }
}

jsfiddle

Prevent F5, form submit, input click and Close/kill the session when the browser or tab is closed, tested in ie8+ and modern browsers, Enjoy!

Array or List in Java. Which is faster?

Since there are already a lot of good answers here, I would like to give you some other information of practical view, which is insertion and iteration performance comparison : primitive array vs Linked-list in Java.

This is actual simple performance check.
So, the result will depend on the machine performance.

Source code used for this is below :

import java.util.Iterator;
import java.util.LinkedList;

public class Array_vs_LinkedList {

    private final static int MAX_SIZE = 40000000;

    public static void main(String[] args) {

        LinkedList lList = new LinkedList(); 

        /* insertion performance check */

        long startTime = System.currentTimeMillis();

        for (int i=0; i<MAX_SIZE; i++) {
            lList.add(i);
        }

        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;
        System.out.println("[Insert]LinkedList insert operation with " + MAX_SIZE + " number of integer elapsed time is " + elapsedTime + " millisecond.");

        int[] arr = new int[MAX_SIZE];

        startTime = System.currentTimeMillis();
        for(int i=0; i<MAX_SIZE; i++){
            arr[i] = i; 
        }

        stopTime = System.currentTimeMillis();
        elapsedTime = stopTime - startTime;
        System.out.println("[Insert]Array Insert operation with " + MAX_SIZE + " number of integer elapsed time is " + elapsedTime + " millisecond.");


        /* iteration performance check */

        startTime = System.currentTimeMillis();

        Iterator itr = lList.iterator();

        while(itr.hasNext()) {
            itr.next();
            // System.out.println("Linked list running : " + itr.next());
        }

        stopTime = System.currentTimeMillis();
        elapsedTime = stopTime - startTime;
        System.out.println("[Loop]LinkedList iteration with " + MAX_SIZE + " number of integer elapsed time is " + elapsedTime + " millisecond.");


        startTime = System.currentTimeMillis();

        int t = 0;
        for (int i=0; i < MAX_SIZE; i++) {
            t = arr[i];
            // System.out.println("array running : " + i);
        }

        stopTime = System.currentTimeMillis();
        elapsedTime = stopTime - startTime;
        System.out.println("[Loop]Array iteration with " + MAX_SIZE + " number of integer elapsed time is " + elapsedTime + " millisecond.");
    }
}

Performance Result is below :

enter image description here

Extract directory path and filename

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

Android - Launcher Icon Size

LDPI should be 36 x 36.

MDPI 48 x 48.

TVDPI 64 x 64.

HDPI 72 x 72.

XHDPI 96 x 96.

XXHDPI 144 x 144.

XXXHDPI 192 x 192.

Windows batch files: .bat vs .cmd?

Here is a compilation of verified information from the various answers and cited references in this thread:

  1. command.com is the 16-bit command processor introduced in MS-DOS and was also used in the Win9x series of operating systems.
  2. cmd.exe is the 32-bit command processor in Windows NT (64-bit Windows OSes also have a 64-bit version). cmd.exe was never part of Windows 9x. It originated in OS/2 version 1.0, and the OS/2 version of cmd began 16-bit (but was nonetheless a fully fledged protected mode program with commands like start). Windows NT inherited cmd from OS/2, but Windows NT's Win32 version started off 32-bit. Although OS/2 went 32-bit in 1992, its cmd remained a 16-bit OS/2 1.x program.
  3. The ComSpec env variable defines which program is launched by .bat and .cmd scripts. (Starting with WinNT this defaults to cmd.exe.)
  4. cmd.exe is backward compatible with command.com.
  5. A script that is designed for cmd.exe can be named .cmd to prevent accidental execution on Windows 9x. This filename extension also dates back to OS/2 version 1.0 and 1987.

Here is a list of cmd.exe features that are not supported by command.com:

  • Long filenames (exceeding the 8.3 format)
  • Command history
  • Tab completion
  • Escape character: ^ (Use for: \ & | > < ^)
  • Directory stack: PUSHD/POPD
  • Integer arithmetic: SET /A i+=1
  • Search/Replace/Substring: SET %varname:expression%
  • Command substitution: FOR /F (existed before, has been enhanced)
  • Functions: CALL :label

Order of Execution:

If both .bat and .cmd versions of a script (test.bat, test.cmd) are in the same folder and you run the script without the extension (test), by default the .bat version of the script will run, even on 64-bit Windows 7. The order of execution is controlled by the PATHEXT environment variable. See Order in which Command Prompt executes files for more details.

References:

wikipedia: Comparison of command shells

Apache POI Excel - how to configure columns to be expanded?

If you want to auto size all columns in a workbook, here is a method that might be useful:

public void autoSizeColumns(Workbook workbook) {
    int numberOfSheets = workbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getPhysicalNumberOfRows() > 0) {
            Row row = sheet.getRow(sheet.getFirstRowNum());
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();
                sheet.autoSizeColumn(columnIndex);
            }
        }
    }
}

How do I pass a method as a parameter in Python

Example: a simple function call wrapper:

def measure_cpu_time(f, *args):
    t_start = time.process_time()
    ret = f(*args)
    t_end = time.process_time()
    return t_end - t_start, ret

Disable Pinch Zoom on Mobile Web

To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.

But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.

Prevent flex items from overflowing a container

One easy solution is to use overflow values other than visible to make the text flex basis width reset as expected.

  1. Here with value auto the text wraps as expected and the article content does not overflow main container.

  2. Also, the article flex value must either have a auto basis AND be able to shrink, OR, only grow AND explicit 0 basis

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
  overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
  /* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

How can I issue a single command from the command line through sql plus?

Have you tried something like this?

sqlplus username/password@database < "EXECUTE some_proc /"

Seems like in UNIX you can do:

sqlplus username/password@database <<EOF
EXECUTE some_proc;
EXIT;
EOF

But I'm not sure what the windows equivalent of that would be.

javascript setTimeout() not working

If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.

i.e. works

setTimeout(function(){ startTimer(p1, p2); }, 1000);

i.e. won't work because it will call the function right away

setTimeout( startTimer(p1, p2), 1000);

Database Diagram Support Objects cannot be Installed ... no valid owner

You should consider SQL authentication account for database ownership; then you don't have to worry about accounts coming and going, databases or instances moving to different servers, and your next PC name change. I have several systems where we use:

ALTER AUTHORIZATION ON DATABASE::Ariha TO [sa];

Or if you want to change the owner to that local Administrator account, then it should be:

ALTER AUTHORIZATION ON DATABASE::Ariha TO [DevPC\Administrator];

Because renaming the machine to DevPC has eliminated the local account that used to be named WIN-ND...\Administrator and this has also invalidated the current owner of the database.

If SELECT @@SERVERNAME; is not accurate (it should say DevPC), then in order to ensure that your server rename has taken hold within SQL Server, you may also want to issue the following:

EXEC sys.sp_dropserver @server = N'old server name';
GO
EXEC sys.sp_addserver @server = N'DevPC', @local = N'local';
GO

Inner join vs Where

They should be exactly the same. However, as a coding practice, I would rather see the Join. It clearly articulates your intent,

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to decrypt hash stored by bcrypt

To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.

In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.

Bcrypt has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt you will be able to check far fewer per second.

The fact that bcrypt is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST recommends the PBKDF2 for password hashing.

How to delete and recreate from scratch an existing EF Code First database

If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx

... then this might work:

  1. Delete all .mdf and .ldf files in your project directory
  2. Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode. See also https://stackoverflow.com/a/15832184/2279059

How can I enable auto complete support in Notepad++?

Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.

Ctrl + Enter - as simple as that!

This, for many people, will be better than autocompleting on everything.

Execute a terminal command from a Cocoa app

Custos Mortem said:

I'm surprised no one really got into blocking/non-blocking call issues

For blocking/non-blocking call issues regarding NSTask read below:

asynctask.m -- sample code that shows how to implement asynchronous stdin, stdout & stderr streams for processing data with NSTask

Source code of asynctask.m is available at GitHub.

Get list of filenames in folder with Javascript

The current code will give a list of all files in a folder, assuming it's on the server side you want to list all files:

var fs = require('fs');
var files = fs.readdirSync('/assets/photos/');

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

You can get table/view details through below query.

For table :sp_help table_name For View :sp_help view_name

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

jQuery - prevent default, then continue default

You can use e.preventDefault() which will stop the current operation.

than you can do$("#form").submit();

 $('#form').submit(function (e)
{
    return !!e.submit;
});
if(blabla...)
{...
}
else
{
    $('#form').submit(
    {
        submit: true
    });
}

Set up adb on Mac OS X

In my case, I installed Android studio, and have some apps (rust lang) that changes the ~/.profile, and adding adb to ~/.bash_profile made the rust un-executable, so I made the changes to the ~/.profile only, as:

$ echo 'PATH=$PATH:$HOME/Library/Android/sdk/platform-tools/' >> ~/.profile
$ source ~/.profile
$ adb --version
Android Debug Bridge version 1.0.41
Version 29.0.4-5871666
Installed as /Users/hasan/Library/Android/sdk/platform-tools/adb

Laravel Eloquent - distinct() and count() not working properly together

Anyone else come across this post, and not finding the other suggestions to work?

Depending on the specific query, a different approach may be needed. In my case, I needed either count the results of a GROUP BY, e.g.

SELECT COUNT(*) FROM (SELECT * FROM a GROUP BY b)

or use COUNT(DISTINCT b):

SELECT COUNT(DISTINCT b) FROM a

After some puzzling around, I realised there was no built-in Laravel function for either of these. So the simplest solution was to use use DB::raw with the count method.

$count = $builder->count(DB::raw('DISTINCT b'));

Remember, don't use groupBy before calling count. You can apply groupBy later, if you need it for getting rows.

Embedding Base64 Images

Update: 2017-01-10

Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.

http://caniuse.com/#feat=datauri


Data URIs are now supported by the following web browsers:

  • Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
  • Konqueror, via KDE's KIO slaves input/output system
  • Opera (including devices such as the Nintendo DSi or Wii)
  • WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
  • Trident
    • Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
    • Data URIs are supported only for the following elements and/or attributes[4]:
      • object (images only)
      • img
      • input type=image
      • link
    • CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
    • Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
    • TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme

http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

HTML text input field with currency symbol

Put the '$' in front of the text input field, instead of inside it. It makes validation for numeric data a lot easier because you don't have to parse out the '$' after submit.

You can, with JQuery.validate() (or other), add some client-side validation rules that handle currency. That would allow you to have the '$' inside the input field. But you still have to do server-side validation for security and that puts you back in the position of having to remove the '$'.

Allow click on twitter bootstrap dropdown toggle link?

An alternative solution is just to remove the 'dropdown-toggle' class from the anchor. After this clicking will no longer trigger the dropwon.js, so you may want to have the submenu to show on hover.

How to identify all stored procedures referring a particular table

The following works on SQL2008 and above. Provides a list of both stored procedures and functions.

select distinct [Table Name] = o.Name, [Found In] = sp.Name, sp.type_desc
  from sys.objects o inner join sys.sql_expression_dependencies  sd on o.object_id = sd.referenced_id
                inner join sys.objects sp on sd.referencing_id = sp.object_id
                    and sp.type in ('P', 'FN')
  where o.name = 'YourTableName'
  order by sp.Name

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

Remote Linux server to remote linux server dir copy. How?

I think you can try with:

rsync -azvu -e ssh user@host1:/directory/ user@host2:/directory2/

(and I assume you are on host0 and you want to copy from host1 to host2 directly)

If the above does not work, you could try:

ssh user@host1 "/usr/bin/rsync -azvu -e ssh /directory/ user@host2:/directory2/"

in the this, it would work, if you already have setup passwordless SSH login from host1 to host2

Regular Expression: Any character that is NOT a letter or number

This is way way too late, but since there is no accepted answer I'd like to provide what I think is the simplest one: \D - matches all non digit characters.

_x000D_
_x000D_
var x = "123 235-25%";_x000D_
x.replace(/\D/g, '');
_x000D_
_x000D_
_x000D_

Results in x: "12323525"

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Underline text in UIlabel

As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.

Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.

You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.

Look up the UIKit additions to NSString:

(CGSize)sizeWithFont:(UIFont *)font 
//Returns the size of the string if it were to be rendered with the specified font on a single line.

(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size 
// Returns the size of the string if it were rendered and constrained to the specified size.

(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
//Returns the size of the string if it were rendered with the specified constraints.

How to change current Theme at runtime in Android

This way work for me:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(GApplication.getInstance().getTheme());
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

Then you want to change a new theme:

GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();

C++ Best way to get integer division and remainder

On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

Instruction: DIV src

Note: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.

int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */

Bootstrap 3 dropdown select

Try this:

<div class="form-group">
     <label class="control-label" for="Company">Company</label>
     <select id="Company" class="form-control" name="Company">
         <option value="small">small</option>
         <option value="medium">medium</option>
         <option value="large">large</option>
     </select> 
 </div>

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

Cassandra port usage - how are the ports used?

8080 - JMX (remote)

8888 - Remote debugger (removed in 0.6.0)

7000 - Used internal by Cassandra
(7001 - Obsolete, removed in 0.6.0. Used for membership communication, aka gossip)

9160 - Thrift client API

Cassandra FAQ What ports does Cassandra use?

Detect Route Change with react-router

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';

<Router>
    <Sidebar />
        <Switch>
            <Route path="/rooms/:roomId" component={Chat}>
            </Route>
        </Switch>
</Router>

import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
    **const history = useHistory();**
    var openChat = function (id) {
        **//To navigate**
        history.push("/rooms/" + id);
    }
}

**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
    var { roomId } = useParams();
    var roomId = props.match.params.roomId;

    useEffect(() => {
       //Detect the paramter change
    }, [roomId])

    useEffect(() => {
       //Detect the location/url change
    }, [location])
}

ASP.NET - How to write some html in the page? With Response.Write?

If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:

<body>
<% Response.Write(stringVariable); %>
</body>

A shorthand for this syntax is:

<body>
<%= stringVariable %>
</body>

how to convert from int to char*?

You also can use casting.

example:

string s;
int value = 3;
s.push_back((char)('0' + value));

c# Best Method to create a log file

Instead of using log4net which is an external library I have created my own simple class, highly customizable and easy to use (edit YOURNAMESPACEHERE with the namespace that you need).

CONSOLE APP

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

    internal static class Log
    {
        private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
        private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

        internal static void Write(LogEvent Level, string Message, bool ShowConsole = true, bool WritelogFile = true)
        {
            string Event = string.Empty;
            ConsoleColor ColorEvent = Console.ForegroundColor;

            switch (Level)
            {
                case LogEvent.Info:
                    Event = "INFO";
                    ColorEvent = ConsoleColor.White;
                    break;
                case LogEvent.Success:
                    Event = "SUCCESS";
                    ColorEvent = ConsoleColor.Green;
                    break;
                case LogEvent.Warning:
                    Event = "WARNING";
                    ColorEvent = ConsoleColor.Yellow;
                    break;
                case LogEvent.Error:
                    Event = "ERROR";
                    ColorEvent = ConsoleColor.Red;
                    break;
            }

            if (ShowConsole)
            {
                Console.ForegroundColor = ColorEvent;
                Console.WriteLine(" [{0}] => {1}", DateTime.Now.ToString("HH:mm:ss"), Message);
                Console.ResetColor();
            }

            if (WritelogFile)
            {
                if (!Directory.Exists(LogPath))
                    Directory.CreateDirectory(LogPath);

                File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
            }
        }
    }
}

NO CONSOLE APP (ONLY LOG)

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

internal static class Log
{
    private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
    private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

    internal static void Write(LogEvent Level, string Message)
    {
        string Event = string.Empty;

        switch (Level)
        {
            case LogEvent.Info:
                Event = "INFO";
                break;
            case LogEvent.Success:
                Event = "SUCCESS";
                break;
            case LogEvent.Warning:
                Event = "WARNING";
                break;
            case LogEvent.Error:
                Event = "ERROR";
                break;
        }

        if (!Directory.Exists(LogPath))
            Directory.CreateDirectory(LogPath);

        File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
    }
}

Usage:

CONSOLE APP

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your console, also will save a copy of this print in a .log file.
Log.Write(LogEvent.Warning, "Test message", false); // It will save the print as warning only in your .log file.
Log.Write(LogEvent.Error, "Test message", true, false); // It will print an error only in your console.

NO CONSOLE APP (ONLY LOG)

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your .log file.

Prevent Android activity dialog from closing on outside touch

This could help you. It is a way to handle the touch outside event:

How to cancel an Dialog themed like Activity when touched outside the window?

By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be not to close itself when you touch outside.

(PS: the code uses WindowManager.LayoutParams)

How to update maven repository in Eclipse?

Sometimes the dependencies don't update even with Maven->Update Project->Force Update option checked using m2eclipse plugin.

In case it doesn't work for anyone else, this method worked for me:

  • mvn eclipse:eclipse

    This will update your .classpath file with the new dependencies while preserving your .project settings and other eclipse config files.

If you want to clear your old settings for whatever reason, you can run:

  • mvn eclipse:clean
  • mvn eclipse:eclipse

    mvn eclipse:clean will erase your old settings, then mvn eclipse:eclipse will create new .project, .classpath and other eclipse config files.

How to insert tab character when expandtab option is on in Vim

You can disable expandtab option from within Vim as below:

:set expandtab!

or

:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

How to find the .NET framework version of a Visual Studio project?

With Respect to .NET Framework 4.6 and Visual Studio 2017 you can take the below steps:

  1. On the option bar at the top of visual studio, select the 4th option "Project" and under that click on the last option which says [ProjectName]Properties.Click on it & you shall see a new tab has been opened.Under that select the Application option on the left and you will see the .NET Framework version by the name "Target Framework".
  2. Under Solution Explorer's tab select your project and press Alt + Enter.
  3. OR simply Right-click on your project and click on the last option which says Properties.

How to set Apache Spark Executor memory

you mentioned that you are running yourcode interactivly on spark-shell so, while doing if no proper value is set for driver-memory or executor memory then spark defaultly assign some value to it, which is based on it's properties file(where default value is being mentioned).

I hope you are aware of the fact that there is one driver(master node) and worker-node(where executors are get created and processed), so basically two types of space is required by the spark program,so if you want to set driver memory then when start spark-shell .

spark-shell --driver-memory "your value" and to set executor memory : spark-shell --executor-memory "your value"

then I think you are good to go with the desired value of the memory that you want your spark-shell to use.

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

We just ran into this same issue. Our Cpanel has expanded from PHP only to PHP and .NET and defaulted to .NET.

Log in to you Cpanel and make sure you don’t have the same issue.

How to set layout_weight attribute dynamically from code?

If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.

So first you should use "getLayoutParams" and then setLayoutParams

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams(); params.weight = 4f; mButton.setLayoutParams(params);

Comment out HTML and PHP together

The <!-- --> is only for HTML commenting and the PHP will still run anyway...

Therefore the best thing I would do is also to comment out the PHP...

Excel how to fill all selected blank cells with text

I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).

In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.

Sub FillWithNull()

Dim cell As range
Dim myRange As range

Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False

For Each cell In myRange
    If Len(cell) = 0 Then
        cell.Value = "Null"
    End If
Next

Application.ScreenUpdating = True

End Sub

Testing the type of a DOM element in JavaScript

I have another way of testing the same.

_x000D_
_x000D_
Element.prototype.typeof = "element";_x000D_
var element = document.body; // any dom element_x000D_
if (element && element.typeof == "element"){_x000D_
   return true; _x000D_
   // this is a dom element_x000D_
}_x000D_
else{_x000D_
  return false; _x000D_
  // this isn't a dom element_x000D_
}
_x000D_
_x000D_
_x000D_

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I have updated old android project for the Wear OS. I have got this error message while build the project:

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:percent:26.0.2] AndroidManifest.xml:25:13-35
is also present at [com.android.support:support-v4:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:23:9-25:38 to override.

My build.gradle for Wear app contains these dependencies:

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.android.support:wearable:2.4.0'
implementation 'com.google.android.gms:play-services-wearable:16.0.1'
compileOnly 'com.google.android.wearable:wearable:2.4.0'}

SOLUTION:

Adding implementation 'com.android.support:support-v4:28.0.0' into the dependencies solved my problem.

add allow_url_fopen to my php.ini using .htaccess

Try this, but I don't think it will work because you're not supposed to be able to change this

Put this line in an htaccess file in the directory you want the setting to be enabled:

php_value allow_url_fopen On

Note that this setting will only apply to PHP file's in the same directory as the htaccess file.

As an alternative to using url_fopen, try using curl.

How do I change the background of a Frame in Tkinter?

You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.

from tkinter import *
from tkinter.ttk import * 

root = Tk()

s = Style()
s.configure('My.TFrame', background='red')

mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

How to get first and last day of week in Oracle?

WEEK

select TRUNC(sysdate, 'iw') AS iso_week_start_date,
       TRUNC(sysdate, 'iw') + 7 - 1/86400 AS iso_week_end_date
from dual;

MONTH

select 
TRUNC (sysdate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (sysdate, 'mm')) + 1 - 1/86400 AS month_end_date
from dual;

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

Can I use a binary literal in C or C++?

You can use the function found in this question to get up to 22 bits in C++. Here's the code from the link, suitably edited:

template< unsigned long long N >
struct binary
{
  enum { value = (N % 8) + 2 * binary< N / 8 > :: value } ;
};

template<>
struct binary< 0 >
{
  enum { value = 0 } ;
};

So you can do something like binary<0101011011>::value.

Edit and replay XHR chrome/firefox etc?

5 years have passed and this essential requirement didn't get ignored by the Chrome devs.
While they offer no method to edit the data like in Firefox, they offer a full XHR replay.
This allows to debug ajax calls.
enter image description here
"Replay XHR" will repeat the entire transmission.

Convert blob to base64

So the problem is that you want to upload a base 64 image and you have a blob url. Now the answer that will work on all html 5 browsers is: Do:

  var fileInput = document.getElementById('myFileInputTag');
  var preview = document.getElementById('myImgTag');

  fileInput.addEventListener('change', function (e) {
      var url = URL.createObjectURL(e.target.files[0]);
      preview.setAttribute('src', url);
  });
function Upload()
{
     // preview can be image object or image element
     var myCanvas = document.getElementById('MyCanvas');
     var ctx = myCanvas.getContext('2d');
     ctx.drawImage(preview, 0,0);
     var base64Str = myCanvas.toDataURL();
     $.ajax({
         url: '/PathToServer',
         method: 'POST',
         data: {
             imageString: base64Str
         },
     success: function(data) { if(data && data.Success) {}},
     error: function(a,b,c){alert(c);}
     });
 }

YouTube Video Embedded via iframe Ignoring z-index?

wmode=opaque or transparent at the beginning of my query string didnt solve anything. This issue for me only occurs on Chrome, and not across even all computers. Just one cpu. It occurs in vimeo embeds as well, and possibly others.

My solution to to attach to the 'shown' and 'hidden' event of the bootstrap modals I am using, add a class which sets the iframe to 1x1 pixels, and remove the class when the modal closes. Seems like it works and is simple to implement.

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

Upgrading PHP on CentOS 6.5 (Final)

Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6

To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Now install yum-utils, a group of useful tools that enhance yum’s default package management features

yum install yum-utils

In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.

yum-config-manager --enable remi-php70

If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.

yum-config-manager --enable remi-php71 
yum-config-manager --enable remi-php72

Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.

yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo

Double check the installed version of PHP on your system as follows.

php -V 

How in node to split string by newline ('\n')?

a = a.split("\n");

Note that splitting returns the new array, rather than just assigning it to the original string. You need to explicitly store it in a variable.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

Differences between JDK and Java SDK

The JDK (Java Development Kit) is an SDK (Software Dev Kit).

It is used to build software/applications on Java and of course it includes the JRE (Java Runtime Edition) to execute that software. If you just want to execute a Java application, download only the JRE.

By the way, Java EE (Enterprise Edition) contains libraries of packages of classes "with methods (functions)" to build apps for the WEB environment and Java ME (Micro Edition) for mobile devices. If you are interested in it (Java ME) I would recommend to take a look at Google's Android DevKit and API.

Take a look here: it's gonna explain bit more.. http://www.oracle.com/technetwork/java/archive-139210.html

Actual meaning of 'shell=True' in subprocess

let's assume you are using shell=False and providing the command as a list. And some malicious user tried injecting an 'rm' command. You will see, that 'rm' will be interpreted as an argument and effectively 'ls' will try to find a file called 'rm'

>>> subprocess.run(['ls','-ld','/home','rm','/etc/passwd'])
ls: rm: No such file or directory
-rw-r--r--    1 root     root          1172 May 28  2020 /etc/passwd
drwxr-xr-x    2 root     root          4096 May 29  2020 /home
CompletedProcess(args=['ls', '-ld', '/home', 'rm', '/etc/passwd'], returncode=1)

shell=False is not a secure by default, if you don't control the input properly. You can still execute dangerous commands.

>>> subprocess.run(['rm','-rf','/home'])
CompletedProcess(args=['rm', '-rf', '/home'], returncode=0)
>>> subprocess.run(['ls','-ld','/home'])
ls: /home: No such file or directory
CompletedProcess(args=['ls', '-ld', '/home'], returncode=1)
>>>

I am writing most of my applications in container environments, I know which shell is being invoked and i am not taking any user input.

So in my use case, I see no security risk. And it is much easier creating long string of commands. Hope I am not wrong.

SOAP client in .NET - references or examples?

Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.

There are 2 main way of doing this:

A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.

Adding a service reference step by step

The simplest way is to generate proxy classes in C# application (this process is called adding service reference).

  1. Open your project (or create a new one) in visual studio
  2. Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
  3. A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.

    add service reference dialog

    I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example

  4. Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).

    You should see generated proxy class name and namespace.

    In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.

    service reference proxy calss

  5. Go to your C# source code and add the following

    using WindowsFormsApplication1.ServiceReference1
    
  6. Now you can call the service this way.

    Service1Client service = new Service1Client();
    int year = service.getCurrentYear();
    

Hope this helps. If you encounter any problems, let us know.

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

Remove a marker from a GoogleMap

Add the marker to the map like this

Marker markerName = map.addMarker(new MarkerOptions().position(latLng).title("Title"));

Then you'll be able to use the remove method, it will remove only that marker

markerName.remove();