Programs & Examples On #Vbulletin

vBulletin (vB) is commercial Internet forum software produced by Jelsoft Enterprises and vBulletin Solutions, both subsidiaries of Internet Brands. It is written in PHP and uses a MySQL database server.

Best solution to protect PHP code without encryption

I have not looked at the VBulletin source code in some time, but the way they used to do it around 2003 was to embed a call to their server inside the code. IIRC, it was on a really long code line (like 200-300+ chars long) and was broken up over several string concatenations and such.

It did nothing "bad" if you pirated it - the forum still worked 100%. But your server's IP was logged along with other info and they used that to investigate and take legal action.

Your license number was embedded in this call, so they could easily track how many IPs/websites a given licensed copy was running on.

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

Error inflating class fragment

Check you class path, this could be the view inflator could not find your class definition as defined in your xml class="de.androidbuch.activiti.task.TaskDetailsFragment" the above path could be wrong.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

Adding line break in C# Code behind page

Option A: concatenate several string literal into one:

string myText = "Looking up into the night sky is looking into infinity" +
    " - distance is incomprehensible and therefore meaningless.";

Option B: use a single multiline string literal:

string myText = @"Looking up into the night sky is looking into infinity
- distance is incomprehensible and therefore meaningless.";

With option B, the newline character(s) will be part of the string saved into variable myText. This might, or might not, be what you want.

Label on the left side instead above an input field

No CSS required. This should look fine on your page. You can set col-md-* as per your needs

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="row">_x000D_
                            <div class="col-md-12">_x000D_
                                <form class="form-inline" role="form">_x000D_
                                    <div class="col">_x000D_
                                        <div class="form-group">_x000D_
                                            <label for="inputEmail" class="col-sm-3">Email</label>_x000D_
                                            <input type="email" class="form-control col-sm-7" id="inputEmail" placeholder="Email">_x000D_
                                        </div>_x000D_
                                    </div>_x000D_
                                    <div class="col">_x000D_
                                        <div class="form-group">_x000D_
                                            <label for="inputPassword" class="col-sm-3">Email</label>_x000D_
                                            <input type="password" class="form-control col-sm-7" id="inputPassword" placeholder="Email">_x000D_
                                        </div>_x000D_
                                    </div>_x000D_
                                    _x000D_
                                    <button class="btn btn-primary">Button 1</button>_x000D_
                                    &nbsp;&nbsp;_x000D_
                                    <button class="btn btn-primary">Button 2</button>_x000D_
                                </form>_x000D_
                            </div>_x000D_
                        </div>
_x000D_
_x000D_
_x000D_

Response Buffer Limit Exceeded

In my case i just have writing this line before rs.Open .....

Response.flush

rs.Open query, conn

Create a txt file using batch file in a specific folder

This code written above worked for me as well. Although, you can use the code I am writing here:

@echo off

@echo>"d:\testing\dblank.txt

If you want to write some text to dblank.txt then add the following line in the end of your code

@echo Writing text to dblank.txt> dblank.txt

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

jQuery: load txt file and insert into div

You can use jQuery load method to get the contents and insert into an element.

Try this:

$(document).ready(function() {
        $("#lesen").click(function() {
                $(".text").load("helloworld.txt");
    }); 
}); 

You, can also add a call back to execute something once the load process is complete

e.g:

$(document).ready(function() {
    $("#lesen").click(function() {
        $(".text").load("helloworld.txt", function(){
            alert("Done Loading");
        });
   }); 
}); 

Check if a given key already exists in a dictionary and increment it

The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.

The other approach is called EAFP (easier to ask forgiveness then permission). In that case, you would just try the operation (increment the value). If it fails, you catch the exception and set the value to 1. This is a slightly more Pythonic way to do it (IMO).

http://mail.python.org/pipermail/python-list/2003-May/205182.html

CSS text-overflow in a table cell?

It seems that if you specify table-layout: fixed; on the table element, then your styles for td should take effect. This will also affect how the cells are sized, though.

Sitepoint discusses the table-layout methods a little here: http://reference.sitepoint.com/css/tableformatting

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

I thought Activity was deprecated

No.

So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?

Activity is the baseline. Every activity inherits from Activity, directly or indirectly.

FragmentActivity is for use with the backport of fragments found in the support-v4 and support-v13 libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion values. The only reason why you would need to consider FragmentActivity specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.

AppCompatActivity is from the appcompat-v7 library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity for that. However, current versions of appcompat-v7 also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7, well beyond the scope of this specific Stack Overflow answer.

ActionBarActivity is the old name of the base activity from appcompat-v7. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity, you should prefer AppCompatActivity over ActionBarActivity.

So, given your minSdkVersion in the 15-16 range:

  • If you want the backported Material Design look, use AppCompatActivity

  • If not, but you want nested fragments, use FragmentActivity

  • If not, use Activity

Just adding from comment as note: AppCompatActivity extends FragmentActivity, so anyone who needs to use features of FragmentActivity can use AppCompatActivity.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

If you are using a Ubuntu system, use the following to Store Password Permanently:

git config --global credential.helper store

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

SQL Add foreign key to existing column

Maybe you got your columns backwards??

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?

Then your command should be:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

How do I insert a JPEG image into a python Tkinter window?

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

How to read single Excel cell value

Here's a solution that may work better in the case you are referencing objWorksheet.UsedRange.

Excel.Worksheet mySheet = ...(load a workbook, etc);
Excel.Range myRange = mySheet.UsedRange;
var values = (myRange.Value as Object[,]);
int rowNumber = 3, columnNumber = 5;
string cellValue = Convert.ToString(values[rowNumber, columnNumber]);

How to set min-font-size in CSS

CSS Solution:

.h2{
  font-size: 2vw
}
@media (min-width: 700px) {
  .h2{
    /* Minimum font size */
    font-size: 14px
  }
}
@media (max-width: 1200px) {
  .h2{
    /* Maximum font size */
    font-size: 24px
  }
}

Just in case if some need scss mixin:

///
/// Viewport sized typography with minimum and maximum values
///
/// @author Eduardo Boucas (@eduardoboucas)
///
/// @param {Number}   $responsive  - Viewport-based size
/// @param {Number}   $min         - Minimum font size (px)
/// @param {Number}   $max         - Maximum font size (px)
///                                  (optional)
/// @param {Number}   $fallback    - Fallback for viewport-
///                                  based units (optional)
///
/// @example scss - 5vw font size (with 50px fallback),
///                 minumum of 35px and maximum of 150px
///  @include responsive-font(5vw, 35px, 150px, 50px);
///

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

How to move from one fragment to another fragment on click of an ImageView in Android?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);
    notification = (ImageView)v.findViewById(R.id.notification);

    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentTransaction fr = getFragmentManager().beginTransaction();
            fr.replace(R.id.container,new NotificationFragment());
            fr.commit();
        }
    });

    return v;
}

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

android View not attached to window manager

Or Simply you Can add

protected void onPreExecute() {
    mDialog = ProgressDialog.show(mContext, "", "Saving changes...", true, false);
}

which will make the ProgressDialog to not cancel-able

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

If using TextBox2.Text as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

If the text box is blank when Convert.ToInt32 is called, you will receive the System.FormatException. Suggest trying:

