Programs & Examples On #Marching cubes

An algorithm for creating a triangular mesh from a three-dimensional scalar field, or graphing an implicit function of the form f(x,y,z) = c.

How to set timer in android?

void method(boolean u,int max)
{
    uu=u;
    maxi=max;
    if (uu==true)
    { 
        CountDownTimer uy = new CountDownTimer(maxi, 1000) 
  {
            public void onFinish()
            {
                text.setText("Finish"); 
            }

            @Override
            public void onTick(long l) {
                String currentTimeString=DateFormat.getTimeInstance().format(new Date());
                text.setText(currentTimeString);
            }
        }.start();
    }

    else{text.setText("Stop ");
}

How can I get the value of a registry key from within a batch script?

Based on tryingToBeClever solution (which I happened to also stumble upon and fixed myself by trial-and-error before finding it), I also suggest passing the result output of reg query through find in order to filter undesired lines due to the ! REG.EXE VERSION x.y inconsistency. The find filtering and tokens tweaking also allows to pick exactly what we want (typically the value). Also added quotes to avoid unexpected results with key/value names containing spaces.

Final result proposed when we are only interested in fetching the value:

@echo off
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKCU\Software\Microsoft\Command Processor
set VALUE_NAME=DefaultColor
for /F "usebackq tokens=1,2,*" %%A IN (`reg query "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul ^| find "%VALUE_NAME%"`) do (
  echo %%C
)

A potential caveat of using find is that the errorlevel set by reg when errors occur is now obfuscated so one should only use this approach for keys known to be there and/or after a previous validation.

A tiny additional optimization (add skip=1 to avoid processing the first line of output) can be done in cases when the key name also contains the value name (as it is the case with HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion and CurrentVersion) but removes most flexibility so should only be used in particular use-cases.

Delayed function calls

Aside from agreeing with the design observations of the previous commenters, none of the solutions were clean enough for me. .Net 4 provides Dispatcher and Task classes which make delaying execution on the current thread pretty simple:

static class AsyncUtils
{
    static public void DelayCall(int msec, Action fn)
    {
        // Grab the dispatcher from the current executing thread
        Dispatcher d = Dispatcher.CurrentDispatcher;

        // Tasks execute in a thread pool thread
        new Task (() => {
            System.Threading.Thread.Sleep (msec);   // delay

            // use the dispatcher to asynchronously invoke the action 
            // back on the original thread
            d.BeginInvoke (fn);                     
        }).Start ();
    }
}

For context, I'm using this to debounce an ICommand tied to a left mouse button up on a UI element. Users are double clicking which was causing all kinds of havoc. (I know I could also use Click/DoubleClick handlers, but I wanted a solution that works with ICommands across the board).

public void Execute(object parameter)
{
    if (!IsDebouncing) {
        IsDebouncing = true;
        AsyncUtils.DelayCall (DebouncePeriodMsec, () => {
            IsDebouncing = false;
        });

        _execute ();
    }
}

How to view AndroidManifest.xml from APK file?

In this thread, Dianne Hackborn tells us we can get info out of the AndroidManifest using aapt.

I whipped up this quick unix command to grab the version info:

aapt dump badging my.apk | sed -n "s/.*versionName='\([^']*\).*/\1/p"

How to change TextField's height and width?

You can try the margin property in the Container. Wrap the TextField inside a Container and adjust the margin property.

new Container(
  margin: const EdgeInsets.only(right: 10, left: 10),
  child: new TextField( 
    decoration: new InputDecoration(
      hintText: 'username',
      icon: new Icon(Icons.person)),
  )
),

Find methods calls in Eclipse project

Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

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.

How to remove first 10 characters from a string?

Substring is probably what you want, as others pointed out. But just to add another option to the mix...

string result = string.Join(string.Empty, str.Skip(10));

You dont even need to check the length on this! :) If its less than 10 chars, you get an empty string.

Update values from one column in same table to another in SQL Server

UPDATE a
SET a.column1 = b.column2
FROM myTable a 
INNER JOIN myTable b
on a.myID = b.myID

in order for both "a" and "b" to work, both aliases must be defined

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

Printing tuple with string formatting in Python

Many answers given above were correct. The right way to do it is:

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

However, there was a dispute over if the '%' String operator is obsolete. As many have pointed out, it is definitely not obsolete, as the '%' String operator is easier to combine a String statement with a list data.

Example:

>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
First: 1, Second: 2, Third: 3

However, using the .format() function, you will end up with a verbose statement.

Example:

>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
>>> print 'First: {}, Second: {}, Third: {}'.format(1,2,3)
>>> print 'First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup)

First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3

Further more, '%' string operator also useful for us to validate the data type such as %s, %d, %i, while .format() only support two conversion flags: '!s' and '!r'.

Is there any way to show a countdown on the lockscreen of iphone?

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

Type List vs type ArrayList in Java

(3) Collection myCollection = new ArrayList<?>();

I am using this typically. And only if I need List methods, I will use List. Same with ArrayList. You always can switch to more "narrow" interface, but you can't switch to more "wide".

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

How to delete file from public folder in laravel 5.1

First make sure the file exist by building the path