protected void SetImageWidth()
{
   try{
      Image1.Width = Convert.ToInt32(TextBox1.Text);
   }
   catch(System.FormatException)
   {
      Image1.Width = 100; // or other default value as appropriate in context.
   }
}

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

For me this error appeared immediatey after I changed the user's home directory by

sudo usermod -d var/www/html username

It can also happen because of lack of proper permission to authorized_key file in ~/.ssh. Make sure the permission of this file is 0600 and permission of ~/.ssh is 700.

Reset local repository branch to be just like remote repository HEAD

I did:

git branch -D master
git checkout master

to totally reset branch


note, you should checkout to another branch to be able to delete required branch

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

How to hide html source & disable right click and text copy?

I have constructed a simple self checking php file, it only allows real loading by humans, and not robots like ( online source code viewer's ) ..

I'm not sure about View Source from Chrome, but it does block access to the html... Not just obfuscation, it uses a bounce back submittance to validate loads.

The short code was still visible in source viewers, so i obfuscated it also...

The page is loaded and bounces back, the bounce gets the real page, not the loader !

   // Create A New File called ( lock.php ) 

Copy this into it....

<?php 
// PAGE SOURCE GUARD by Elijah Cuff.
if (!hasParam('bounce'))
{
echo "
<script type='text/javascript'>
<!-- 
eval(unescape('%66%75%6e%63%74%69%6f%6e%20%63%36%36%32%32%30%36%62%32%63%28%73%29%20%7b%0a%09%76%61%72%20%72%20%3d%20%22%22%3b%0a%09%76%61%72%20%74%6d%70%20%3d%20%73%2e%73%70%6c%69%74%28%22%37%36%33%33%31%37%31%22%29%3b%0a%09%73%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%30%5d%29%3b%0a%09%6b%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%31%5d%20%2b%20%22%35%37%35%31%36%35%22%29%3b%0a%09%66%6f%72%28%20%76%61%72%20%69%20%3d%20%30%3b%20%69%20%3c%20%73%2e%6c%65%6e%67%74%68%3b%20%69%2b%2b%29%20%7b%0a%09%09%72%20%2b%3d%20%53%74%72%69%6e%67%2e%66%72%6f%6d%43%68%61%72%43%6f%64%65%28%28%70%61%72%73%65%49%6e%74%28%6b%2e%63%68%61%72%41%74%28%69%25%6b%2e%6c%65%6e%67%74%68%29%29%5e%73%2e%63%68%61%72%43%6f%64%65%41%74%28%69%29%29%2b%2d%36%29%3b%0a%09%7d%0a%09%72%65%74%75%72%6e%20%72%3b%0a%7d%0a'));
eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%63%36%36%32%32%30%36%62%32%63%28%27') + '%47%67%7f%76%73%44%15%15%45%69%74%7e%76%23%7a%6e%7f%6f%75%6c%46%2f%73%74%7f%7f%2d%2f%6a%6f%42%28%7e%62%7a%2d%45%15%15%47%66%71%73%7a%7a%20%7f%78%73%6a%45%2d%6b%66%6f%6f%6a%74%2e%23%73%62%72%6d%46%2d%61%70%7e%75%69%6d%2d%21%79%66%74%7e%6e%4a%2d%32%29%44%44%30%68%71%77%7d%7f%41%1a%15%47%34%6c%73%7d%74%41%12%16%47%7c%60%7d%6a%77%7a%42%16%17%23%7c%69%71%6f%7c%78%31%78%6b%7c%5f%68%76%6a%73%7e%7f%27%69%7e%75%69%7c%6a%72%71%2f%29%23%84%1a%15%23%6b%75%6f%7e%74%6e%75%7c%31%68%62%7f%4e%73%6b%75%6e%73%7f%49%79%4a%6f%27%67%28%79%67%7b%67%2a%2a%35%7f%7e%6d%7a%6a%7f%2f%2f%47%16%17%23%27%85%37%23%33%33%33%2e%41%15%15%45%30%78%6f%7d%6a%7f%7f%41%12%10%44%30%69%7f%72%74%417633171%35%39%35%35%31%30%36' + unescape('%27%29%29%3b'));
// -->
</script>
<noscript><i>Javascript required</i></noscript>
";
exit;
}
function hasParam($param)
{
    return isset($_POST[$param]);
}
?>

NOW ADD THIS TO THE VERY TOP OF
EVERY PAGE .. Example....

<?php
 // use require for more security...
include('lock.php'); 
?>

<HTML> 
etc.. etc...

OR is not supported with CASE Statement in SQL Server

Try

CASE WHEN ebv.db_no IN (22978,23218,23219) THEN 'WECS 9500' ELSE 'WECS 9520' END

How to cast or convert an unsigned int to int in C?

If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Convert Variable Name to String?

This is not possible.

In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.

Consider this example:

foo = 1
bar = 1
baz = 1

Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.

In Python, a name is a way to access an object, so there is no way to work with names directly. There might be some clever way to hack the Python bytecodes or something to get the value of the name, but that is at best a parlor trick.

If you know you want print foo to print "foo", you might as well just execute print "foo" in the first place.

EDIT: I have changed the wording slightly to make this more clear. Also, here is an even better example:

foo = 1
bar = foo
baz = foo

In practice, Python reuses the same object for integers with common values like 0 or 1, so the first example should bind the same object to all three names. But this example is crystal clear: the same object is bound to foo, bar, and baz.

Best way to store a key=>value array in JavaScript?

Simply do this

var key = "keyOne";
var obj = {};
obj[key] = someValue;

How do I make the text box bigger in HTML/CSS?

Try this:

#signin input {
    background-color:#FFF;
    height: 1.5em;
    /* or */
    line-height: 1.5em;
}

Regular Expression to select everything before and up to a particular text

After executing the below regex, your answer is in the first capture.

/^(.*?)\.txt/

Java - How to create new Entry (key, value)

Why Map.Entry? I guess something like a key-value pair is fit for the case.

Use java.util.AbstractMap.SimpleImmutableEntry or java.util.AbstractMap.SimpleEntry

What's the Use of '\r' escape sequence?

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.

The cursor is the position where the next characters will be rendered.

So, printing a \r allows to override the current line of the terminal emulator.

Tom Zych figured why the output of your program is o world while the \r is at the end of the line and you don't print anything after that:

When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world.

The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r has no effect.

See https://en.wikipedia.org/wiki/Carriage_return

Here is a usage example of \r:

#include <stdio.h>
#include <unistd.h>

int main()
{
        char chars[] = {'-', '\\', '|', '/'};
        unsigned int i;

        for (i = 0; ; ++i) {
                printf("%c\r", chars[i % sizeof(chars)]);
                fflush(stdout);
                usleep(200000);
        }

        return 0;
}

It repeatedly prints the characters - \ | / at the same position to give the illusion of a rotating | in the terminal.

How to run bootRun with spring profile via gradle task

Kotlin edition: Define the following task in you build.gradle.kts file:

tasks.named<BootRun>("bootRun") {
  args("--spring.profiles.active=dev")
}

This will pass the parameter --spring.profiles.active=dev to bootRun, where the profile name is dev in this case.

Every time you run gradle bootRun the profile dev is used.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I was having the same problem. Turns out in my case, I was missing the comma after the last column. 30 minutes of my life wasted, I will never get back!

enter image description here

Launch Image does not show up in my iOS App

This is worked for me. Click LaunchScreen.storyboard then in the right panel you can select "Is Initial View Controller" check box.

LaunchScreen.storyboard -> Is Initial View Controller

Create a new line in Java's FileWriter

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out is also instance of PrintStream).

Contains method for a slice

The go style:

func Contains(n int, match func(i int) bool) bool {
    for i := 0; i < n; i++ {
        if match(i) {
            return true
        }
    }
    return false
}


s := []string{"a", "b", "c", "o"}
// test if s contains "o"
ok := Contains(len(s), func(i int) bool {
    return s[i] == "o"
})

Not receiving Google OAuth refresh token

The refresh_token is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh_token again. :)

  1. Go to the page showing Apps with access to your account: https://myaccount.google.com/u/0/permissions.
  2. Under the Third-party apps menu, choose your app.
  3. Click Remove access and then click Ok to confirm
  4. The next OAuth2 request you make will return a refresh_token (providing that it also includes the 'access_type=offline' query parameter.

Alternatively, you can add the query parameters prompt=consent&access_type=offline to the OAuth redirect (see Google's OAuth 2.0 for Web Server Applications page).

This will prompt the user to authorize the application again and will always return a refresh_token.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

how to display a javascript var in html body

Use document.write().

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    var number = 123;_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <h1>_x000D_
      the value for number is:_x000D_
      <script type="text/javascript">_x000D_
        document.write(number)_x000D_
      </script>_x000D_
    </h1>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

How to copy a file to multiple directories using the gnu cp command

No - you cannot.

I've found on multiple occasions that I could use this functionality so I've made my own tool to do this for me.

http://github.com/ddavison/branch

pretty simple -
branch myfile dir1 dir2 dir3

How to detect lowercase letters in Python?

There are many methods to this, here are some of them:

  1. Using the predefined str method islower():

    >>> c = 'a'
    >>> c.islower()
    True
    
  2. Using the ord() function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:

    >>> c = 'a'
    >>> ord(c) in range(97, 123)
    True
    
  3. Checking if the letter is equal to it's lowercase form:

    >>> c = 'a'
    >>> c.lower() == c
    True
    
  4. Checking if the letter is in the list ascii_lowercase of the string module:

    >>> from string import ascii_lowercase
    >>> c = 'a'
    >>> c in ascii_lowercase
    True
    

But that may not be all, you can find your own ways if you don't like these ones: D.

Finally, let's start detecting:

d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]

# here i used islower() because it's the shortest and most-reliable
# one (being a predefined function), using this list comprehension
# is (probably) the most efficient way of doing this

Missing styles. Is the correct theme chosen for this layout?

This is very late but i like to share my experience this same issue. i face the same issue in Android studio i tried to some other solution that i found in internet but nothing works for me unless i REBUILD THE PROJECT and it solve my issue.

Hope this will works for you too.

Happy coding.

How to fix HTTP 404 on Github Pages?

My pages also kept 404'ing. Contacted support, and they pointed out that the url is case sensitive; solved my issue.

Ways to insert javascript into URL?

I don't believe you can hack via the URL. Someone could try to inject code into your application if you are passing parameters (either GET or POST) into your app so your avoidance is going to be very similar to what you'd do for a local application.

Make sure you aren't adding parameters to SQL or other script executions that were passed into the code from the browser without making sure the strings don't contain any script language. Search the next for details about injection attacks for the development platform you are working with, that should yield lots of good advice and examples.

Simple pagination in javascript

So you can use a library for pagination logic https://github.com/pagino/pagino-js

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Copy all files with a certain extension from all subdirectories

I also had to do this myself. I did it via the --parents argument for cp:

find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;

How can I make my website's background transparent without making the content (images & text) transparent too?

Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...

How to find Google's IP address?

If all you are trying to do is find the IP address that corresponds to a domain name, like google.com, this is very easy on every machine connected to the Internet.

Simply run the ping command from any command prompt. Typing something like

ping google.com

will give you (among other things) that information.

Convert JsonObject to String

JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;

How to disable text selection highlighting

You may also want to prevent the context menu appearing when touching elements like buttons that have their selection prevented. To do that, add this code to the entire page, or just those button elements:

$("body").on("contextmenu",function(e){
    return false;
});

Capturing a form submit with jquery and .submit

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var form = $('#login_form')[0];_x000D_
  form.onsubmit = function(e){_x000D_
  var data = $("#login_form :input").serializeArray();_x000D_
  console.log(data);_x000D_
  $.ajax({_x000D_
  url: "the url to post",_x000D_
  data: data,_x000D_
  processData: false,_x000D_
  contentType: false,_x000D_
  type: 'POST',_x000D_
  success: function(data){_x000D_
    alert(data);_x000D_
  },_x000D_
  error: function(xhrRequest, status, error) {_x000D_
    alert(JSON.stringify(xhrRequest));_x000D_
  }_x000D_
});_x000D_
    return false;_x000D_
  }_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
    <label>Username:</label>_x000D_
    <input type="text" name="username" id="username"/>_x000D_
    <label>Password:</label>_x000D_
    <input type="password" name="password" id="password"/>_x000D_
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

If you got this error trying to add a component to Visual Studio,- Microsoft.VisualStudio.TemplateWizardInterface - (after trying to install weird development tools)

consider this solution(courtesy of larocha (thanks, whoever you are)):

  1. Open C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe.config in a text editor
  2. Find this string: "Microsoft.VisualStudio.TemplateWizardInterface"
  3. Comment out the element so it looks like this:

<dependentAssembly>
<!-- assemblyIdentity name="Microsoft.VisualStudio.TemplateWizardInterface" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" / -->
<bindingRedirect oldVersion="0.0.0.0-8.9.9.9" newVersion="9.0.0.0" />
</dependentAssembly>

source: http://webclientguidance.codeplex.com/workitem/15444

android: changing option menu items programmatically

Try this code:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    this.menu=menu;
    updateMenuItems(menu);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.document_list_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    if (item.getItemId() == android.R.id.home) {
        onHomeButtonPresssed();
    }else if (item.getItemId() == R.id.action_delete) {
        useCheckBoxAdapter=false;
        deleteDocuments();
    } else if (item.getItemId() == R.id.share) {
        useCheckBoxAdapter=false;
        shareDocuments();
    } else if (item.getItemId() == R.id.action_tick) {
        useCheckBoxAdapter=true;
        onShowCheckboxes();
    }
    updateMenuItems(menu);
    return true;
}

private void updateMenuItems(Menu menu){
    if (useCheckBoxAdapter && menu != null) {
        menu.findItem(R.id.action_delete).setVisible(true);
        menu.findItem(R.id.share).setVisible(true);
        menu.findItem(R.id.action_tick).setVisible(false);
    } else {
        menu.findItem(R.id.action_delete).setVisible(false);
        menu.findItem(R.id.share).setVisible(false);
        menu.findItem(R.id.action_tick).setVisible(true);
    }
    invalidateOptionsMenu();
}

Reading NFC Tags with iPhone 6 / iOS 8

The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

var session: NFCNDEFReaderSession? 
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

Then we need to start the session by:

session?.begin()

and when done:

session?.invalidate()

The delegate (which self should implement) has basically two functions:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)

here is my reference Apple docs

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

First I tried

lsof -wni tcp:5432 but it doesn't show any PID number.