if($request->hasFile('image')){
    $path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image;
      if(File::exists($path)){
          unlink($path);
      }

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

Class not registered Error

Somewhere in the code you are using, there is a call to the Win32 API, CoCreateInstance, to dynamically load a DLL and instantiate an object from it.

The mapping between the component ID and the DLL that is capable of instantiating that object is usually found in HEKY_CLASSES_ROOT\CLSID in the registry. To discuss this further would be to explain a lot about COM in Windows. But the error indicates that the COM guid is not present in the registry.

I don't much about what the PackAndGo DLL is (an Autodesk component), but I suspect you simply need to "install" that component or the software package it came with through the designated installer to have that DLL and appropriate COM registry keys on your computer you are trying to run your code on. (i.e. go run setup.exe for this product).

In other words, I think you need to install "Pack and Go" on this computer instead of just copying the DLL to the target machine.

Also, make sure you decide to build your code appropriate as 32-bit vs. 64-bit depending on the which build flavor (32 or 64 bit) of Pack And Go you install.

Center fixed div with dynamic width (CSS)

Here's another method if you can safely use CSS3's transform property:

.fixed-horizontal-center
{
    position: fixed;
    top: 100px; /* or whatever top you need */
    left: 50%;
    width: auto;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    transform: translateX(-50%);
}

...or if you want both horizontal AND vertical centering:

.fixed-center
{
    position: fixed;
    top: 50%;
    left: 50%;
    width: auto;
    height: auto;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

What is "loose coupling?" Please provide examples

Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)

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

then I'm dependent on the ArrayList implementation.

If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.

List<String> myList = new ArrayList<String>();

This prevents me from calling any method on myList that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.

Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.

In Windows cmd, how do I prompt for user input and use the result in another command?

Just to keep a default value of the variable. Press Enter to use default from the recent run of your .bat:

@echo off
set /p Var1=<Var1.txt
set /p Var1="Enter new value ("%Var1%") "
echo %Var1%> Var1.txt

rem YourApp %Var1%

In the first run just ignore the message about lack of file with the initial value of the variable (or do create the Var1.txt manually).

Cross-browser window resize event - JavaScript / jQuery

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

 function someFun() {
 //use your code
 }

browser resize use like these.

 $(window).on('resize', function () {
    someFun();  //call your function.
 });

How to use BOOLEAN type in SELECT statement

The answer to this question simply put is: Don't use BOOLEAN with Oracle-- PL/SQL is dumb and it doesn't work. Use another data type to run your process.

A note to SSRS report developers with Oracle datasource: You can use BOOLEAN parameters, but be careful how you implement. Oracle PL/SQL does not play nicely with BOOLEAN, but you can use the BOOLEAN value in the Tablix Filter if the data resides in your dataset. This really tripped me up, because I have used BOOLEAN parameter with Oracle data source. But in that instance I was filtering against Tablix data, not SQL query.

If the data is NOT in your SSRS Dataset Fields, you can rewrite the SQL something like this using an INTEGER parameter:

__

<ReportParameter Name="paramPickupOrders">
  <DataType>Integer</DataType>
  <DefaultValue>
    <Values>
      <Value>0</Value>
    </Values>
  </DefaultValue>
  <Prompt>Pickup orders?</Prompt>
  <ValidValues>
    <ParameterValues>
      <ParameterValue>
        <Value>0</Value>
        <Label>NO</Label>
      </ParameterValue>
      <ParameterValue>
        <Value>1</Value>
        <Label>YES</Label>
      </ParameterValue>
    </ParameterValues>
  </ValidValues>
</ReportParameter>

...

<Query>
<DataSourceName>Gmenu</DataSourceName>
<QueryParameters>
  <QueryParameter Name=":paramPickupOrders">
    <Value>=Parameters!paramPickupOrders.Value</Value>
  </QueryParameter>
<CommandText>
    where 
        (:paramPickupOrders = 0 AND ordh.PICKUP_FLAG = 'N'
        OR :paramPickupOrders = 1 AND ordh.PICKUP_FLAG = 'Y' )

If the data is in your SSRS Dataset Fields, you can use a tablix filter with a BOOLEAN parameter:

__

</ReportParameter>
<ReportParameter Name="paramFilterOrdersWithNoLoad">
  <DataType>Boolean</DataType>
  <DefaultValue>
    <Values>
      <Value>false</Value>
    </Values>
  </DefaultValue>
  <Prompt>Only orders with no load?</Prompt>
</ReportParameter>

...

<Tablix Name="tablix_dsMyData">
<Filters>
  <Filter>
    <FilterExpression>
        =(Parameters!paramFilterOrdersWithNoLoad.Value=false) 
        or (Parameters!paramFilterOrdersWithNoLoad.Value=true and Fields!LOADNUMBER.Value=0)
    </FilterExpression>
    <Operator>Equal</Operator>
    <FilterValues>
      <FilterValue DataType="Boolean">=true</FilterValue>
    </FilterValues>
  </Filter>
</Filters>

How to Use -confirm in PowerShell

Read-Host is one example of a cmdlet that -Confirm does not have an effect on.-Confirm is one of PowerShell's Common Parameters specifically a Risk-Mitigation Parameter which is used when a cmdlet is about to make a change to the system that is outside of the Windows PowerShell environment. Many but not all cmdlets support the -Confirm risk mitigation parameter.

As an alternative the following would be an example of using the Read-Host cmdlet and a regular expression test to get confirmation from a user:

$reply = Read-Host -Prompt "Continue?[y/n]"
if ( $reply -match "[yY]" ) { 
    # Highway to the danger zone 
}

The Remove-Variable cmdlet is one example that illustrates the usage of the -confirm switch.

Remove-Variable 'reply' -Confirm

Additional References: CommonParameters, Write-Host, Read-Host, Comparison Operators, Regular Expressions, Remove-Variable

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

You can use numpy.recfromcsv(filename): the types of each column will be automatically determined (as if you use np.genfromtxt() with dtype=None), and by default delimiter=",". It's basically a shortcut for np.genfromtxt(filename, delimiter=",", dtype=None) that Pierre GM pointed at in his answer.

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

How to click a link whose href has a certain substring in Selenium?

With the help of xpath locator also, you can achieve the same.

Your statement would be:

driver.findElement(By.xpath(".//a[contains(@href,'long')]")).click();

And for clicking all the links contains long in the URL, you can use:-

List<WebElement> linksList = driver.findElements(By.xpath(".//a[contains(@href,'long')]"));

for (WebElement webElement : linksList){
         webElement.click();
}

Ruby on Rails generates model field:type - what are the options for field:type?

http://guides.rubyonrails.org should be a good site if you're trying to get through the basic stuff in Ruby on Rails.

Here is a link to associate models while you generate them: http://guides.rubyonrails.org/getting_started.html#associating-models

How do I get the time difference between two DateTime objects using C#?

 var startDate = new DateTime(2007, 3, 24);

 var endDate = new DateTime(2009, 6, 26);

 var dateDiff = endDate.Subtract(startDate);

 var date = string.Format("{0} years {1} months {2} days", (int)dateDiff.TotalDays / 365, 
 (int)(dateDiff.TotalDays % 365) / 30, (int)(dateDiff.TotalDays % 365) / 30);

 Console.WriteLine(date);

Why are the Level.FINE logging messages not showing?

Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.

You might be using a ConsoleHandler (I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO. You will have to configure this handler, to publish log records of level Level.FINER and higher, for the desired outcome.

I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.

Editing the handler level

1. Using the Configuration file

The java.util.logging properties file (by default, this is the logging.properties file in JRE_HOME/lib) can be modified to change the default level of the ConsoleHandler:

java.util.logging.ConsoleHandler.level = FINER

2. Creating handlers at runtime

This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.

Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);

How to convert from int to string in objective c: example code

Dot grammar maybe more swift!

@(intValueDemo).stringValue 

for example

int intValueDemo  = 1;
//or
NSInteger intValueDemo = 1;

//So you can use dot grammar 
NSLog(@"%@",@(intValueDemo).stringValue);

load external URL into modal jquery ui dialog

EDIT: This answer might be outdated if you're using a recent version of jQueryUI.

For an anchor to trigger the dialog -

<a href="http://ibm.com" class="example">

Here's the script -

$('a.example').click(function(){   //bind handlers
   var url = $(this).attr('href');
   showDialog(url);

   return false;
});

$("#targetDiv").dialog({  //create dialog, but keep it closed
   autoOpen: false,
   height: 300,
   width: 350,
   modal: true
});

function showDialog(url){  //load content and open dialog
    $("#targetDiv").load(url);
    $("#targetDiv").dialog("open");         
}

Getting the name of a variable as a string

Maybe this could be useful:

def Retriever(bar):
    return (list(globals().keys()))[list(map(lambda x: id(x), list(globals().values()))).index(id(bar))]

The function goes through the list of IDs of values from the global scope (the namespace could be edited), finds the index of the wanted/required var or function based on its ID, and then returns the name from the list of global names based on the acquired index.

How do I ignore all files in a folder with a Git repository in Sourcetree?

Ignore full folder on source tree.

   Just Open Repository >Repository setting > Edit git ignore File and 
   you can rite some thing like this :

 *.pdb 
*.bak 
*.dll
*.lib 
.gitignore
packages/ 
*/bin/
*/obj/ 

For bin folder and obj folder just write : */bin/ */obj/

Getting View's coordinates relative to the root layout

Please use view.getLocationOnScreen(int[] location); (see Javadocs). The answer is in the integer array (x = location[0] and y = location[1]).

referenced before assignment error in python

def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

problem ended

How to use default Android drawables

Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd

Convert String into a Class Object

You cannot store a class object into a string using toString(), toString() only returns a String representation of your object-in any way you'd like. You might want to do some reading about Serialization.

delete map[key] in go?

From Effective Go:

To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.

delete(timeZone, "PDT")  // Now on Standard Time

center a row using Bootstrap 3

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</div>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</div>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</div>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

How do I set the visibility of a text box in SSRS using an expression?

=IIf((CountRows("ScannerStatisticsData")=0),False,True)

Should be replaced with

=IIf((CountRows("ScannerStatisticsData")=0),True,False)

because the Visibility expression set up the Hidden value.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

    Following code is the simple example to change the timezone
public static void main(String[] args) {
          //get time zone
          TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
          Calendar calendar = new GregorianCalendar();
          //setting required timeZone
          calendar.setTimeZone(timeZone1);
          System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));

       }

if you want see the list of timezones, here is the follwing code

public static void main(String[] args) {

    String[] ids = TimeZone.getAvailableIDs();
    for (String id : ids) {
        System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
    }

    System.out.println("\nTotal TimeZone ID " + ids.length);

}

private static String displayTimeZone(TimeZone tz) {

    long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
    long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
                              - TimeUnit.HOURS.toMinutes(hours);
    // avoid -4:-30 issue
    minutes = Math.abs(minutes);

    String result = "";
    if (hours > 0) {
        result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
    } else {
        result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
    }

    return result;

}

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

Printing with sed or awk a line following a matching pattern

Piping some greps can do it (it runs in POSIX shell and under BusyBox):

cat my-file | grep -A1 my-regexp | grep -v -- '--' | grep -v my-regexp
  1. -v will show non-matching lines
  2. -- is printed by grep to separate each match, so we skip that too

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Finding duplicate values in a SQL table

SELECT column_name,COUNT(*) FROM TABLE_NAME GROUP BY column1, HAVING COUNT(*) > 1;

Homebrew refusing to link OpenSSL

Note: this no longer works due to https://github.com/Homebrew/brew/pull/612

I had the same problem today. I uninstalled (unbrewed??) openssl 1.0.2 and installed 1.0.1 also with homebrew. Dotnet new/restore/run then worked fine.

Install openssl 101:
brew install homebrew/versions/openssl101
Linking:
brew link --force homebrew/versions/openssl101

Using LINQ to remove elements from a List<T>

To keep the code fluent (if code optimisation is not crucial) and you would need to do some further operations on the list:

authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;

or

authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;

Input text dialog Android

It's work for me

private void showForgotDialog(Context c) {
        final EditText taskEditText = new EditText(c);
        AlertDialog dialog = new AlertDialog.Builder(c)
                .setTitle("Forgot Password")
                .setMessage("Enter your mobile number?")
                .setView(taskEditText)
                .setPositiveButton("Reset", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String task = String.valueOf(taskEditText.getText());
                    }
                })
                .setNegativeButton("Cancel", null)
                .create();
        dialog.show();
    }

How to call? (Current activity name)

showForgotDialog(current_activity_name.this);

Android – Listen For Incoming SMS Messages

@Mike M. and I found an issue with the accepted answer (see our comments):

Basically, there is no point in going through the for loop if we are not concatenating the multipart message each time:

for (int i = 0; i < msgs.length; i++) {
    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
    msg_from = msgs[i].getOriginatingAddress();
    String msgBody = msgs[i].getMessageBody();
}

Notice that we just set msgBody to the string value of the respective part of the message no matter what index we are on, which makes the entire point of looping through the different parts of the SMS message useless, since it will just be set to the very last index value. Instead we should use +=, or as Mike noted, StringBuilder:

All in all, here is what my SMS receiving code looks like:

if (myBundle != null) {
    Object[] pdus = (Object[]) myBundle.get("pdus"); // pdus is key for SMS in bundle

    //Object [] pdus now contains array of bytes
    messages = new SmsMessage[pdus.length];
    for (int i = 0; i < messages.length; i++) {
         messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); //Returns one message, in array because multipart message due to sms max char
         Message += messages[i].getMessageBody(); // Using +=, because need to add multipart from before also
    }

    contactNumber = messages[0].getOriginatingAddress(); //This could also be inside the loop, but there is no need
}

Just putting this answer out there in case anyone else has the same confusion.

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

What is the difference between ( for... in ) and ( for... of ) statements?

Difference for..in and for..of:

Both for..in and for..of are looping constructs which are used to iterate over data structures. The only difference between them is the entities they iterate over:

  1. for..in iterates over all enumerable property keys of an object
  2. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.

Example:

_x000D_
_x000D_
let arr = ['el1', 'el2', 'el3'];

arr.addedProp = 'arrProp';

// elKey are the property keys
for (let elKey in arr) {
  console.log(elKey);
}

// elValue are the property values
for (let elValue of arr) {
  console.log(elValue)
}
_x000D_
_x000D_
_x000D_

In this example we can observe that the for..in loop iterates over the keys of the object, which is an array object in this example. The keys are 0, 1, 2 (which correspond to the array elements) and addedProp. This is how the arr array object looks in chrome devtools:

enter image description here

You see that our for..in loop does nothing more than simply iterating over these keys.


The for..of loop in our example iterates over the values of a data structure. The values in this specific example are 'el1', 'el2', 'el3'. The values which an iterable data structure will return using for..of is dependent on the type of iterable object. For example an array will return the values of all the array elements whereas a string returns every individual character of the string.

Change date format in a Java string

You can just use:

Date yourDate = new Date();

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);

It works perfectly!

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

How do I set the default Java installation/runtime (Windows)?

I just had that problem (Java 1.8 vs. Java 9 on Windows 7) and my findings are:

short version

default seems to be (because of Path entry)

c:\ProgramData\Oracle\Java\javapath\java -version

select the version you want (test, use tab completing in cmd, not sure what those numbers represent), I had 2 options, see longer version for details

c:\ProgramData\Oracle\Java\javapath_target_[tab]

remove junction/link and link to your version (the one ending with 181743567 in my case for Java 8)

rmdir javapath
mklink /D javapath javapath_target_181743567

longer version:

Reinstall Java 1.8 after Java 9 didn't work. The sequence of installations was jdk1.8.0_74, jdk-9.0.4 and attempt to make Java 8 default with jdk1.8.0_162...

After jdk1.8.0_162 installation I still have

java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

What I see in path is

Path=...;C:\ProgramData\Oracle\Java\javapath;...

So I checked what is that and I found it is a junction (link)

c:\ProgramData\Oracle\Java>dir
 Volume in drive C is OSDisk
 Volume Serial Number is DA2F-C2CC

 Directory of c:\ProgramData\Oracle\Java

2018-02-07  17:06    <DIR>          .
2018-02-07  17:06    <DIR>          ..
2018-02-08  17:08    <DIR>          .oracle_jre_usage
2017-08-22  11:04    <DIR>          installcache
2018-02-08  17:08    <DIR>          installcache_x64
2018-02-07  17:06    <JUNCTION>     javapath [C:\ProgramData\Oracle\Java\javapath_target_185258831]
2018-02-07  17:06    <DIR>          javapath_target_181743567
2018-02-07  17:06    <DIR>          javapath_target_185258831

Those hashes doesn't ring a bell, but when I checked

c:\ProgramData\Oracle\Java\javapath_target_181743567>.\java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

c:\ProgramData\Oracle\Java\javapath_target_185258831>.\java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

so to make Java 8 default again I had to delete the link as described here

rmdir javapath

and recreate with Java I wanted

mklink /D javapath javapath_target_181743567

tested:

c:\ProgramData\Oracle\Java>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

** update (Java 10) **

With Java 10 it is similar, only javapath is in c:\Program Files (x86)\Common Files\Oracle\Java\ which is strange as I installed 64-bit IMHO

.\java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

AttributeError("'str' object has no attribute 'read'")

If you get a python error like this:

AttributeError: 'str' object has no attribute 'some_method'

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

Run it, which prints:

AttributeError: 'str' object has no attribute 'loads'

But change the name of the variablename, and it works fine:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

How to read data from excel file using c#

There is the option to use OleDB and use the Excel sheets like datatables in a database...

Just an example.....

string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}

This example use the Microsoft.Jet.OleDb.4.0 provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.

The provider is called Microsoft.ACE.OLEDB.12.0;. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.

Of course you don't need Office installed on the target machine.

While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters

Add default value of datetime field in SQL Server to a timestamp

This worked for me. I am using SQL Developer with Oracle DB:

ALTER TABLE YOUR_TABLE
  ADD Date_Created TIMESTAMP  DEFAULT CURRENT_TIMESTAMP NOT NULL;

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Make copy of an array

If you must work with raw arrays and not ArrayList then Arrays has what you need. If you look at the source code, these are the absolutely best ways to get a copy of an array. They do have a good bit of defensive programming because the System.arraycopy() method throws lots of unchecked exceptions if you feed it illogical parameters.

You can use either Arrays.copyOf() which will copy from the first to Nth element to the new shorter array.

public static <T> T[] copyOf(T[] original, int newLength)

Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.

2770
2771    public static <T,U> T[] More ...copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
2772        T[] copy = ((Object)newType == (Object)Object[].class)
2773            ? (T[]) new Object[newLength]
2774            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
2775        System.arraycopy(original, 0, copy, 0,
2776                         Math.min(original.length, newLength));
2777        return copy;
2778    }

or Arrays.copyOfRange() will also do the trick:

public static <T> T[] copyOfRange(T[] original, int from, int to)

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. The resulting array is of exactly the same class as the original array.

3035    public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3036        int newLength = to - from;
3037        if (newLength < 0)
3038            throw new IllegalArgumentException(from + " > " + to);
3039        T[] copy = ((Object)newType == (Object)Object[].class)
3040            ? (T[]) new Object[newLength]
3041            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3042        System.arraycopy(original, from, copy, 0,
3043                         Math.min(original.length - from, newLength));
3044        return copy;
3045    }

As you can see, both of these are just wrapper functions over System.arraycopy with defensive logic that what you are trying to do is valid.

System.arraycopy is the absolute fastest way to copy arrays.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Win32Exception (0x80004005): The wait operation timed out

The problem you are having is the query command is taking too long. I believe that the default timeout for a query to execute is 15 seconds. You need to set the CommandTimeout (in seconds) so that it is long enough for the command to complete its execution. The "CommandTimeout" is different than the "Connection Timeout" in your connection string and must be set for each command.

In your sql Selecting Event, use the command:

e.Command.CommandTimeout = 60

for example:

Protected Sub SqlDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
    e.Command.CommandTimeout = 60
End Sub

How to display length of filtered ng-repeat data

It is also useful to note that you can store multiple levels of results by grouping filters

all items: {{items.length}}
filtered items: {{filteredItems.length}}
limited and filtered items: {{limitedAndFilteredItems.length}}
<div ng-repeat="item in limitedAndFilteredItems = (filteredItems = (items | filter:search) | limitTo:25)">...</div>

here's a demo fiddle