Second I tried

Postgres -D /usr/local/var/postgres and it showed that server is listening.

So I just restarted my mac to restore all ports back and it worked for me.

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

inherit from two classes in C#

You can define a base class for A and B where you can hold a common methods/properties/fields of those.

After implement C:Base.

Or in order to simulate multiple inheritance, define a common interface(s) and implement them in C

Hope this helps.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

Check with jquery if div has overflowing elements

So I used the overflowing jquery library: https://github.com/kevinmarx/overflowing

After installing the library, if you want to assign the class overflowing to all overflowing elements, you simply run:

$('.targetElement').overflowing('.parentElement')

This will then give the class overflowing, as in <div class="targetElement overflowing"> to all elements that are overflowing. You could then add this to some event handler(click, mouseover) or other function that will run the above code so that it updates dynamically.

insert/delete/update trigger in SQL server

Not possible, per MSDN:

You can have the same code execute for multiple trigger types, but the syntax does not allow for multiple code blocks in one trigger:

Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ NOT FOR REPLICATION ] 
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

What is the best way to remove the first element from an array?

To sum up, the quick linkedlist method:

List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

jquery: get id from class selector

Nothing from this examples , works for me

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });

HTTP Error 404 when running Tomcat from Eclipse

It is because there is no default ROOT web application. When you create some web app and deploy it to Tomcat using Eclipse, then you will be able to access it with the URL in the form of

http://localhost:8080/YourWebAppName

where YourWebAppName is some name you give to your web app (the so called application context path).

Quote from Jetty Documentation Wiki (emphasis mine):

The context path is the prefix of a URL path that is used to select the web application to which an incoming request is routed. Typically a URL in a Java servlet server is of the format http://hostname.com/contextPath/servletPath/pathInfo, where each of the path elements may be zero or more / separated elements. If there is no context path, the context is referred to as the root context.


If you still want the default app which is accessed with the URL of the form

http://localhost:8080

or if you change the default 8080 port to 80, then just

http://localhost

i.e. without application context path read the following (quote from Tutorial: Installing Tomcat 7 and Using it with Eclipse, emphasis mine):

Copy the ROOT (default) Web app into Eclipse. Eclipse forgets to copy the default apps (ROOT, examples, docs, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps and copy the ROOT folder. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like C:\your-eclipse-workspace-location\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Modify SVG fill color when being served as Background-Image

You can use CSS masks, With the 'mask' property, you create a mask that is applied to an element.

.icon {
    background-color: red;
    -webkit-mask-image: url(icon.svg);
    mask-image: url(icon.svg);
}

For more see this great article: https://codepen.io/noahblon/post/coloring-svgs-in-css-background-images

What is the proper way to display the full InnerException?

You can simply print exception.ToString() -- that will also include the full text for all the nested InnerExceptions.

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

Add an element to an array in Swift

Here is a small extension if you wish to insert at the beginning of the array without loosing the item at the first position

extension Array{
    mutating func appendAtBeginning(newItem : Element){
        let copy = self
        self = []
        self.append(newItem)
        self.appendContentsOf(copy)
    }
}

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc
});

How do I uniquely identify computers visiting my web site?

Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.

I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.

Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).

A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.

Hope that helps.

jQuery - get all divs inside a div with class ".container"

To set the class when clicking on a div immediately within the .container element, you could use:

<script>
$('.container>div').click(function () {
        $(this).addClass('whatever')
    });
</script>

How to read line by line of a text area HTML tag

Try this.

var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
    //code here using lines[i] which will give you each line
}

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

How to subtract 30 days from the current datetime in mysql?

If you only need the date and not the time use:

select*from table where exec_datetime
between subdate(curdate(), 30)and curdate();

Since curdate() omits the time component, it's potentially faster than now() and more "semantically correct" in cases where you're only interested in the date.

Also, subdate()'s 2-arity overload is potentially faster than using interval. interval is meant to be for cases when you need a non-day component.

Adding blank spaces to layout

The previous answers didn't work in my case. However, creating an empty item in the menu does.

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
  ...
  <item />
  ...
</menu>

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

You can also use inline assembly like this:

int i;

__asm {
    mov eax, 00000000000000000000000000000000b
    mov i,   eax
}

std::cout << i;

Okay, it might be somewhat overkill, but it works.

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

console.log timestamps in Chrome?

If you want to preserve line number information (each message pointing to its .log() call, not all pointing to our wrapper), you have to use .bind(). You can prepend an extra timestamp argument via console.log.bind(console, <timestamp>) but the problem is you need to re-run this every time to get a function bound with a fresh timestamp. An awkward way to do that is a function that returns a bound function:

function logf() {
  // console.log is native function, has no .bind in some browsers.
  // TODO: fallback to wrapping if .bind doesn't exist...
  return Function.prototype.bind.call(console.log, console, yourTimeFormat());
}

which then has to be used with a double call:

logf()(object, "message...")

BUT we can make the first call implicit by installing a property with getter function:

var origLog = console.log;
// TODO: fallbacks if no `defineProperty`...
Object.defineProperty(console, "log", {
  get: function () { 
    return Function.prototype.bind.call(origLog, console, yourTimeFormat()); 
  }
});

Now you just call console.log(...) and automagically it prepends a timestamp!

> console.log(12)
71.919s 12 VM232:2
undefined
> console.log(12)
72.866s 12 VM233:2
undefined

You can even achieve this magical behavior with a simple log() instead of console.log() by doing Object.defineProperty(window, "log", ...).


See https://github.com/pimterry/loglevel for a well-done safe console wrapper using .bind(), with compatibility fallbacks.

See https://github.com/eligrey/Xccessors for compatibility fallbacks from defineProperty() to legacy __defineGetter__ API. If neither property API works, you should fallback to a wrapper function that gets a fresh timestamp every time. (In this case you lose line number info, but timestamps will still show.)


Boilerplate: Time formatting the way I like it:

var timestampMs = ((window.performance && window.performance.now) ?
                 function() { return window.performance.now(); } :
                 function() { return new Date().getTime(); });
function formatDuration(ms) { return (ms / 1000).toFixed(3) + "s"; }
var t0 = timestampMs();
function yourTimeFormat() { return formatDuration(timestampMs() - t0); }

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

Overlay a background-image with an rgba background-color

I've gotten the following to work:

html {
  background:
      linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
      url('bgimage.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

The above will produce a nice opaque blue overlay.

Difference Between Cohesion and Coupling

Cohesion in software engineering is the degree to which the elements of a certain module belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

I wrote a blog post about this, if you want to read up in a little bit more details with examples and drawings. I think it answers most of your questions.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Unfortunately the web.config setting is ignored by the default JsonResult implementation. So I guess you will need to implement a custom json result to overcome this issue.

Why won't bundler install JSON gem?

For macOS Sierra:

I ran into this error When i used bundler(v1.15.3) in Rails(v4.2) project. The solution for me is gem uninstall bundler -v '1.15.3' and gem install bundler -v '1.14.6'.

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

Find an element in DOM based on an attribute value

Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector and querySelectorAll, see Wojtek's answer for how to do this.

There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.


There's not a very short way to do this in vanilla javascript, but there are some solutions available.

You do something like this, looping through elements and checking the attribute

If a library like jQuery is an option, you can do it a bit easier, like this:

$("[myAttribute=value]")

If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):

$("[myAttribute='my value']")

You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.

Check if a Python list item contains a string inside another string

for item in my_list:
    if item.find("abc") != -1:
        print item

Get PostGIS version

Did you try using SELECT PostGIS_version();

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

Merge or combine by rownames

you can wrap -Andrie answer into a generic function

mbind<-function(...){
 Reduce( function(x,y){cbind(x,y[match(row.names(x),row.names(y)),])}, list(...) )
}

Here, you can bind multiple frames with rownames as key

How to force maven update?

If you are using eclipse IDE then :

  • Select Project.
  • Press alt+F5, window for Update Maven Project will pop up.

  • Check - Force Update of Snapshots/releases and click OK.

If Using Intellij IDE

  • go to settings/Maven
  • check Always update snapshots

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I had a problem like this when I deleted a folder (and sub-folders) and went to recreate them from scratch. You get this error from manually deleting and re-adding folders (whereas files seem to cope OK with this).

After some frustrating messing around, found I had to:
(using TortoiseSVN on Windows)

  1. Move conflicting folders out of working copy (so that I don't lose my work-in-progress)
  2. Do an svn update which added old files/folders back into working copy
  3. svn delete folder
  4. commit
  5. Copy new folder back into working copy (ensuring you delete all the .svn folders inside)
  6. commit

Unfortunately it (A) requires two commits, and (B) loses file revision history as it only tracks back to the recent re-add (unless someone can explain how to fix this). An alternative solution that works around these 2 issues is to skip steps 3 and 4, the only problem being that old/unnecessary files may still be present in your directory. You could delete these manually.

Would love to hear any additional insights others might have on this.

Simon.


[Update] OK, I had this same problem again just then, but the offending folder was NOT in the last commit, so an update didn't restore it. Instead I had to browse the repository and delete the offending folder. I could then add the folder back in and commit successfully.

Can constructors throw exceptions in Java?

Yes.

Constructors are nothing more than special methods, and can throw exceptions like any other method.

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

lexical or preprocessor issue file not found occurs while archiving?

I had this same issue now and found that my sub-projects 'Public Header Folder Path' was set to an incorrect path (when compared with what my main project was using as its 'Header Search Path' and 'User Header Search Path').

e.g.

My main project had the following:

  • Header Search Paths
    • Debug "build/Debug-iphoneos/../../Headers"
    • Release "build/Debug-iphoneos/../../Headers"

And the same for the User Header Search Paths


Whereas my sub-project (dependency) had the following:

  • Public Header Folder Path
    • Debug "include/BoxSDK"
    • Release "include/BoxSDK"

Changing the 'Public Header Folder Path' to "../../Headers/BoxSDK" fixed the problem since the main project was already searching that folder ('../../Headers').

PS: I took some good screenshots, but I am not allowed to post an answer with images until I hit reputation 10 :(

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

PHP substring extraction. Get the string before the first '/' or the whole string

Using current on explode would ease the process.

 $str = current(explode("/", $str, 2));

How can I change an element's class with JavaScript?

Here is simple jQuery code to do that.

$(".class1").click(function(argument) {
    $(".parentclass").removeClass("classtoremove");
    setTimeout(function (argument) {
        $(".parentclass").addClass("classtoadd");
    }, 100);
});

Here,

  • Class1 is a listener for an event.
  • The parent class is the class which hosts the class you want to change
  • Classtoremove is the old class you have.
  • Class to add is the new class that you want to add.
  • 100 is the timeout delay during which the class is changed.

Good Luck.

Setting width and height

You can change the aspectRatio according to your needs:

options:{
     aspectRatio:4 //(width/height)
}

Copy files without overwrite

There is an odd way to do this with xcopy:

echo nnnnnnnnnnn | xcopy /-y source target

Just include as many n's as files you're copying, and it will answer n to all of the overwrite questions.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Merge (Concat) Multiple JSONObjects in Java

If you want a new object with two keys, Object1 and Object2, you can do:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

If you want to merge them, so e.g. a top level object has 5 keys (Stringkey1, ArrayKey, StringKey2, StringKey3, StringKey4), I think you have to do that manually:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

This would be a lot easier if JSONObject implemented Map, and supported putAll.

How to delete columns in numpy.array

>>> A = array([[ 1,  2,  3,  4],
               [ 5,  6,  7,  8],
               [ 9, 10, 11, 12]])

>>> A = A.transpose()

>>> A = A[1:].transpose()

Can a Windows batch file determine its own file name?

Yes.

Use the special %0 variable to get the path to the current file.

Write %~n0 to get just the filename without the extension.

Write %~n0%~x0 to get the filename and extension.

Also possible to write %~nx0 to get the filename and extension.

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

NSDictionary to NSArray?

This code is actually used to add values to the dictionary and through the data to an Array According to the Key.

NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);

Increase number of axis ticks

You can override ggplots default scales by modifying scale_x_continuous and/or scale_y_continuous. For example:

library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))

ggplot(dat, aes(x,y)) +
  geom_point()

Gives you this:

enter image description here

And overriding the scales can give you something like this:

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks = round(seq(min(dat$x), max(dat$x), by = 0.5),1)) +
  scale_y_continuous(breaks = round(seq(min(dat$y), max(dat$y), by = 0.5),1))

enter image description here

If you want to simply "zoom" in on a specific part of a plot, look at xlim() and ylim() respectively. Good insight can also be found here to understand the other arguments as well.

Is there any way to have a fieldset width only be as wide as the controls in them?

Going further of Mihai solution, cross-browser left aligned:

<TABLE>
  <TR>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

Cross-browser right aligned:

<TABLE>
  <TR>
    <TD WIDTH=100%></TD>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Materialize CSS - Select Doesn't Seem to Render

I found myself in a situation where using the solution selected

$(document).ready(function() {
$('select').material_select();
}); 

for whatever reason was throwing errors because the material_select() function could not be found. It was not possible to just say <select class="browser-default... Because I was using a framework which auto-rendered the the forms. So my solution was to add the class using js(Jquery)

<script>
 $(document).ready(function() {
   $('select').attr("class", "browser-default")
});

Can a website detect when you are using Selenium with chromedriver?

Some sites are detecting this:

function d() {
try {
    if (window.document.$cdc_asdjflasutopfhvcZLmcfl_.cache_)
        return !0
} catch (e) {}

try {
    //if (window.document.documentElement.getAttribute(decodeURIComponent("%77%65%62%64%72%69%76%65%72")))
    if (window.document.documentElement.getAttribute("webdriver"))
        return !0
} catch (e) {}

try {
    //if (decodeURIComponent("%5F%53%65%6C%65%6E%69%75%6D%5F%49%44%45%5F%52%65%63%6F%72%64%65%72") in window)
    if ("_Selenium_IDE_Recorder" in window)
        return !0
} catch (e) {}

try {
    //if (decodeURIComponent("%5F%5F%77%65%62%64%72%69%76%65%72%5F%73%63%72%69%70%74%5F%66%6E") in document)
    if ("__webdriver_script_fn" in document)
        return !0
} catch (e) {}

Adding items to end of linked list

public static Node insertNodeAtTail(Node head,Object data) {
               Node node = new Node(data);
                 node.next = null;
                if (head == null){
                    return node;
                }
                else{
                    Node temp = head;
                    while(temp.next != null){
                        temp = temp.next;
                    }
                    temp.next = node; 
                    return head;
                }        
    }

How to copy a selection to the OS X clipboard

Visually select the text and type:

ggVG
!tee >(pbcopy)

Which I find nicer than:

ggVG
:w !pbcopy

Since it doesn't flash up a prompt: "Press ENTER or type command to continue"

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

How to change lowercase chars to uppercase using the 'keyup' event?

I success use this code to change uppercase

$(document).ready(function(){
$('#kode').keyup(function()
{
    $(this).val($(this).val().toUpperCase());
});
});
</script>

in your html tag bootstraps

<div class="form-group">
                            <label class="control-label col-md-3">Kode</label>
                            <div class="col-md-9 col-sm-9 col-xs-12">
                                <input name="kode" placeholder="Kode matakul" id="kode" class="form-control col-md-7 col-xs-12" type="text" required="required" maxlength="15">
                                <span class="fa fa-user form-control-feedback right" aria-hidden="true"></span>
                            </div>
                        </div>

How to use responsive background image in css3 in bootstrap

You need to use background-size: 100% 100%;

Demo

Demo 2 (Won't stretch, this is what you are doing)

Explanation: You need to use 100% 100% as it sets for X AS WELL AS Y, you are setting 100% just for the X parameter, thus the background doesn't stretch vertically.


Still, the image will stretch out, it won't be responsive, if you want to stretch the background proportionately, you can look for background-size: cover; but IE will create trouble for you here as it's CSS3 property, but yes, you can use CSS3 Pie as a polyfill. Also, using cover will crop your image.

What is an unsigned char?

An unsigned char uses the bit that is reserved for the sign of a regular char as another number. This changes the range to [0 - 255] as opposed to [-128 - 127].

Generally unsigned chars are used when you don't want a sign. This will make a difference when doing things like shifting bits (shift extends the sign) and other things when dealing with a char as a byte rather than using it as a number.

Generate a random letter in Python

A summary and improvement of some of the answers.

import numpy as np
n = 5
[chr(i) for i in np.random.randint(ord('a'), ord('z') + 1, n)]
# ['b', 'f', 'r', 'w', 't']

Scanner vs. StringTokenizer vs. String.Split

They're essentially horses for courses.

  • Scanner is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression.
  • String.split() and Pattern.split() give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.
  • StringTokenizer is even more restrictive than String.split(), and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as String.split(). (See my comparison of String.split() and StringTokenizer.) It also predates the regular expressions API, of which String.split() is a part.

You'll note from my timings that String.split() can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage over StringTokenizer that it gives you the output as a string array, which is usually what you want. Using an Enumeration, as provided by StringTokenizer, is too "syntactically fussy" most of the time. From this point of view, StringTokenizer is a bit of a waste of space nowadays, and you may as well just use String.split().

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
    public int s_id;
    public String s_name, c_name, dob;
}
class Program
{
    static void Main(string[] args)
    {
        student[] arr = new student[4];

        for(int i = 0; i < 4; i++)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");


            arr[i].s_id = Int32.Parse(Console.ReadLine());
            arr[i].s_name = Console.ReadLine();
            arr[i].c_name = Console.ReadLine();
            arr[i].s_dob = Console.ReadLine();
       }
    }
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

Regex to get NUMBER only from String

The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342

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

As seen on WWDC 2016/XCode 8 (what's new in LLVM session @5:05). Class properties can be declared as follows

@interface MyType : NSObject
@property (class) NSString *someString;
@end

NSLog(@"format string %@", MyType.someString);

Note that class properties are never synthesized

@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end

Change Twitter Bootstrap Tooltip content on click

This works if the tooltip has been instantiated (possibly with javascript):

$("#tooltip_id").data('tooltip').options.title="New_value!";
$("#tooltip_id").tooltip('hide').tooltip('show');

What is the quickest way to HTTP GET in Python?

You could use a library called requests.

import requests
r = requests.get("http://example.com/foo/bar")

This is quite easy. Then you can do like this:

>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)

Python: convert string from UTF-8 to Latin-1

Instead of .encode('utf-8'), use .encode('latin-1').

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

Return from lambda forEach() in java

If you want to return a boolean value, then you can use something like this (much faster than filter):

players.stream().anyMatch(player -> player.getName().contains(name));

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

You can pass via GET. So if you want to pass the value foobar from PageA.php to PageB.php, call it as PageB.php?value=foobar.

In PageB.php, you can access it this way:

$value = $_GET['value'];

How to check queue length in Python

Yes we can check the length of queue object created from collections.

from collections import deque
class Queue():
    def __init__(self,batchSize=32):
        #self.batchSie = batchSize
        self._queue = deque(maxlen=batchSize)

    def enqueue(self, items):
        ''' Appending the items to the queue'''
        self._queue.append(items)

    def dequeue(self):
        '''remoe the items from the top if the queue becomes full '''
        return self._queue.popleft()

Creating an object of class

q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])

Now retrieving the length of the queue

#check the len of queue
print(len(q._queue)) 
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item 
print(len(q.dequeue()))

check the results in attached screen shot

enter image description here

Hope this helps...

foreach loop in angularjs

Change the line into this

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value);
 });

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value.Name);
 });

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Solution it's quite simple

Just enable Builds for iOS 8 and Later

enter image description here

How to import multiple .csv files at once?

Using purrr and including file IDs as a column:

library(tidyverse)


p <- "my/directory"
files <- list.files(p, pattern="csv", full.names=TRUE) %>%
    set_names()
merged <- files %>% map_dfr(read_csv, .id="filename")

Without set_names(), .id= will use integer indicators, instead of actual file names.

If you then want just the short filename without the full path:

merged <- merged %>% mutate(filename=basename(filename))

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6 then install pyaudio

It works

Read whole ASCII file into C++ std::string

I could do it like this:

void readfile(const std::string &filepath,std::string &buffer){
    std::ifstream fin(filepath.c_str());
    getline(fin, buffer, char(-1));
    fin.close();
}

If this is something to be frowned upon, please let me know why

Check object empty

I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.

To check for Collection be empty or null

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

or use Apache Commons CollectionUtils.isEmpty()

To check if Map is empty or null

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

or use Apache Commons MapUtils.isEmpty()

To check for String empty or null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

or use Apache Commons StringUtils.isBlank()

To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.

How to create an executable .exe file from a .m file

Try:

mcc -m yourfile

Also see help mcc

Two onClick actions one button

Give your button an id something like this:


<input id="mybutton" type="button" value="Dont show this again! " />

Then use jquery (to make this unobtrusive) and attach click action like so:


$(document).ready(function (){
    $('#mybutton').click(function (){
       fbLikeDump();
       WriteCookie();
    });
});

(this part should be in your .js file too)

I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>

The reason to add just before body closing tag is for performance of perceived page loading times

Dataframe to Excel sheet

I tested the previous answers found here: Assuming that we want the other four sheets to remain, the previous answers here did not work, because the other four sheets were deleted. In case we want them to remain use xlwings:

import xlwings as xw
import pandas as pd

filename = "test.xlsx"

df = pd.DataFrame([
    ("a", 1, 8, 3),
    ("b", 1, 2, 5),
    ("c", 3, 4, 6),
    ], columns=['one', 'two', 'three', "four"])