UIView touch event in controller

you can used this way: create extension

extension UIView {

    func addTapGesture(action : @escaping ()->Void ){
        let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
        tap.action = action
        tap.numberOfTapsRequired = 1

        self.addGestureRecognizer(tap)
        self.isUserInteractionEnabled = true

    }
    @objc func handleTap(_ sender: MyTapGestureRecognizer) {
        sender.action!()
    }
}

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var action : (()->Void)? = nil
}

and use this way:

@IBOutlet weak var testView: UIView!
testView.addTapGesture{
   // ...
}

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

How to concat two ArrayLists?

add one ArrayList to second ArrayList as:

Arraylist1.addAll(Arraylist2);

EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:

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

arraylist3.addAll(Arraylist1); // add first arraylist

arraylist3.addAll(Arraylist2); // add Second arraylist

One time page refresh after first page load

Try with this

var element = document.getElementById('position');        
element.scrollIntoView(true);`

MySQL root access from all hosts

MYSQL 8.0 - open mysql command line client

GRANT ALL PRIVILEGES ON \*.* TO 'root'@'localhost';  

use mysql

UPDATE mysql.user SET host='%' WHERE user='root';  

Restart mysql service

Getting the textarea value of a ckeditor textarea with javascript

Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:

$("#CampaignTitle").bind("keyup", function()
{
    $("#titleBar").text($(this).val());
});

If you really wanted a textarea change your input type text to this

<textarea id="CampaignTitle"></textarea>

Hope it helps.

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

Can I set background image and opacity in the same property?

In your CSS add...

 filter: opacity(50%);

In JavaScript use...

 element.style.filter='opacity(50%)';

NB: Add vendor prefixes as required but Chromium should be fine without.

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

How do I specify the platform for MSBuild?

If you're trying to do this from the command line, you may be encountering an issue where a machine-wide environment variable 'Platform' is being set for you and working against you. I can reproduce this if I use the VS2012 Command window instead of a regular windows Command window.

At the command prompt type:

set platform

In a VS2012 Command window, I have a value of 'X64' preset. That seems to interfere with whatever is in my solution file.

In a regular Command window, the 'set' command results in a "variable not defined" message...which is good.

If the result of your 'set' command above returns no environment variable value, you should be good to go.

jQuery Date Picker - disable past dates

just replace your code:

old code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd'

});

new code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    minDate: 0
});

How to limit the number of selected checkboxes?

This is how I made it work:

// Function to check and disable checkbox
function limit_checked( element, size ) {
  var bol = $( element + ':checked').length >= size;
  $(element).not(':checked').attr('disabled',bol);
}

// List of checkbox groups to check
var check_elements = [
  { id: '.group1 input[type=checkbox]', size: 2 },
  { id: '.group2 input[type=checkbox]', size: 3 },
];

// Run function for each group in list
$(check_elements).each( function(index, element) {
  // Limit checked on window load
  $(window).load( function() {
    limit_checked( element.id, element.size );
  })

  // Limit checked on click
  $(element.id).click(function() {
    limit_checked( element.id, element.size );
  });
});

How do I disable form fields using CSS?

A variation to the pointer-events: none; solution, which resolves the issue of the input still being accessible via it's labeled control or tabindex, is to wrap the input in a div, which is styled as a disabled text input, and setting input { visibility: hidden; } when the input is "disabled".
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values

_x000D_
_x000D_
div.dependant {_x000D_
  border: 0.1px solid rgb(170, 170, 170);_x000D_
  background-color: rgb(235,235,228);_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type {_x000D_
  display: inline-block;_x000D_
}_x000D_
input[type="checkbox"]:checked ~ div.dependant:first-of-type {_x000D_
  display: contents;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type > input {_x000D_
  visibility: hidden;_x000D_
}
_x000D_
<form>_x000D_
  <label for="chk1">Enable textbox?</label>_x000D_
  <input id="chk1" type="checkbox" />_x000D_
  <br />_x000D_
  <label for="text1">Input textbox label</label>_x000D_
  <div class="dependant">_x000D_
    <input id="text1" type="text" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The disabled styling applied in the snippet above is taken from the Chrome UI and may not be visually identical to disabled inputs on other browsers. Possibly it can be customised for individual browsers using engine-specific CSS extension -prefixes. Though at a glance, I don't think it could:
Microsoft CSS extensions, Mozilla CSS extensions, WebKit CSS extensions

It would seem far more sensible to introduce an additional value visibility: disabled or display: disabled or perhaps even appearance: disabled, given that visibility: hidden already affects the behavior of the applicable elements any associated control elements.

proper way to sudo over ssh

Depending on your usage, I had success with the following:

ssh root@server "script"

This will prompt for the root password and then execute the command correctly.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

Yet another tip that worked for me.

If your project / library is signed, not even delay signed, it still may not be debuggable. Try disabling the signing option, debugging it, then restoring the signing option.

Query to get the names of all tables in SQL Server 2008 Database

Try this:

SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

it will display the schema+table name for all tables in the current database.

Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1

set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.

Get device token for push notification

NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.

Please use following code instead:

+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
  NSUInteger dataLength = data.length;
  if (dataLength == 0) {
    return nil;
  }

  const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  return [hexString copy];
}

Solution that worked prior to iOS 13:

Objective-C

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
} 

Swift 3.0

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}

Can I define a class name on paragraph using Markdown?

If your environment is JavaScript, use markdown-it along with the plugin markdown-it-attrs:

const md = require('markdown-it')();
const attrs = require('markdown-it-attrs');
md.use(attrs);

const src = 'paragraph {.className #id and=attributes}';

// render
let res = md.render(src);
console.log(res);

Output

<p class="className" id="id" and="attributes">paragraph</p>

jsfiddle

Note: Be aware of the security aspect when allowing attributes in your markdown!

Disclaimer, I'm the author of markdown-it-attrs.

Convert float64 column to int64 in Pandas

This seems to be a little buggy in Pandas 0.23.4?

If there are np.nan values then this will throw an error as expected:

df['col'] = df['col'].astype(np.int64)

But doesn't change any values from float to int as I would expect if "ignore" is used:

df['col'] = df['col'].astype(np.int64,errors='ignore') 

It worked if I first converted np.nan:

df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)

Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:

df['col']  = df['col'].replace(0,np.nan)

jquery, selector for class within id

Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )

How to set a cron job to run at a exact time?

check out

http://www.thesitewizard.com/general/set-cron-job.shtml

for the specifics of setting your crontab directives.

 45 10 * * *

will run in the 10th hour, 45th minute of every day.

for midnight... maybe

 0 0 * * *

Should I use Python 32bit or Python 64bit

Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.

How to properly assert that an exception gets raised in pytest?

Right way is using pytest.raises but I found interesting alternative way in comments here and want to save it for future readers of this question:

try:
    thing_that_rasises_typeerror()
    assert False
except TypeError:
    assert True

ExecuteNonQuery doesn't return results

From MSDN: SqlCommand.ExecuteNonQuery Method

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

You are using SELECT query, thus you get -1

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

You can use bootstrap 3 classes and build a table using the ng-repeat directive

Example:

_x000D_
_x000D_
angular.module('App', []);_x000D_
_x000D_
function ctrl($scope) {_x000D_
    $scope.items = [_x000D_
        ['A', 'B', 'C'],_x000D_
        ['item1', 'item2', 'item3'],_x000D_
        ['item4', 'item5', 'item6']_x000D_
    ];_x000D_
}
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="App">_x000D_
  <div ng-controller="ctrl">_x000D_
    _x000D_
    _x000D_
    <table class="table table-bordered">_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th ng-repeat="itemA in items[0]">{{itemA}}</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemB in items[1]">{{itemB}}</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemC in items[2]">{{itemC}}</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
    _x000D_
    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

live example: http://jsfiddle.net/choroshin/5YDJW/5/

Update:

or you can always try the popular ng-grid , ng-grid is good for sorting, searching, grouping etc, but I haven't tested it yet on a large scale data.

Add a tooltip to a div

You don't need JavaScript for this at all; just set the title attribute:

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>

Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

Demo in Stack Snippets

_x000D_
_x000D_
<div title="Hello, World!">_x000D_
  <label>Name</label>_x000D_
  <input type="text"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why extend the Android Application class?

You can access variables to any class without creating objects, if its extended by Application. They can be called globally and their state is maintained till application is not killed.

Create a directory if it does not exist and then create the files in that directory as well

If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

    private File createFile(String path, String fileName) throws IOException {
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource(".").getFile() + path + fileName);

       // Lets create the directory
       try {
          file.getParentFile().mkdir();
       } catch (Exception err){
           System.out.println("ERROR (Directory Create)" + err.getMessage());
       }

       // Lets create the file if we have credential
       try {
           file.createNewFile();
       } catch (Exception err){
           System.out.println("ERROR (File Create)" + err.getMessage());
       }
       return  file;
   }

org.hibernate.MappingException: Could not determine type for: java.util.Set

My guess is you are using a Set<Role> in the User class annotated with @OneToMany. Which means one User has many Roles. But on the same field you use the @Column annotation which makes no sense. One-to-many relationships are managed using a separate join table or a join column on the many side, which in this case would be the Role class. Using @JoinColumn instead of @Column would probably fix the issue, but it seems semantically wrong. I guess the relationship between role and user should be many-to-many.

ScalaTest in sbt: is there a way to run a single test without tags?

Here's the Scalatest page on using the runner and the extended discussion on the -t and -z options.

This post shows what commands work for a test file that uses FunSpec.

Here's the test file:

package com.github.mrpowers.scalatest.example

import org.scalatest.FunSpec

class CardiBSpec extends FunSpec {

  describe("realName") {

    it("returns her birth name") {
      assert(CardiB.realName() === "Belcalis Almanzar")
    }

  }

  describe("iLike") {

    it("works with a single argument") {
      assert(CardiB.iLike("dollars") === "I like dollars")
    }

    it("works with multiple arguments") {
      assert(CardiB.iLike("dollars", "diamonds") === "I like dollars, diamonds")
    }

    it("throws an error if an integer argument is supplied") {
      assertThrows[java.lang.IllegalArgumentException]{
        CardiB.iLike()
      }
    }

    it("does not compile with integer arguments") {
      assertDoesNotCompile("""CardiB.iLike(1, 2, 3)""")
    }

  }

}

This command runs the four tests in the iLike describe block (from the SBT command line):

testOnly *CardiBSpec -- -z iLike

You can also use quotation marks, so this will also work:

testOnly *CardiBSpec -- -z "iLike"

This will run a single test:

testOnly *CardiBSpec -- -z "works with multiple arguments"

This will run the two tests that start with "works with":

testOnly *CardiBSpec -- -z "works with"

I can't get the -t option to run any tests in the CardiBSpec file. This command doesn't run any tests:

testOnly *CardiBSpec -- -t "works with multiple arguments"

Looks like the -t option works when tests aren't nested in describe blocks. Let's take a look at another test file:

class CalculatorSpec extends FunSpec {
  it("adds two numbers") {
    assert(Calculator.addNumbers(3, 4) === 7)
  }
}

-t can be used to run the single test:

testOnly *CalculatorSpec -- -t "adds two numbers"

-z can also be used to run the single test:

testOnly *CalculatorSpec -- -z "adds two numbers"

See this repo if you'd like to run these examples. You can find more info on running tests here.

How to install PyQt4 in anaconda?

Successfully installed it on OSX using homebrew:

brew install sip
brew install pyqt     

which (currently) installs PyQt4. Anaconda is the main python on the machine (OSX 10.8.5).

How to compare two java objects

You need to implement the equals() method in your MyClass.

The reason that == didn't work is this is checking that they refer to the same instance. Since you did new for each, each one is a different instance.

The reason that equals() didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==.

Note that you should also implement hashcode() if you're going to implement equals() because a lot of java.util Collections expect that.

Sublime Text 3 how to change the font size of the file sidebar?

Default.sublime-theme file works unless you have installed a theme. If you did, go to your theme's github repo and download the your_theme.sublime-theme file and put it in your 'User' folder. In that file, find "class": "sidebar_label", add "font.size":16 to that section.

Change onclick action with a Javascript function

var Foo = function(){
    document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}

var Boo = function(){
    alert("test");
}

AngularJS : ng-model binding not updating when changed with jQuery

Whatever happens outside the Scope of Angular, Angular will never know that.

Digest cycle put the changes from the model -> controller and then from controller -> model.

If you need to see the latest Model, you need to trigger the digest cycle

But there is a chance of a digest cycle in progress, so we need to check and init the cycle.

Preferably, always perform a safe apply.

       $scope.safeApply = function(fn) {
            if (this.$root) {
                var phase = this.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            }
        };


      $scope.safeApply(function(){
          // your function here.
      });

How do I put a variable inside a string?

plot.savefig('hanning(%d).pdf' % num)

The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

"This operation requires IIS integrated pipeline mode."

This was a strange problem since my hosts IIS shouldn't complain that it requires integrated pipeline mode when it already is in that mode as I stated in my question as:

I have searched a lot and unable to find anything except for directing the reader to change the pipeline from classic mode to integrated mode that which I already did with no luck..

Using Levi's directions, I put <%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %> and <%: System.Web.Hosting.HttpRuntime.IISVersion %>* on an empty aspx page and told my host what going on and asked them to fix the problem and confirm the problem using the page I uploaded... I checked very often if something has changed at the state of the page and I can see that they struggled 3-4 hours to solve it...

When I asked what they have done to solve the problem, their answer was kind of 'classified', since they said:

Our team made the required changes on the server

The problem was all with my host.

* Update: As Ben stated in the comments

  1. <%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %> and
  2. <%: System.Web.Hosting.HttpRuntime.IISVersion %>

are no longer valid and they are now:

  1. <%: System.Web.HttpRuntime.UsingIntegratedPipeline %> and
  2. <%: System.Web.HttpRuntime.IISVersion %>

Safely remove migration In Laravel

You likely need to delete the entry from the migrations table too.

Which selector do I need to select an option by its text?

For jquery version 1.10.2 below worked for me

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });

How to run a maven created jar file using just the command line

Use this command.

mvn package

to make the package jar file. Then, run this command.

java -cp target/artifactId-version-SNAPSHOT.jar package.Java-Main-File-Name

after mvn package command. Target folder with classes, test classes, jar file and other resources folder and files will be created.

type your own artifactId, version and package and java main file.

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

ES6 Class Multiple inheritance

use Mixins for ES6 multiple Inheritence.

let classTwo = Base => class extends Base{
    // ClassTwo Code
};

class Example extends classTwo(ClassOne) {
    constructor() {
    }
}

Is Spring annotation @Controller same as @Service?

No you can't they are different. When the app was deployed your controller mappings would be borked for example.

Why do you want to anyway, a controller is not a service, and vice versa.

Removing elements by class name?

I prefer using forEach over for/while looping. In order to use it's necessary to convert HTMLCollection to Array first:

Array.from(document.getElementsByClassName("post-text"))
    .forEach(element => element.remove());

Pay attention, it's not necessary the most efficient way. Just much more elegant for me.

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Convert Iterator to ArrayList

Try StickyList from Cactoos:

List<String> list = new StickyList<>(iterable);

Disclaimer: I'm one of the developers.

regular expression for finding 'href' value of a <a> link

I came up with this one, that supports anchor and image tags, and supports single and double quotes.

<[a|img]+\\s+(?:[^>]*?\\s+)?[src|href]+=[\"']([^\"']*)['\"]

So

<a href="/something.ext">click here</a>

Will match:

 Match 1: /something.ext

And

<a href='/something.ext'>click here</a>

Will match:

 Match 1: /something.ext

Same goes for img src attributes

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

How do I minimize the command prompt from my bat file

Another option that works fine for me is to use ConEmu, see http://conemu.github.io/en/ConEmuArgs.html

"C:\Program Files\ConEmu\ConEmu64.exe" -min -run myfile.bat

Graphical HTTP client for windows

I too have been frustrated by the lack of good graphical http clients available for Windows. So over the past couple years I've been developing one myself: I'm Only Resting, "a feature-rich WinForms-based HTTP client." It's open source (Apache License, Version 2.0) with freely available downloads.

It currently has fairly complete coverage of HTTP features except for file uploads, and it provides a very good user interface with great request and response management.

Here's a screenshot:

enter image description here
(source: swensensoftware.com)

Access Database opens as read only

on my pc I had the same problem and it was because in properties -> security I didn't have the ownership of the file...

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

If you take advantage of how == works, you could simply create an object with a custom toString (or valueOf) function that changes what it returns each time it is used such that it satisfies all three conditions.

_x000D_
_x000D_
const a = {_x000D_
  i: 1,_x000D_
  toString: function () {_x000D_
    return a.i++;_x000D_
  }_x000D_
}_x000D_
_x000D_
if(a == 1 && a == 2 && a == 3) {_x000D_
  console.log('Hello World!');_x000D_
}
_x000D_
_x000D_
_x000D_


The reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling valueOf if it is callable, and failing that, it will call toString. I used toString in this case simply because it's what came to mind, valueOf would make more sense. If I instead returned a string from toString, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.

PHP - get base64 img string decode and save as jpg (resulting empty image )

Client need to send base64 to server.

And above answer described code is work perfectly:

$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

Thanks

CSS/HTML: Create a glowing border around an Input Field

SLaks hit the nail on the head but you might want to look over the changes for inputs in CSS3 in general. Rounded corners and box-shadow are both new features in CSS3 and will let you do exactly what you're looking for. One of my personal favorite links for CSS3/HTML5 is http://diveintohtml5.ep.io/ .

php - How do I fix this illegal offset type error

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...

How to get numeric position of alphabets in java?

String word = "blah blah";

for(int i =0;i<word.length;++i)
{

if(Character.isLowerCase(word.charAt(i)){
System.out.print((int)word.charAt(i) - (int)'a'+1);
}
else{
System.out.print((int)word.charAt(i)-(int)'A' +1);
}
}

Sort a Custom Class List<T>

First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...

You can then make an IComparer:

public class TagComparer : IComparer<cTag>
{
    public int Compare(cTag first, cTag second)
    {
        if (first != null && second != null)
        {
            // We can compare both properties.
            return first.date.CompareTo(second.date);
        }

        if (first == null && second == null)
        {
            // We can't compare any properties, so they are essentially equal.
            return 0;
        }

        if (first != null)
        {
            // Only the first instance is not null, so prefer that.
            return -1;
        }

        // Only the second instance is not null, so prefer that.
        return 1;
    }
}

var list = new List<cTag>();
// populate list.

list.Sort(new TagComparer());

You can even do it as a delegate:

list.Sort((first, second) =>
          {
              if (first != null && second != null)
                  return first.date.CompareTo(second.date);

              if (first == null && second == null)
                  return 0;

              if (first != null)
                  return -1;

              return 1;
          });

How to determine if string contains specific substring within the first X characters

This is what you need :

if (Value1.StartsWith("abc"))
{
found = true;
}

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

Maven with Eclipse Juno

From Eclipse

  • Go to Help
  • Eclipse Marketplace
  • Search for m2e or maven integration for eclipse
  • click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
  • Restart and Enjoy!!!

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
         else:
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")


         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/Firefox.app %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/Safari.app %s")
         navigator.open_new(url)

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

What's the best practice to round a float to 2 decimals?

Here is a simple one-line solution

((int) ((value + 0.005f) * 100)) / 100f

Android - java.lang.SecurityException: Permission Denial: starting Intent

Similar to Olayinka's answer about the configuration file for ADT: I just had the same issue on IntelliJ's IdeaU v14.

I'm working through a tutorial that had me change the starting activity from MyActivity to MyListActivity (Which is a list of MyActivity). I started getting Permissions Denial.

After much trial, toil and pain: In .idea\workspace.xml:

...
<configuration default="false" name="MyApp" type="AndroidRunConfigurationType" factoryName="Android Application">
    <module name="MyApp" />
    <option name="ACTIVITY_CLASS" value="com.domain.MyApp.MyActivity" />
    ...
</configuration>
...

I changed the MyActivity to MyListActivity, reloaded the project and I'm off to a rolling start again.

Not sure which IDE you are using, but maybe your IDE is overriding or forcing a specific starting activity?

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

This solution work on my case i am using ubuntu 16.04, VirtualBox 2.7.2 and genymotion 2.7.2 Same error come in my system i have followed simple step and my problem was solve

1. $ LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
2. $ export LD_LIBRARY_PATH
3. $ sudo apt-add-repository ppa:ubuntu-toolchain-r/test
4. $ sudo apt-get update
5. $ sudo apt-get install gcc-4.9 g++-4.9

I hope this will work for you

Java: How to read a text file

Java 1.5 introduced the Scanner class for handling input from file and streams.

It is used for getting integers from a file and would look something like this:

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

Regex replace uppercase with lowercase letters

In BBEdit works this (ex.: changing the ID values to lowercase):

Search any value: <a id="(?P<x>.*?)"></a> Replace with the same in lowercase: <a id="\L\P<x>\E"></a>

Was: <a id="VALUE"></a> Became: <a id="value"></a>

Remove decimal values using SQL query

Simply update with a convert/cast to INT:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CAST(YOUR_COLUMN AS INT)
WHERE -- some condition is met if required

Or convert:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CONVERT(INT, YOUR_COLUMN)
WHERE -- some condition is met if required

To test you can do this:

SELECT YOUR_COLUMN AS CurrentValue,
       CAST(YOUR_COLUMN AS INT) AS NewValue
FROM YOUR_TABLE

class << self idiom in Ruby

? singleton method is a method that is defined only for a single object.

Example:

class SomeClass
  class << self
    def test
    end
  end
end

test_obj = SomeClass.new

def test_obj.test_2
end

class << test_obj
  def test_3
  end
end

puts "Singleton's methods of SomeClass"
puts SomeClass.singleton_methods
puts '------------------------------------------'
puts "Singleton's methods of test_obj"
puts test_obj.singleton_methods

Singleton's methods of SomeClass

test


Singleton's methods of test_obj

test_2

test_3

Going from MM/DD/YYYY to DD-MMM-YYYY in java

Try this

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
        String currentData = sdf.format(new Date());
        Toast.makeText(getApplicationContext(), ""+currentData,Toast.LENGTH_SHORT ).show();

Pandas "Can only compare identically-labeled DataFrame objects" error

At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals

You use it like this:

df1.equals(df2)

Some differenes to == are:

  • You don't get the error described in the question
  • It returns a simple boolean.
  • NaN values in the same location are considered equal
  • 2 DataFrames need to have the same dtype to be considered equal, see this stackoverflow question

What's the difference between display:inline-flex and display:flex?

Open in Full page for better understanding

_x000D_
_x000D_
.item {_x000D_
  width : 100px;_x000D_
  height : 100px;_x000D_
  margin: 20px;_x000D_
  border: 1px solid blue;_x000D_
  background-color: yellow;_x000D_
  text-align: center;_x000D_
  line-height: 99px;_x000D_
}_x000D_
_x000D_
.flex-con {_x000D_
  flex-wrap: wrap;_x000D_
  /* <A>    */_x000D_
  display: flex;_x000D_
  /* 1. uncomment below 2 lines by commenting above 1 line */_x000D_
  /* <B>   */_x000D_
/*   display: inline-flex; */_x000D_
 _x000D_
}_x000D_
_x000D_
.label {_x000D_
  padding-bottom: 20px;_x000D_
}_x000D_
.flex-inline-play {_x000D_
  padding: 20px;_x000D_
  border: 1px dashed green;_x000D_
/*  <C> */_x000D_
  width: 1000px;_x000D_
/*   <D> */_x000D_
  display: flex;_x000D_
}
_x000D_
<figure>_x000D_
  <blockquote>_x000D_
     <h1>Flex vs inline-flex</h1>_x000D_
    <cite>This pen is understand difference between_x000D_
    flex and inline-flex. Follow along to understand this basic property of css</cite>_x000D_
    <ul>_x000D_
      <li>Follow #1 in CSS:_x000D_
        <ul>_x000D_
          <li>Comment <code>display: flex</code></li>_x000D_
          <li>Un-comment <code>display: inline-flex</code></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li>_x000D_
        Hope you would have understood till now. This is very similar to situation of `inline-block` vs `block`. Lets go beyond and understand usecase to apply learning. Now lets play with combinations of A, B, C & D by un-commenting only as instructed:_x000D_
        <ul>_x000D_
     <li>A with D -- does this do same job as <code>display: inline-flex</code>. Umm, you may be right, but not its doesnt do always, keep going !</li>_x000D_
          <li>A with C</li>_x000D_
          <li>A with C & D -- Something wrong ? Keep going !</li>_x000D_
          <li>B with C</li>_x000D_
          <li>B with C & D -- Still same ? Did you learn something ? inline-flex is useful if you have space to occupy in parent of 2 flexboxes <code>.flex-con</code>. That's the only usecase</li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </blockquote>_x000D_
  _x000D_
</figure>_x000D_
<br/>_x000D_
 <div class="label">Playground:</div>_x000D_
<div class="flex-inline-play">_x000D_
  <div class="flex-con">_x000D_
    <div class="item">1</div>_x000D_
    <div class="item">2</div>_x000D_
    <div class="item">3</div>_x000D_
    <div class="item">4</div>_x000D_
  </div>_x000D_
  <div class="flex-con">_x000D_
    <div class="item">X</div>_x000D_
    <div class="item">Y</div>_x000D_
    <div class="item">Z</div>_x000D_
    <div class="item">V</div>_x000D_
    <div class="item">W</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Testing the type of a DOM element in JavaScript

if (element.nodeName == "A") {
 ...
} else if (element.nodeName == "TD") {
 ...
}

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

Count specific character occurrences in a string

The most straightforward is to simply loop through the characters in the string:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then 
      cnt += 1
    End If
  Next
  Return cnt
End Function

Usage:

count = CountCharacter(str, "e"C)

Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return value.Count(Function(c As Char) c = ch)
End Function

How can I find a specific file from a Linux terminal?

The below line of code would do it for you.

find / -name index.html

However, on most Linux servers, your files will be located in /var/www or in your user directory folder /home/(user) depending on how you have it set up. If you're using a control panel, most likely it'll be under your user folder.

Validate decimal numbers in JavaScript - IsNumeric()

Only problem I had with @CMS's answer is the exclusion of NaN and Infinity, which are useful numbers for many situations. One way to check for NaN's is to check for numeric values that don't equal themselves, NaN != NaN! So there are really 3 tests you'd like to deal with ...

function isNumber(n) {
  n = parseFloat(n);
  return !isNaN(n) || n != n;
}
function isFiniteNumber(n) {
  n = parseFloat(n);
  return !isNaN(n) && isFinite(n);
}    
function isComparableNumber(n) {
  n = parseFloat(n);
  return (n >=0 || n < 0);
}

isFiniteNumber('NaN')
false
isFiniteNumber('OxFF')
true
isNumber('NaN')
true
isNumber(1/0-1/0)
true
isComparableNumber('NaN')
false
isComparableNumber('Infinity')
true

My isComparableNumber is pretty close to another elegant answer, but handles hex and other string representations of numbers.

select the TOP N rows from a table

Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:

SQL Server, Oracle:

SELECT *   -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, * 
      FROM Reflow  
      WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40    

MySQL:

SELECT * 
FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20

Laravel: Auth::user()->id trying to get a property of a non-object

use Illuminate\Support\Facades\Auth;

In class:

protected $user;

This code it`s works for me

In construct:

$this->user = User::find(Auth::user()->id);

In function:
$this->user->id;
$this->user->email;

etc..

Returning a value from thread?

Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke.

Example:

static int GetAnswer() {
   return 42;
}

...

Func<int> method = GetAnswer;
var res = method.BeginInvoke(null, null); // provide args as needed
var answer = method.EndInvoke(res);

GetAnswer will execute on a thread pool thread and when completed you can retrieve the answer via EndInvoke as shown.

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Select where count of one field is greater than one

I give an example up on Group By between two table in Sql:

Select cn.name,ct.name,count(ct.id) totalcity from city ct left join country cn on ct.countryid = cn.id Group By cn.name,ct.name Having totalcity > 2


Loop and get key/value pair for JSON array using jQuery

var obj = $.parseJSON(result);
for (var prop in obj) {
    alert(prop + " is " + obj[prop]);
}

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

Python read in string from file and split it into values

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

SQL Row_Number() function in Where Clause

WITH MyCte AS 
(
    select 
       employee_id,
       RowNum = row_number() OVER (order by employee_id)
    from V_EMPLOYEE 
)
SELECT  employee_id
FROM    MyCte
WHERE   RowNum > 0
ORDER BY employee_id

How to check if an array element exists?

You can use either the language construct isset, or the function array_key_exists.

isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.


For example, considering this array :

$a = array(
    123 => 'glop', 
    456 => null, 
);

And those three tests, relying on isset :

var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));

The first one will get you (the element exists, and is not null) :

boolean true

While the second one will get you (the element exists, but is null) :

boolean false

And the last one will get you (the element doesn't exist) :

boolean false


On the other hand, using array_key_exists like this :

var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));

You'd get those outputs :

boolean true
boolean true
boolean false

Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.


For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)

For instance, your code could become something like this :

if (!isset(self::$instances[$instanceKey])) {
    $instances[$instanceKey] = $theInstance;
}

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

What is the purpose of the "role" attribute in HTML?

As I understand it, roles were initially defined by XHTML but were deprecated. However, they are now defined by HTML 5, see here: https://www.w3.org/WAI/PF/aria/roles#abstract_roles_header

The purpose of the role attribute is to identify to parsing software the exact function of an element (and its children) as part of a web application. This is mostly as an accessibility thing for screen readers, but I can also see it as being useful for embedded browsers and screen scrapers. In order to be useful to the unusual HTML client, the attribute needs to be set to one of the roles from the spec I linked. If you make up your own, this 'future' functionality can't work - a comment would be better.

Practicalities here: http://www.accessibleculture.org/articles/2011/04/html5-aria-2011/