app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["Sheet5"]

ws.clear()
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df

# If formatting of column names and index is needed as xlsxwriter does it, 
# the following lines will do it (if the dataframe is not multiindex).
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2

wb.save(filename)
app.quit()

Passing 'this' to an onclick event

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>?

var foo = function()
{
    this.innerHTML = "Not a button";
};

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just do it in the Base, that way any child can be Serialized, less code cleaner code.

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.

How to add multiple classes to a ReactJS Component?

You can use arrays and then join them using space.

<li key={index} className={[activeClass, data.class, "main-class"].join(' ')}></li>

This will result in :

<li key={index} class="activeClass data.class main-class"></li>

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

CodeIgniter htaccess and URL rewrite issues

There are 3 steps to remove index.php.

  1. Make below changes in application/config.php file

    $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name';
    $config['index_page'] = '';
    $config['uri_protocol'] = 'AUTO';
    
  2. Make .htaccess file in your root directory using below code

    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    
  3. Enable the rewrite engine (if not already enabled)

    i. First, initiate it with the following command:

    a2enmod rewrite
    

    ii. Edit the file /etc/apache2/sites-enabled/000-default

    Change all AllowOverride None to AllowOverride All.

    Note: In latest version you need to change in /etc/apache2/apache2.conf file

    iii. Restart your server with the following command:

    sudo /etc/init.d/apache2 restart
    

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

How to read first N lines of a file?

For first 5 lines, simply do:

N=5
with open("data_file", "r") as file:
    for i in range(N):
       print file.next()

The difference in months between dates in MySQL

PERIOD_DIFF calculates months between two dates.

For example, to calculate the difference between now() and a time column in your_table:

select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;

Get the content of a sharepoint folder with Excel VBA

Mapping the WebDAV folder is my preferred method of creating an easily accessible, long-term connection to SharePoint. However, you'll find—even when properly mapped—that a file will return a URL when selected (especially via Application.FileDialog) due to changes in Windows 10 1803.

To circumvent this, you can map the drive using DriveMapper (or an equivalent) and then combine the resulting Application.FileDialog.SelectedItems with a URL to UNC converter function:

Public Function SharePointURLtoUNC( _
  sURL As String) _