Recursive sub folder search and return files in a list python

Your original solution was very nearly correct, but the variable "root" is dynamically updated as it recursively paths around. os.walk() is a recursive generator. Each tuple set of (root, subFolder, files) is for a specific root the way you have it setup.

i.e.

root = 'C:\\'
subFolder = ['Users', 'ProgramFiles', 'ProgramFiles (x86)', 'Windows', ...]
files = ['foo1.txt', 'foo2.txt', 'foo3.txt', ...]

root = 'C:\\Users\\'
subFolder = ['UserAccount1', 'UserAccount2', ...]
files = ['bar1.txt', 'bar2.txt', 'bar3.txt', ...]

...

I made a slight tweak to your code to print a full list.

import os
for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,item))
            print(fileNamePath)

Hope this helps!

EDIT: (based on feeback)

OP misunderstood/mislabeled the subFolder variable, as it is actually all the sub folders in "root". Because of this, OP, you're trying to do os.path.join(str, list, str), which probably doesn't work out like you expected.

To help add clarity, you could try this labeling scheme:

import os
for current_dir_path, current_subdirs, current_files in os.walk(RECURSIVE_ROOT):
    for aFile in current_files:
        if aFile.endswith(".txt") :
            txt_file_path = str(os.path.join(current_dir_path, aFile))
            print(txt_file_path)

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

selecting an entire row based on a variable excel vba

The key is in the quotes around the colon and &, i.e. rows(variable & ":" & variable).select

Adapt this:

Rows(x & ":" & y).select

where x and y are your variables.

Some other examples that may help you understand

Rows(x & ":" & x).select

Or

Rows((x+1) & ":" (x*3)).select

Or

Rows((x+2) & ":" & (y-3)).select

Hopefully you get the idea.

MySQL - UPDATE query based on SELECT Query

You can actually do this one of two ways:

MySQL update join syntax:

UPDATE tableA a
INNER JOIN tableB b ON a.name_a = b.name_b
SET validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here

ANSI SQL syntax:

UPDATE tableA SET validation_check = 
    (SELECT if(start_DTS > end_DTS, 'VALID', '') AS validation_check
        FROM tableA
        INNER JOIN tableB ON name_A = name_B
        WHERE id_A = tableA.id_A)

Pick whichever one seems most natural to you.

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

What is the use of System.in.read()?

Two and a half years late is better than never, right?

int System.in.read() reads the next byte of data from the input stream. But I am sure you already knew that, because it is trivial to look up. So, what you are probably asking is:

  • Why is it declared to return an int when the documentation says that it reads a byte?

  • and why does it appear to return garbage? (I type '9', but it returns 57.)

It returns an int because besides all the possible values of a byte, it also needs to be able to return an extra value to indicate end-of-stream. So, it has to return a type which can express more values than a byte can.

Note: They could have made it a short, but they opted for int instead, possibly as a tip of the hat of historical significance to C, whose getc() function also returns an int, but more importantly because short is a bit cumbersome to work with, (the language offers no means of specifying a short literal, so you have to specify an int literal and cast it to short,) plus on certain architectures int has better performance than short.

It appears to return garbage because when you view a character as an integer, what you are looking at is the ASCII(*) value of that character. So, a '9' appears as a 57. But if you cast it to a character, you get '9', so all is well.

Think of it this way: if you typed the character '9' it is nonsensical to expect System.in.read() to return the number 9, because then what number would you expect it to return if you had typed an 'a'? Obviously, characters must be mapped to numbers. ASCII(*) is a system of mapping characters to numbers. And in this system, character '9' maps to number 57, not number 9.

(*) Not necessarily ASCII; it may be some other encoding, like UTF-16; but in the vast majority of encodings, and certainly in all popular encodings, the first 127 values are the same as ASCII. And this includes all english alphanumeric characters and popular symbols.

How can I round down a number in Javascript?

Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!

<script>

var marks = 0;

function getRandomNumbers(){    //  generate a random number between 1 & 10
    var number = Math.floor((Math.random() * 10) + 1);
    return number;
}

function getNew(){  
/*  
    This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;

document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"

}

function checkAns(){
/*
    After entering the answer, the entered answer will be compared with the correct answer. 
        If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
        If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
        The updated total marks should be always displayed at the total marks box.
*/

var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);

if(answer==(num1+num2)){
    marks = marks + 10;
    document.getElementById("resultBox").innerHTML = "Correct";
    document.getElementById("resultBox").style.backgroundColor = "green";
    document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;

}

else{
    marks = marks - 3;
    document.getElementById("resultBox").innerHTML = "Wrong";
    document.getElementById("resultBox").style.backgroundColor = "red";
    document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}




}

</script>
</head>

<body onLoad="getNew()">
    <div class="container">
        <h1>Let's add numbers</h1>
        <div class="sum">
            <input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
        </div>
        <h2>Enter the answer below and click 'Check'</h2>
        <div class="answer">
            <input id="ans" type="text" value="">
        </div>
        <input id="btnchk" onClick="checkAns()" type="button" value="Check" >
        <div id="resultBox">***</div>
        <input id="btnnew" onClick="getNew()" type="button" value="New">
        <div id="totalMarks">Total marks : 0</div>  
    </div>
</body>
</html>

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Move_uploaded_file() function is not working

If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access first type in;

sudo chgrp "www-data" your_project_folder

once its done, if there is no write access to the following as well;

sudo chown g+w your_project_folder

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.

How to find MAC address of an Android device programmatically

Here the Kotlin version of Arth Tilvas answer:

fun getMacAddr(): String {
    try {
        val all = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (nif in all) {
            if (!nif.getName().equals("wlan0", ignoreCase=true)) continue

            val macBytes = nif.getHardwareAddress() ?: return ""

            val res1 = StringBuilder()
            for (b in macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b))
            }

            if (res1.length > 0) {
                res1.deleteCharAt(res1.length - 1)
            }
            return res1.toString()
        }
    } catch (ex: Exception) {
    }

    return "02:00:00:00:00:00"
}

Sorting a list with stream.sorted() in Java

Java 8 provides different utility api methods to help us sort the streams better.

If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.

List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);

Creating comparator on fly:

integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);

With default comparator provided by java 8 when no argument passed to sorted():

integerList.stream().sorted().forEach(System.out::println); //Natural order

If you want to sort the same list in reverse order:

 integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order

If your list is a list of user defined objects, then:

List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
        new Person(2000, "Second", 30, 45000),
        new Person(3000, "Third", 35, 25000));

Creating comparator on fly:

personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
        .forEach(person -> System.out.println(person.getName()));

Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):

personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

Using Comparator.comparing() method(Generic method which compares based on the getter method provided):

personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

We can do chaining too using thenComparing() method:

personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.

Person class

public class Person {
    private long personId;
    private String name;
    private int age;
    private double salary;

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }

    public Person(long personId, String name, int age, double salary) {
        this.personId = personId;
        this.name = name;
        this.age = age;

        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

How to open the default webbrowser using java

Here is my code. It'll open given url in default browser (cross platform solution).

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Send email using the GMail SMTP server from a PHP page

Send Mail using phpMailer library through Gmail Please donwload library files from Github

<?php
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 */
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "[email protected]";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

How to make String.Contains case insensitive?

bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

insert data into database using servlet and jsp in eclipse

String user = request.getParameter("uname");
out.println(user); 
String pass = request.getParameter("pass");
out.println(pass); 
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);

Comparing Arrays of Objects in JavaScript

As serialization doesn't work generally (only when the order of properties matches: JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})) you have to check the count of properties and compare each property as well:

_x000D_
_x000D_
const objectsEqual = (o1, o2) =>_x000D_
    Object.keys(o1).length === Object.keys(o2).length _x000D_
        && Object.keys(o1).every(p => o1[p] === o2[p]);_x000D_
_x000D_
const obj1 = { name: 'John', age: 33};_x000D_
const obj2 = { age: 33, name: 'John' };_x000D_
const obj3 = { name: 'John', age: 45 };_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

If you need a deep comparison, you can call the function recursively:

_x000D_
_x000D_
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };_x000D_
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };_x000D_
const obj3 = { name: 'John', age: 33 };_x000D_
_x000D_
const objectsEqual = (o1, o2) => _x000D_
    typeof o1 === 'object' && Object.keys(o1).length > 0 _x000D_
        ? Object.keys(o1).length === Object.keys(o2).length _x000D_
            && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))_x000D_
        : o1 === o2;_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

Then it's easy to use this function to compare objects in arrays:

const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];

const arraysEqual = (a1, a2) => 
   a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));

console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

Simple Deadlock Examples

public class DeadLock {
    public static void main(String[] args) throws InterruptedException {
        Thread mainThread = Thread.currentThread();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mainThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread1.join();
    }
}

Angular2 *ngFor in select list, set active based on string from object

This should work

<option *ngFor="let title of titleArray" 
    [value]="title.Value" 
    [attr.selected]="passenger.Title==title.Text ? true : null">
  {{title.Text}}
</option>

I'm not sure the attr. part is necessary.

Add button to navigationbar programmatically

If you are not looking for a BarButtonItem but simple button on navigationBar then below code works:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
            action:@selector(showButtonView:)
  forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

How to force NSLocalizedString to use a specific language

Based on Tudorizer's answer to change language without leaving or restarting the application.

Instead of a macro, use a class for accessing the preferred language in order to check if a specific language code is present.

Below is a class used to obtain the current language bundle that is working for iOS 9:

@implementation OSLocalization

+ (NSBundle *)currentLanguageBundle
{
    // Default language incase an unsupported language is found
    NSString *language = @"en";

    if ([NSLocale preferredLanguages].count) {
        // Check first object to be of type "en","es" etc
        // Codes seen by my eyes: "en-US","en","es-US","es" etc

        NSString *letterCode = [[NSLocale preferredLanguages] objectAtIndex:0];

        if ([letterCode rangeOfString:@"en"].location != NSNotFound) {
            // English
            language = @"en";
        } else if ([letterCode rangeOfString:@"es"].location != NSNotFound) {
            // Spanish
            language = @"es";
        } else if ([letterCode rangeOfString:@"fr"].location != NSNotFound) {
            // French
            language = @"fr";
        } // Add more if needed
    }

    return [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]];
}

/// Check if preferred language is English
+ (BOOL)isCurrentLanguageEnglish
{
    if (![NSLocale preferredLanguages].count) {
        // Just incase check for no items in array
        return YES;
    }

    if ([[[NSLocale preferredLanguages] objectAtIndex:0] rangeOfString:@"en"].location == NSNotFound) {
        // No letter code for english found
        return NO;
    } else {
        // Tis English
        return YES;
    }
}

/*  Swap language between English & Spanish
 *  Could send a string argument to directly pass the new language
 */
+ (void)changeCurrentLanguage
{
    if ([self isCurrentLanguageEnglish]) {
        [[NSUserDefaults standardUserDefaults] setObject:@[@"es"] forKey:@"AppleLanguages"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:@[@"en"] forKey:@"AppleLanguages"];
    }
}
@end

Use the class above to reference a string file / image / video / etc:

// Access a localized image
[[OSLocalization currentLanguageBundle] pathForResource:@"my_image_name.png" ofType:nil]
// Access  a localized string from Localizable.strings file
NSLocalizedStringFromTableInBundle(@"StringKey", nil, [OSLocalization currentLanguageBundle], @"comment")

Change language in-line like below or update the "changeCurrentLanguage" method in the class above to take a string parameter referencing the new language.

[[NSUserDefaults standardUserDefaults] setObject:@[@"es"] forKey:@"AppleLanguages"];

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I just encountered this problem on a virgin install with a system that has a bad clock battery (when I turn off the power, it resets the date/time. Syncing to time.windows.com again allowed me to run VS2010 successfully.

How to write to Console.Out during execution of an MSTest test

You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

Getting value of selected item in list box as string

If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         label1.Text  = listBox1.SelectedItem.ToString();
    }

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

How to get file extension from string in C++

Assuming you have access to STL:

std::string filename("filename.conf");
std::string::size_type idx;

idx = filename.rfind('.');

if(idx != std::string::npos)
{
    std::string extension = filename.substr(idx+1);
}
else
{
    // No extension found
}

Edit: This is a cross platform solution since you didn't mention the platform. If you're specifically on Windows, you'll want to leverage the Windows specific functions mentioned by others in the thread.

jQuery multiselect drop down menu

Take a look at erichynds dropdown multiselect with huge amount of settings and tunings.