As String
  Dim bIsSSL As Boolean

  bIsSSL = InStr(1, sURL, "https:") > 0
  sURL = Replace(Replace(sURL, "/", "\"), "%20", " ")
  sURL = Replace(Replace(sURL, "https:", vbNullString), "http:", vbNullString)
  
  sURL= Replace(sURL, Split(sURL, "\")(2), Split(sURL, "\")(2) & "@SSL\DavWWWRoot")
  If Not bIsSSL Then sURL = Replace(sURL, "@SSL\", vbNullString) 
  SharePointURLtoUNC = sURL
End Function

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Ansible: copy a directory content to another directory

I got involved whole a day, too! and finally found the solution in shell command instead of copy: or command: as below:

- hosts: remote-server-name
  gather_facts: no
  vars:
    src_path: "/path/to/source/"
    des_path: "/path/to/dest/"
  tasks:
  - name: Ansible copy files remote to remote
    shell: 'cp -r {{ src_path }}/. {{ des_path }}'

strictly notice to: 1. src_path and des_path end by / symbol 2. in shell command src_path ends by . which shows all content of directory 3. I used my remote-server-name both in hosts: and execute shell section of jenkins, instead of remote_src: specifier in playbook.

I guess it is a good advice to run below command in Execute Shell section in jenkins:

ansible-playbook  copy-payment.yml -i remote-server-name

Open new Terminal Tab from command line (Mac OS X)

I added these to my .bash_profile so I can have access to tabname and newtab

tabname() {
  printf "\e]1;$1\a"
}

new_tab() {
  TAB_NAME=$1
  COMMAND=$2
  osascript \
    -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"printf '\\\e]1;$TAB_NAME\\\a'; $COMMAND\" in front window" \
    -e "end tell" > /dev/null
}

So when you're on a particular tab you can just type

tabname "New TabName"

to organize all the open tabs you have. It's much better than getting info on the tab and changing it there.

How to group by month from Date field using sql

SQL Server 2012 version above,

SELECT  format(Closing_Date,'yyyy-MM') as ClosingMonth,
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY format(Closing_Date,'yyyy-MM'), Category;

How to use wget in php?

This method is only one class and doesn't require importing other libraries or reusing code.

Personally I use this script that I made a while ago. Located here but for those who don't want to click on that link you can view it below. It lets the developer use the static method HTTP::GET($url, $options) to use the get method in curl while being able to pass through custom curl options. You can also use HTTP::POST($url, $options) but I hardly use that method.

/**
  *  echo HTTP::POST('http://accounts.kbcomp.co',
  *      array(
  *            'user_name'=>'[email protected]',
  *            'user_password'=>'demo1234'
  *      )
  *  );
  *  OR
  *  echo HTTP::GET('http://api.austinkregel.com/colors/E64B3B/1');
  *                  
  */

class HTTP{
   public static function GET($url,Array $options=array()){
    $ch = curl_init();
    if(count($options>0)){
       curl_setopt_array($ch, $options);
       curl_setopt($ch, CURLOPT_URL, $url);
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
     }
   }
   public static function POST($url, $postfields, $options = null){
       $ch = curl_init();
       $options = array(
          CURLOPT_URL=>$url,
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_POSTFIELDS => $postfields,
          CURLOPT_HEADER => true
          //CURLOPT_HTTPHEADER, array('Content-Type:application/json')
          ); 
       if(count($options>0)){
           curl_setopt_array($ch, $options);
       }
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
   }
}

SQL Server 2008 - Help writing simple INSERT Trigger

cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.

You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.

Continue For loop

For i=1 To 10
    Do 
        'Do everything in here and

        If I_Dont_Want_Finish_This_Loop Then
            Exit Do
        End If 

        'Of course, if I do want to finish it,
        'I put more stuff here, and then...

    Loop While False 'quit after one loop
Next i

Why do we need boxing and unboxing in C#?

Boxing is the conversion of a value to a reference type with the data at some offset in an object on the heap.

As for what boxing actually does. Here are some examples

Mono C++

void* mono_object_unbox (MonoObject *obj)
 {    
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
 }

#define MONO_EXTERNAL_ONLY_GC_UNSAFE(t, expr) \
    t result;       \
    MONO_ENTER_GC_UNSAFE;   \
    result = expr;      \
    MONO_EXIT_GC_UNSAFE;    \
    return result;

static inline gpointer
mono_object_unbox_internal (MonoObject *obj)
{
    /* add assert for valuetypes? */
    g_assert (m_class_is_valuetype (mono_object_class (obj)));
    return mono_object_get_data (obj);
}

static inline gpointer
mono_object_get_data (MonoObject *o)
{
    return (guint8*)o + MONO_ABI_SIZEOF (MonoObject);
}

#define MONO_ABI_SIZEOF(type) (MONO_STRUCT_SIZE (type))
#define MONO_STRUCT_SIZE(struct) MONO_SIZEOF_ ## struct
#define MONO_SIZEOF_MonoObject (2 * MONO_SIZEOF_gpointer)

typedef struct {
    MonoVTable *vtable;
    MonoThreadsSync *synchronisation;
} MonoObject;

Unboxing an object in Mono is a process of casting a pointer at an offset of 2 gpointers in the object (e.g. 16 bytes). A gpointer is a void*. This makes sense when looking at the definition of MonoObject as it's clearly just a header for the data.

C++

To box a value in C++ you could do something like:

#include <iostream>
#define Object void*

template<class T> Object box(T j){
  return new T(j);
}

template<class T> T unbox(Object j){
  T temp = *(T*)j;
  delete j;
  return temp;
}

int main() {
  int j=2;
  Object o = box(j);
  int k = unbox<int>(o);
  std::cout << k;
}

How to decompile an APK or DEX file on Android platform?

You need Three Tools to decompile an APK file.

  1. Dex2jar - Tools to work with android .dex and java .class files

  2. ApkTool - A tool for reverse engineering Android apk files

  3. JD-GUI - Java Decompiler is a tools to decompile and analyze Java 5 “byte code” and the later versions.

for more how-to-use-dextojar. Hope this will help You and all! :)

How to stick text to the bottom of the page?

This is how I've done it.

_x000D_
_x000D_
#copyright {_x000D_
 float: left;_x000D_
 padding-bottom: 10px;_x000D_
 padding-top: 10px;_x000D_
 text-align: center;_x000D_
 bottom: 0px;_x000D_
 width: 100%;_x000D_
}
_x000D_
  <div id="copyright">_x000D_
  Copyright 2018 &copy; Steven Clough_x000D_
  </div>
_x000D_
_x000D_
_x000D_

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

How to store an array into mysql?

You can use the php serialize function to store array in MySQL.

<?php

$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");

$string_array = serialize($array);

echo $string_array;

?>

It’s output will be :

a:3{s:4:"Name";s:7:"Shubham";s:3:"Age";s:2:"17";s:7:"website";s:25:"http://mycodingtricks.com";}

And then you can use the php unserialize function to decode the data.

I think you should visit this page on storing array in mysql.

ASP.NET Setting width of DataBound column in GridView

hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false" and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"

How to increment datetime by custom months in python without using library

Perhaps add the number of days in the current month using calendar.monthrange()?

import calendar, datetime

def increment_month(when):
    days = calendar.monthrange(when.year, when.month)[1]
    return when + datetime.timedelta(days=days)

now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)

Run multiple python scripts concurrently

I am working in Windows 7 with Python IDLE. I have two programs,

# progA
while True:
    m = input('progA is running ')
    print (m)

and

# progB
while True:
    m = input('progB is running ')
    print (m)

I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter> and then "c" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running 

Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter> and then "y" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running 

Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.

What is the best way to use a HashMap in C++?

A hash_map is an older, unstandardized version of what for standardization purposes is called an unordered_map (originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map primarily in being unordered -- if, for example, you iterate through a map from begin() to end(), you get items in order by key1, but if you iterate through an unordered_map from begin() to end(), you get items in a more or less arbitrary order.

An unordered_map is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.

From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).


1 Where the order is defined by the third template parameter when you create the map, std::less<T> by default.

Extract time from date String

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Passing parameters to JavaScript files

If you need a way that passes CSP check (which prohibits unsafe-inline) then you have to use nonce method to add a unique value to both the script and the CSP directive or write your values into the html and read them again.

Nonce method for express.js:

const uuidv4 = require('uuid/v4')

app.use(function (req, res, next) {
  res.locals.nonce = uuidv4()
  next()
})

app.use(csp({
  directives: {
    scriptSrc: [
      "'self'",
      (req, res) => `'nonce-${res.locals.nonce}'`  // 'nonce-614d9122-d5b0-4760-aecf-3a5d17cf0ac9'
    ]
  }
}))

app.use(function (req, res) {
  res.end(`<script nonce="${res.locals.nonce}">alert(1 + 1);</script>`)
})

or write values to html method. in this case using Jquery:

<div id="account" data-email="{{user.email}}"></div>
...


$(document).ready(() => {
    globalThis.EMAIL = $('#account').data('email');
}

How to render a DateTime in a specific format in ASP.NET MVC 3?

My preference is to keep the formatting details with the view and not the viewmodel. So in MVC4/Razor:

@Html.TextBoxFor(model => model.DateTime, "{0:d}");

datetime format reference: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx

Then I have a JQuery datepicker bound to it, and that put's the date in as a different format...doh!

Looks like I need to set the datepicker's format to the same formatting.

So I'm storing the System.Globalization formatting in a data-* attribute and collecting it when setting up the

@Html.TextBoxFor(
    model => model.DateTime.Date, 
    "{0:d}", 
    new 
    { 
        @class = "datePicker", 
        @data_date_format=System.Globalization.CultureInfo
                          .CurrentUICulture.DateTimeFormat.ShortDatePattern 
    }));

And here's the sucky part: the formats of .net and datepicker do not match, so hackery is needed:

$('.datePicker').each(function(){
    $(this).datepicker({
        dateFormat:$(this).data("dateFormat").toLowerCase().replace("yyyy","yy")
    });
});

that's kind of weak, but should cover a lot of cases.

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

'negative' pattern matching in python

You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group.

Let's write python code:

string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.
"""

search_result = re.search(r"^OK.*\n((.|\s)*).", string)

if search_result:
    print(search_result.group(1))

Output is:

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

^OK.*\n will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*), so put it inside parentheses. And in the end of regexp we look for a dot ., but we also don't want to capture it.

P.S: I find this answer is super helpful to understand power of groups. https://stackoverflow.com/a/3513858/4333811

Font size relative to the user's screen resolution?

I've developed a nice JS solution - which is suitable for entirely-responsive HTML (i.e. HTML built with percentages)

  1. I use only "em" to define font-sizes.

  2. html font size is set to 10 pixels:

    html {
      font-size: 100%;
      font-size: 62.5%;
    }
    
  3. I call a font-resizing function on document-ready:

// this requires JQuery

function doResize() {
    // FONT SIZE
    var ww = $('body').width();
    var maxW = [your design max-width here];
    ww = Math.min(ww, maxW);
    var fw = ww*(10/maxW);
    var fpc = fw*100/16;
    var fpc = Math.round(fpc*100)/100;
    $('html').css('font-size',fpc+'%');
}

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Here is the pure HTML and CSS solution.

  1. We create a container box for navbar with position: fixed; height:100%;

  2. Then we create an inner box with height: 100%; overflow-y: scroll;

  3. Next, we put out content inside that box.

Here is the code:

_x000D_
_x000D_
.nav-box{_x000D_
        position: fixed;_x000D_
        border: 1px solid #0a2b1d;_x000D_
        height:100%;_x000D_
   }_x000D_
   .inner-box{_x000D_
        width: 200px;_x000D_
        height: 100%;_x000D_
        overflow-y: scroll;_x000D_
        border: 1px solid #0A246A;_x000D_
    }_x000D_
    .tabs{_x000D_
        border: 3px solid chartreuse;_x000D_
        color:darkred;_x000D_
    }_x000D_
    .content-box p{_x000D_
      height:50px;_x000D_
      text-align:center;_x000D_
    }
_x000D_
<div class="nav-box">_x000D_
  <div class="inner-box">_x000D_
    <div class="tabs"><p>Navbar content Start</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content End</p></div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="content-box">_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link to jsFiddle:

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit