Programs & Examples On #Xtratreelist

The XtraTreeList Suite is a comprehensive WinForms TreeView and ListView control by DevExpress.

How do you assert that a certain exception is thrown in JUnit 4 tests?

Java 8 solution

If you would like a solution which:

  • Utilizes Java 8 lambdas
  • Does not depend on any JUnit magic
  • Allows you to check for multiple exceptions within a single test method
  • Checks for an exception being thrown by a specific set of lines within your test method instead of any unknown line in the entire test method
  • Yields the actual exception object that was thrown so that you can further examine it

Here is a utility function that I wrote:

public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
{
    try
    {
        runnable.run();
    }
    catch( Throwable throwable )
    {
        if( throwable instanceof AssertionError && throwable.getCause() != null )
            throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
        assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
        assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
        @SuppressWarnings( "unchecked" )
        T result = (T)throwable;
        return result;
    }
    assert false; //expected exception was not thrown.
    return null; //to keep the compiler happy.
}

(taken from my blog)

Use it as follows:

@Test
public void testThrows()
{
    RuntimeException e = expectException( RuntimeException.class, () -> 
        {
            throw new RuntimeException( "fail!" );
        } );
    assert e.getMessage().equals( "fail!" );
}

Get GPS location via a service in Android

Just complementing, I implemented this way and usually worked in my Service class

In my Service

@Override
public void onCreate()
{
    mHandler = new Handler(Looper.getMainLooper());
    mHandler.post(this);
    super.onCreate();
}

@Override
public void onDestroy() 
{
    mHandler.removeCallbacks(this);     
    super.onDestroy();
}

@Override
public void run()
{
    InciarGPSTracker();
}

How to deal with SQL column names that look like SQL keywords?

In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.

select [from] from <table>

As a note, the above does not work in MySQL

matplotlib savefig() plots different from show()

Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.

If you create a figure from scratch you can give it a size option while creation:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3, 6))

plt.plot(range(10)) #plot example
plt.show() #for control

fig.savefig('temp.png', dpi=fig.dpi)

figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.

As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().

Alternatively the figure size can be changed after creation with:

fig.set_size_inches(3, 6, forward=True)

forward allows to change the size on the fly.

If you have trouble with too large borders in the created image you can adjust those either with:

plt.tight_layout()
#or:
plt.tight_layout(pad=2)

or:

fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)

The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.

nodejs npm global config missing on windows

Isn't this the path you are looking for?

C:\Program Files\nodejs\node_modules\npm\npmrc

I know that npm outputs that , but the global folder is the folder where node.js is installed and all the modules are.

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

Try running fuser command

[root@guest2 ~]# fuser -mv /home

USER PID ACCESS COMMAND

/home: root 2919 f.... automount

[root@guest2 ~]# kill -9 2919

autofs service is known to cause this issue.

You can use command

#service autofs stop

And try again.

Cordova app not displaying correctly on iPhone X (Simulator)

I'm developing cordova apps for 2 years and I spent weeks to solve related problems (eg: webview scrolls when keyboard open). Here's a tested and proven solution for both ios and android

P.S.: I'm using iScroll for scrolling content

  1. Never use viewport-fit=cover at index.html's meta tag, leave the app stay out of statusbar. iOS will handle proper area for all iPhone variants.
  2. In XCode uncheck hide status bar and requires full screen and don't forget to select Launch Screen File as CDVLaunchScreen
  3. In config.xml set fullscreen as false
  4. Finally, (thanks to Eddy Verbruggen for great plugins) add his plugin cordova-plugin-webviewcolor to set statusbar and bottom area background color. This plugin will allow you to set any color you want.
  5. Add below to config.xml (first ff after x is opacity)

    <preference name="BackgroundColor" value="0xff088c90" />
    
  6. Handle your scroll position yourself by adding focus events to input elements

    iscrollObj.scrollToElement(elm, transitionduration ... etc)
    

For android, do the same but instead of cordova-plugin-webviewcolor, install cordova-plugin-statusbar and cordova-plugin-navigationbar-color

Here's a javascript code using those plugins to work on both ios and android:

function setStatusColor(colorCode) {
    //colorCode is smtg like '#427309';
    if (cordova.platformId == 'android') {
        StatusBar.backgroundColorByHexString(colorCode);
        NavigationBar.backgroundColorByHexString(colorCode);
    } else if (cordova.platformId == 'ios') {
        window.plugins.webviewcolor.change(colorCode);
    }
}

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

What should main() return in C and C++?

If you really have issues related to efficiency of returning an integer from a process, you should probably avoid to call that process so many times that this return value becomes an issue.

If you are doing this (call a process so many times), you should find a way to put your logic directly inside the caller, or in a DLL file, without allocate a specific process for each call; the multiple process allocations bring you the relevant efficiency problem in this case.

In detail, if you only want to know if returning 0 is more or less efficient than returning 1, it could depend from the compiler in some cases, but generically, assuming they are read from the same source (local, field, constant, embedded in the code, function result, etc.) it requires exactly the same number of clock cycles.

NuGet auto package restore does not work with MSBuild

There is a packages.config file with the project, it contains the package details.

Also there is a .nuget folder which contains the NuGet.exe and NuGet.targets. if any one of the file is missing it will not restore the missing package and cause "are you missing a using directive or an assembly reference?" error

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff
</IfModule>

Get and set position with jQuery .offset()

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

How do I get the last four characters from a string in C#?

A simple solution would be:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);

jQuery .on('change', function() {} not triggering for dynamically created inputs

You should provide a selector to the on function:

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

In that case, it will work as you expected. Also, it is better to specify some element instead of document.

Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

PHP random string generator

/**
 * @param int $length
 * @param string $abc
 * @return string
 */
function generateRandomString($length = 10, $abc = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
    return substr(str_shuffle($abc), 0, $length);
}

Source from http://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-in-php/

Django Server Error: port is already in use

In case You are using the VSC's screen terminal, The error might be due to the fact that you already runserver in some other shell.

Just click on the dropbox on the left of the + sign in the header of the terminal of VSC and select some other shell and check if the server is already running there. Quit that server and you are ready to launch a another server.

Is the practice of returning a C++ reference variable evil?

Not only is it not evil, it is sometimes essential. For example, it would be impossible to implement the [] operator of std::vector without using a reference return value.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

Can't use modulus on doubles?

You can implement your own modulus function to do that for you:

double dmod(double x, double y) {
    return x - (int)(x/y) * y;
}

Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.

Determine whether an array contains a value

It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.

Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.

_.includes([1, 2, 3], 3); // returns true

If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:

var includes = require('lodash/collections/includes');

NOTICE: With older versions of lodash, this was _.contains() rather than _.includes().

Convert xlsx file to csv using batch

Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.

$excelApp = New-Object -ComObject Excel.Application 
$excelApp.DisplayAlerts = $false 

$ExcelFiles | ForEach-Object { 
    $workbook = $excelApp.Workbooks.Open($_.FullName) 
    $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv" 
    $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV) 
    $workbook.Close() 
} 

You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell

GitHub authentication failing over https, returning wrong email address

On Windows, you may be silently blocked by your Antivirus or Windows firewall. Temporarily turn off those services and push/pull from remote origin.

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

How generate unique Integers based on GUIDs

I had a requirement where multiple instances of a console application needed to get an unique integer ID. It is used to identify the instance and assigned at startup. Because the .exe is started by hands, I settled on a solution using the ticks of the start time.

My reasoning was that it would be nearly impossible for the user to start two .exe in the same millisecond. This behavior is deterministic: if you have a collision, you know that the problem was that two instances were started at the same time. Methods depending on hashcode, GUID or random numbers might fail in unpredictable ways.

I set the date to 0001-01-01, add the current time and divide the ticks by 10000 (because I don't set the microseconds) to get a number that is small enough to fit into an integer.

 var now = DateTime.Now;
 var zeroDate = DateTime.MinValue.AddHours(now.Hour).AddMinutes(now.Minute).AddSeconds(now.Second).AddMilliseconds(now.Millisecond);
 int uniqueId = (int)(zeroDate.Ticks / 10000);

EDIT: There are some caveats. To make collisions unlikely, make sure that:

  • The instances are started manually (more than one millisecond apart)
  • The ID is generated once per instance, at startup
  • The ID must only be unique in regard to other instances that are currently running
  • Only a small number of IDs will ever be needed

How to hide collapsible Bootstrap 4 navbar on click

add below code in your < a > TAG

data-toggle="collapse" data-target=".navbar-collapse.show"

as shows below in every TAG

<li class="nav-item">
   <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>

Running Python on Windows for Node.js dependencies

I met the same challenge while trying to install [email protected].

And after looking at the current official documentation, and having read the answers above, i noticed that you might not necessarily have to install node-gyp nor install windows-build tools. This is what it says, here about installing node-gyp on windows. Remember node-gyp is involved in the installation process of node-sass. And you don't really have to re-install another python version.

This is the savior, configure the python path that "npm" should look for while installing any packages that require build-tools.

C:\> npm config set python /Python36/python

I had installed python3.6.3, on windows-7, there.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

How to stop the task scheduled in java.util.Timer class

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

Redirect stderr to stdout in C shell

I think this is the correct answer for csh.

xxx >/dev/stderr

Note most csh are really tcsh in modern environments:

rmockler> ls -latr /usr/bin/csh

lrwxrwxrwx 1 root root 9 2011-05-03 13:40 /usr/bin/csh -> /bin/tcsh

using a backtick embedded statement to portray this as follows:

echo "`echo 'standard out1'` `echo 'error out1' >/dev/stderr` `echo 'standard out2'`" | tee -a /tmp/test.txt ; cat /tmp/test.txt

if this works for you please bump up to 1. The other suggestions don't work for my csh environment.

How to drop column with constraint?

It's not always just a default constraint that prevents from droping a column and sometimes indexes can also block you from droping the constraint. So I wrote a procedure that drops any index or constraint on a column and the column it self at the end.

IF OBJECT_ID ('ADM_delete_column', 'P') IS NOT NULL
   DROP procedure ADM_delete_column;
GO

CREATE procedure ADM_delete_column
    @table_name_in  nvarchar(300)
,   @column_name_in nvarchar(300)
AS 
BEGIN
    /*  Author: Matthis ([email protected] at 2019.07.20)
        License CC BY (creativecommons.org)
        Desc:   Administrative procedure that drops columns at MS SQL Server
                - if there is an index or constraint on the column 
                    that will be dropped in advice
                => input parameters are TABLE NAME and COLUMN NAME as STRING
    */
    SET NOCOUNT ON

    --drop index if exist (search first if there is a index on the column)
    declare @idx_name VARCHAR(100)
    SELECT  top 1 @idx_name = i.name
    from    sys.tables t
    join    sys.columns c
    on      t.object_id = c.object_id
    join    sys.index_columns ic
    on      c.object_id = ic.object_id
    and     c.column_id = ic.column_id
    join    sys.indexes i
    on      i.object_id = ic.object_id
    and     i.index_id = ic.index_id
    where   t.name like @table_name_in
    and     c.name like @column_name_in
    if      @idx_name is not null
    begin 
        print concat('DROP INDEX ', @idx_name, ' ON ', @table_name_in)
        exec ('DROP INDEX ' + @idx_name + ' ON ' + @table_name_in)
    end

    --drop fk constraint if exist (search first if there is a constraint on the column)
    declare @fk_name VARCHAR(100)
    SELECT  top 1 @fk_name = CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
    where   TABLE_NAME like @table_name_in
    and     COLUMN_NAME like @column_name_in
    if      @fk_name is not null
    begin 
        print concat('ALTER TABLE ', @table_name_in, ' DROP CONSTRAINT ', @fk_name)
        exec ('ALTER TABLE ' + @table_name_in + ' DROP CONSTRAINT ' + @fk_name)
    end

    --drop column if exist
    declare @column_name VARCHAR(100)
    SELECT  top 1 @column_name = COLUMN_NAME 
    FROM    INFORMATION_SCHEMA.COLUMNS 
    WHERE   COLUMN_NAME like concat('%',@column_name_in,'%')
    if  @column_name is not null
    begin 
        print concat('ALTER TABLE ', @table_name_in, ' DROP COLUMN ', @column_name)
        exec ('ALTER TABLE ' + @table_name_in + ' DROP COLUMN ' + @column_name)
    end
end;
GO


--to run the procedure use this execute and fill the parameters 
execute ADM_delete_column 
    @table_name_in  = ''
,   @column_name_in = ''
    ;

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

Is log(n!) = T(n·log(n))?

Remember that

log(n!) = log(1) + log(2) + ... + log(n-1) + log(n)

You can get the upper bound by

log(1) + log(2) + ... + log(n) <= log(n) + log(n) + ... + log(n)
                                = n*log(n)

And you can get the lower bound by doing a similar thing after throwing away the first half of the sum:

log(1) + ... + log(n/2) + ... + log(n) >= log(n/2) + ... + log(n) 
                                       = log(n/2) + log(n/2+1) + ... + log(n-1) + log(n)
                                       >= log(n/2) + ... + log(n/2)
                                        = n/2 * log(n/2) 

How to sort a list of lists by a specific index of the inner list?

**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
    #let's assume we want to sort lists by last value ( old_list[2] )
    new_list = sorted(old_list, key=lambda x: x[2])**

correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?

Timestamp Difference In Hours for PostgreSQL

The first things popping up

EXTRACT(EPOCH FROM current_timestamp-somedate)/3600

May not be pretty, but unblocks the road. Could be prettier if division of interval by interval was defined.

Edit: if you want it greater than zero either use abs or greatest(...,0). Whichever suits your intention.

Edit++: the reason why I didn't use age is that age with a single argument, to quote the documentation: Subtract from current_date (at midnight). Meaning you don't get an accurate "age" unless running at midnight. Right now it's almost 1am here:

select age(current_timestamp);
       age        
------------------
 -00:52:40.826309
(1 row)

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

It happened to me when I had a same port used in ssh tunnel SOCKS to run Proxy in 8080 port and my server and my firefox browser proxy was set to that port and got this issue.

Reading an Excel file in python using pandas

You just need to feed the path to your file to pd.read_excel

import pandas as pd

file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)

Checkout the documentation to explore parameters like skiprows to ignore rows when loading the excel

How to check currently internet connection is available or not in android

Use Below Code:

private boolean isNetworkAvailable() {
  ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

if isNetworkAvailable() returns true then internet connection available, otherwise internet connection not available

Here need to add below uses-permission in your application Manifest file

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

Make the image go behind the text and keep it in center using CSS

You can position both the image and the text with position:absolute or position:relative. Then the z-index property will work. E.g.

#sometext {
    position:absolute;
    z-index:1;

}
image.center {
    position:absolute;
    z-index:0;
}

Use whatever method you like to center it.

Another option/hack is to make the image the background, either on the whole page or just within the text box.

Remove x-axis label/text in chart.js

UPDATE chart.js 2.1 and above

var chart = new Chart(ctx, {
    ...
    options:{
        scales:{
            xAxes: [{
                display: false //this will remove all the x-axis grid lines
            }]
        }
    }
});


var chart = new Chart(ctx, {
    ...
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false //this will remove only the label
                }
            }]
        }
    }
});

Reference: chart.js documentation

Old answer (written when the current version was 1.0 beta) just for reference below:

To avoid displaying labels in chart.js you have to set scaleShowLabels : false and also avoid to pass the labels:

<script>
    var options = {
        ...
        scaleShowLabels : false
    };
    var lineChartData = {
        //COMMENT THIS LINE TO AVOID DISPLAYING THE LABELS
        //labels : ["1","2","3","4","5","6","7"],
        ... 
    }
    ...
</script>

How to automate drag & drop functionality using Selenium WebDriver Java

    WebElement fromElement= driver.findElement(By.xpath("SourceElement"));
    WebElement toElement=driver.findElement(By.xpath("TragetElement"));
    Actions action = new Actions(WebDriver);
    Action dragDrop = action.dragAndDrop(fromElement, toElement).build();
    dragDrop.perform(); 

Formatting code snippets for blogging on Blogger

It looks like there have been some changes with SyntaxHighlighter 2.0 that make it easier to use with Blogger.

There are hosted versions of the styles and Javascripts at: http://alexgorbatchev.com/pub/sh/

How to store a dataframe using Pandas

Pickle works good!

import pandas as pd
df.to_pickle('123.pkl')    #to save the dataframe, df to 123.pkl
df1 = pd.read_pickle('123.pkl') #to load 123.pkl back to the dataframe df

Why doesn't margin:auto center an image?

I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.

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");  

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

I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:

set /p Var1="Prompt String"

Without the prompt string in quotes, I get various results depending on the text.

Convert digits into words with JavaScript

Convert digits to word in French language using JavaScript and html - original French words

_x000D_
_x000D_
        <html>
            <head>
                <title>Number to word</title>
    
                <script>
                    function toWords() {
                        var s = document.getElementById('value').value;
                        var th = ['','mille','million', 'milliard','billion'];
                        var dg = ['zéro','un','deux','trois','quatre', 'cinq','six','sept','huit','neuf'];
                        var tn = 
    
    ['dix','onze','douze','treize', 'quatorze','quinze','seize', 'dix-sept','dix-huit','dix-neuf'];
                    var tw = ['vingt','trente','quarante','cinquante', 'soixante','soixante-dix','quatre-vingt','quatre-vingt-dix'];
                    s = s.toString();
                    s = s.replace(/[\, ]/g,'');
                    if (s != parseFloat(s)) return 'not a number';
                    var x = s.indexOf('.');
                    if (x == -1)
                        x = s.length;
                    if (x > 15)
                        return 'too big';
                    var n = s.split(''); 
                    var str = '';
                    var sk = 0;
                    for (var i=0;   i < x;  i++) {
                        if ((x-i)%3==2) { 
                            if (n[i] == '1') {
    
                                str += tn[Number(n[i+1])] + ' ';
                                i++;
                                sk=1;
                            } else if (n[i]!=0) { 
                                if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                                if(s==20 || s==30 || s==40 || s==50 || s==60 || s==70 || s==80 || s==90){
                                str += tw[n[i]-2] + ' ';} // for not to display hyphens for 20,30...90 
                                else{
                                str += tw[n[i]-2] + '-';}
                                sk=1;
                                }
                            }
                        } else if (n[i]!=0) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
    
                            str += dg[n[i]] +' ';
                            if ((x-i)%3==0) str += 'hundert ';  // for start from 101 - 
    
                            sk=1;
                            }
                        }
                        if ((x-i)%3==1) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                            if (sk)
                                str += th[(x-i-1)/3] + ' ';
                            sk=0;
                            }
                        }
                    }
    
                    if (x != s.length) {
                        var y = s.length;
                        //str += 'point ';
                        //for (var i=x+1; i<y; i++)
                        //  str += dg[n[i]] +' ';
                        str += 'virgule ';
                         var counter=0;
                         for (var i=x+1; i<y; i++){
                            if ((y-i)%3==2) { 
                                                if (n[i] == '1') {
                                                                str += tn[Number(n[i+1])] + ' ';
                                                                i++;
                                                                counter=1;
                                                } else if (n[i]!=0) {
                                                                str += tw[n[i]-2] + '-';
                                                                counter=1;
                                                }
                                            }else if (n[i]!=0) { // 0235
                                                str += dg[n[i]] +' ';
                                            }
                         }
    
                    }
    
                    if (s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                    document.getElementById("demo").innerHTML = str.replace(/\s+/g,' ')
    
                    }
                    else if (s==21){
                    str = 'vingt-et-un'
                    document.getElementById("demo").innerHTML = str;
                    }//alert(str.replace(/\s+/g,' '));
                    else if (s==31){
                    str = 'trente-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==41){
                    str = 'quarante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==51){
                    str = 'cinquante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==61){
                    str = 'soixante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==71){
                    str = 'soixante-et-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==72){
                    str = 'soixante-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==73){
                    str = 'soixante-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==74){
                    str = 'soixante-quatorze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==75){
                    str = 'soixante-quinze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==76){
                    str = 'soixante-seize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==100){
                    str = 'cent'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==91){
                    str = 'quatre-vingt-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==92){
                    str = 'quatre-vingt-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==93){
                    str = 'quatre-vingt-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==94){
                    str = 'quatre-vingt-quatorze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==95){
                    str = 'quatre-vingt-quinze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==96){
                    str = 'quatre-vingt-seize'
                    document.getElementById("demo").innerHTML = str;}               
                }
            </script>
        </head>
        <body>
            <p>Enter only numbers (max 15 digits) : </p>
            <input type="text" name="value" id='value' /><br>
            <input type="button" value="submit" onclick="toWords()" />
            <p id="demo"></p>
            <p id="demo1"></p>
        </body>
    </html> 
_x000D_
_x000D_
_x000D_

How can I stop .gitignore from appearing in the list of untracked files?

This seems to only work for your current directory to get Git to ignore all files from the repository.

update this file

.git/info/exclude 

with your wild card or filename

*pyc
*swp
*~

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How to use font-awesome icons from node-modules

You will need to copy the files as part of your build process. For example, you can use a npm postinstall script to copy the files to the correct directory:

"postinstall": "cp -R node_modules/font-awesome/fonts ./public/"

For some build tools, there are preexisting font-awesome packages. For example, webpack has font-awesome-webpack which lets you simple require('font-awesome-webpack').

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Disable scrolling in all mobile devices

I suspect most everyone really wants to disable zoom/scroll in order to put together a more app-like experience; because the answers seem to contain elements of solutions for both zooming and scrolling, but nobody's really nailed either one down.

Scrolling

To answer OP, the only thing you seem to need to do to disable scrolling is intercept the window's scroll and touchmove events and call preventDefault and stopPropagation on the events they generate; like so

window.addEventListener("scroll", preventMotion, false);
window.addEventListener("touchmove", preventMotion, false);

function preventMotion(event)
{
    window.scrollTo(0, 0);
    event.preventDefault();
    event.stopPropagation();
}

And in your stylesheet, make sure your body and html tags include the following:

html:
{
    overflow: hidden;
}

body
{
    overflow: hidden;
    position: relative;
    margin: 0;
    padding: 0;
}

Zooming

However, scrolling is one thing, but you probably want to disable zoom as well. Which you do with the meta tag in your markup:

<meta name="viewport" content="user-scalable=no" />

All of these put together give you an app-like experience, probably a best fit for canvas.

(Be wary of the advice of some to add attributes like initial-scale and width to the meta tag if you're using a canvas, because canvasses scale their contents, unlike block elements, and you'll wind up with an ugly canvas, more often than not).

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

Are there any disadvantages to always using nvarchar(MAX)?

The only problem I found was that we develop our applications on SQL Server 2005, and in one instance, we have to support SQL Server 2000. I just learned, the hard way that SQL Server 2000 doesn't like the MAX option for varchar or nvarchar.

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

Remove querystring from URL

2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;

// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
    testURL.substring(0, testURL.indexOf('?'));
    i++;
}
console.timeEnd('10k substring');

// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
    testURL.split('?')[0]; 
    i++;
}
console.timeEnd('10k split');

// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
    testURL.match(re)[0]; 
    i++;
}
console.timeEnd('10k regex');

Results in Firefox 3.5.8 on Mac OS X 10.6.2:

10k substring:  16ms
10k split:      25ms
10k regex:      44ms

Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:

10k substring:  14ms
10k split:      20ms
10k regex:      15ms

Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.


1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0];    // Returns: "/Products/List"

var testURL2 = '/Products/List';
testURL2.split('?')[0];    // Returns: "/Products/List"

Original Answer:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?'));    // Returns: "/Products/List"

Convert LocalDate to LocalDateTime or java.sql.Timestamp

Java8 +

import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Use the following Statement:

IF EXISTS(SELECT * FROM prueba )
then
  UPDATE prueba
  SET nombre = '1', apellido = '1' 
  WHERE cedula = 'ct'
ELSE 
  INSERT INTO prueba (cedula, nombre, apellido)
  VALUES ('ct', 'ct', 'ct');

Unable to launch the IIS Express Web server

VS2015

edit file .csproj.user

Insert the following xml tags (do not duplicate if already exists)

<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>2870</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:2859</IISUrl>
<OverrideIISAppRootUrl>True</OverrideIISAppRootUrl>
<IISAppRootUrl>http://localhost:2859</IISAppRootUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>http://localhost/app</CustomServerUrl>

Insert above tags in XML node bellow:

<ProjectExtensions><VisualStudio><FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"><WebProjectProperties> 

How to convert a datetime to string in T-SQL

SELECT CONVERT(varchar, @datetime, 103) --for UK Date format 'DD/MM/YYYY'

101 - US - MM/DD/YYYY

108 - Time - HH:MI:SS

112 - Date - YYYYMMDD

121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF

20 - ODBC - YYYY-MM-DD HH:MI:SS

Show Console in Windows Application?

In wind32, console-mode applications are a completely different beast from the usual message-queue-receiving applications. They are declared and compile differently. You might create an application which has both a console part and normal window and hide one or the other. But suspect you will find the whole thing a bit more work than you thought.

How do I disable a jquery-ui draggable?

Seems like no one looked at the original documentation. May be there was no it at that time))

Initialize a draggable with the disabled option specified.

$( ".selector" ).draggable({ disabled: true });

Get or set the disabled option, after init.

//getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );

How to create a jar with external libraries included in Eclipse?

To generate jar file in eclipse right click on the project for which you want to generate, Select Export>Java>Runnable Jar File,

enter image description here

enter image description here

Its create jar which includes all the dependencies from Pom.xml, But please make sure license issue if you are using third-party dependency for your application.

Converting year and month ("yyyy-mm" format) to a date?

I think @ben-rollert's solution is a good solution.

You just have to be careful if you want to use this solution in a function inside a new package.

When developping packages, it's recommended to use the syntaxe packagename::function_name() (see http://kbroman.org/pkg_primer/pages/depends.html).

In this case, you have to use the version of as.Date() defined by the zoo library.

Here is an example :

> devtools::session_info()
Session info ----------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, linux-gnu           
 ui       RStudio (1.0.35)            
 language (EN)                        
 collate  C                           
 tz       <NA>                        
 date     2016-11-09                  

Packages --------------------------------------------------------------------------------------------------------------------------------------------------------

 package  * version date       source        
 devtools   1.12.0  2016-06-24 CRAN (R 3.3.1)
 digest     0.6.10  2016-08-02 CRAN (R 3.2.3)
 memoise    1.0.0   2016-01-29 CRAN (R 3.2.3)
 withr      1.0.2   2016-06-20 CRAN (R 3.2.3)

> as.Date(zoo::as.yearmon("1989-10", "%Y-%m")) 
Error in as.Date.default(zoo::as.yearmon("1989-10", "%Y-%m")) : 
  do not know how to convert 'zoo::as.yearmon("1989-10", "%Y-%m")' to class “Date”

> zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
[1] "1989-10-01"

So if you're developping a package, the good practice is to use :

zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))

How do you beta test an iphone app?

(As the official guide is still missing in this thread..)

TestFlight, acquired by Apple and now (iOS8+) available for beta testing makes it easy to hand your app to beta testers without the need to collect device UUIDs beforehand (you only need email addresses of your testers). An extensive guide explaining all necessary steps may be found in the iTunes Connect Developer Guide.

Entity Framework. Delete all rows in table

if

      using(var db = new MyDbContext())
            {
               await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
            }

causes

Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.

I use this :

      using(var db = new MyDbContext())
               {
                   await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
               }

How to redraw DataTable with new data

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

How to directly initialize a HashMap (in a literal way)?

We can initialize hashmap using following ways :

  1. HashMap using Constructor

    Map<String, String> hashMap = new HashMap<String, String>();

     hashMap.put("hcl", "amit");
    
     hashMap.put("tcs","ravi");
    

Hashmap have four different type constructor so we can initialize it as per our requirement. Now using HashMap(int initialCapacity) constructor

    Map<String, String> hashMap = new HashMap<String, String>(3);
    hashMap.put("virat", "cricket");
    hashMap.put("amit","football");

Reference : How to create HashMap

  1. Singleton HashMaps using Collections

      Map<String, String> immutableMap = Collections.singletonMap("rohit", 
           "cricket");
    
  2. Empty HashMaps using Collections

      Map<String, String> emptyMap = Collections.emptyMap();
    
  3. Anonymous Subclass to Create HashMap

       Map<String, String> map = new HashMap<String, String>() {{
         put("hcl", "amit");
         put("tcs","ravi");
         put("wipro","anmol");
        }};
    

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

Can't get value of input type="file"?

You can get it by using document.getElementById();

var fileVal=document.getElementById("some Id");
alert(fileVal.value);

will give the value of file,but it gives with fakepath as follows

c:\fakepath\filename

web-api POST body object always null

It can be helpful to add TRACING to the json serializer so you can see what's up when things go wrong.

Define an ITraceWriter implementation to show their debug output like:

class TraceWriter : Newtonsoft.Json.Serialization.ITraceWriter
{
    public TraceLevel LevelFilter {
        get {
            return TraceLevel.Error;
        }
    }

    public void Trace(TraceLevel level, string message, Exception ex)
    {
        Console.WriteLine("JSON {0} {1}: {2}", level, message, ex);
    }
}

Then in your WebApiConfig do:

    config.Formatters.JsonFormatter.SerializerSettings.TraceWriter = new TraceWriter();

(maybe wrap it in an #if DEBUG)

Pandas - Get first row value of a given column

To select the ith row, use iloc:

In [31]: df_test.iloc[0]
Out[31]: 
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

To select the ith value in the Btime column you could use:

In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2

There is a difference between df_test['Btime'].iloc[0] (recommended) and df_test.iloc[0]['Btime']:

DataFrames store data in column-based blocks (where each block has a single dtype). If you select by column first, a view can be returned (which is quicker than returning a copy) and the original dtype is preserved. In contrast, if you select by row first, and if the DataFrame has columns of different dtypes, then Pandas copies the data into a new Series of object dtype. So selecting columns is a bit faster than selecting rows. Thus, although df_test.iloc[0]['Btime'] works, df_test['Btime'].iloc[0] is a little bit more efficient.

There is a big difference between the two when it comes to assignment. df_test['Btime'].iloc[0] = x affects df_test, but df_test.iloc[0]['Btime'] may not. See below for an explanation of why. Because a subtle difference in the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:

df.iloc[0, df.columns.get_loc('Btime')] = x

df.iloc[0, df.columns.get_loc('Btime')] = x (recommended):

The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,

df.loc[df.index[n], 'Btime'] = x

or

df.iloc[n, df.columns.get_loc('Btime')] = x

The latter method is a bit faster, because df.loc has to convert the row and column labels to positional indices, so there is a little less conversion necessary if you use df.iloc instead.


df['Btime'].iloc[0] = x works, but is not recommended:

Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime'] always returns a view (not a copy) so df['Btime'].iloc[n] = x can be used to assign a new value at the nth location of the Btime column of df.

Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning even though in this case the assignment succeeds in modifying df:

In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

In [26]: df
Out[26]: 
  foo  bar
0   A   99  <-- assignment succeeded
2   B  100
1   C  100

df.iloc[0]['Btime'] = x does not work:

In contrast, assignment with df.iloc[0]['bar'] = 123 does not work because df.iloc[0] is returning a copy:

In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df
Out[67]: 
  foo  bar
0   A   99  <-- assignment failed
2   B  100
1   C  100

Warning: I had previously suggested df_test.ix[i, 'Btime']. But this is not guaranteed to give you the ith value since ix tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i] will return the row labeled i rather than the ith row. For example,

In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]: 
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'

Can I pass column name as input parameter in SQL stored Procedure

Please Try with this. I hope it will work for you.

Create Procedure Test
(
    @Table VARCHAR(500),
    @Column VARCHAR(100),
    @Value  VARCHAR(300)
)
AS
BEGIN

DECLARE @sql nvarchar(1000)

SET @sql = 'SELECT * FROM ' + @Table + ' WHERE ' + @Column + ' = ' + @Value

--SELECT @sql
exec (@sql)

END

-----execution----

/** Exec Test Products,IsDeposit,1 **/

Force page scroll position to top at page refresh in HTML

Instead of location.reload(), simply use location.href = location.href. It will not scroll to the previous position as location.reload() does.

Note: This will not reload if there is any # in the URL

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

i Have face the same issue and resolved by replacing the old Oracle.DataAccess.dll with new Oracle.DataAccess.dll(which come with oracle client when install)

in my case the path of new Oracle.DataAccess.dll is

  • E:\app\Rehman.Rashid\product\11.2.0\client_1\ODP.NET\bin

PHP page redirect

<?php

    http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);

?>

Wait until flag=true

In my example, I log a new counter value every second:

_x000D_
_x000D_
var promises_arr = [];_x000D_
var new_cntr_val = 0;_x000D_
_x000D_
// fill array with promises_x000D_
for (let seconds = 1; seconds < 10; seconds++) {_x000D_
    new_cntr_val = new_cntr_val + 5;    // count to 50_x000D_
    promises_arr.push(new Promise(function (resolve, reject) {_x000D_
        // create two timeouts: one to work and one to resolve the promise_x000D_
        setTimeout(function(cntr) {_x000D_
            console.log(cntr);_x000D_
        }, seconds * 1000, new_cntr_val);    // feed setTimeout the counter parameter_x000D_
        setTimeout(resolve, seconds * 1000);_x000D_
    }));_x000D_
}_x000D_
_x000D_
// wait for promises to finish_x000D_
Promise.all(promises_arr).then(function (values) {_x000D_
    console.log("all promises have returned");_x000D_
});
_x000D_
_x000D_
_x000D_

Why is IoC / DI not common in Python?

I back "Jörg W Mittag" answer: "The Python implementation of DI/IoC is so lightweight that it completely vanishes".

To back up this statement, take a look at the famous Martin Fowler's example ported from Java to Python: Python:Design_Patterns:Inversion_of_Control

As you can see from the above link, a "Container" in Python can be written in 8 lines of code:

class Container:
    def __init__(self, system_data):
        for component_name, component_class, component_args in system_data:
            if type(component_class) == types.ClassType:
                args = [self.__dict__[arg] for arg in component_args]
                self.__dict__[component_name] = component_class(*args)
            else:
                self.__dict__[component_name] = component_class

How do you create a daemon in Python?

since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon

pep3143daemon should support at least python 2.6, 2.7 and 3.x

It also contains a PidFile class.

The library only depends on the standard library and on the six module.

It can be used as a drop in replacement for python-daemon.

Here is the documentation.

Connect to Oracle DB using sqlplus

if you want to connect with oracle database

  1. open sql prompt
  2. connect with sysdba for XE- conn / as sysdba for IE- conn sys as sysdba
  3. then start up database by below command startup;

once it get start means you can access oracle database now. if you want connect another user you can write conn username/password e.g. conn scott/tiger; it will show connected........

How to prevent http file caching in Apache httpd (MAMP)

<FilesMatch "\.(js|css)$">
  ExpiresActive On
  ExpiresDefault A1
  Header append Cache-Control must-revalidate
</FilesMatch>

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Where does Visual Studio look for C++ header files?

Actually On my windows 10 with visual studio 2017 community, the C++ headers path are:

  1. C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include

  2. C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt

The 1st contains standard C++ headers such as <iostream>, <algorithm>. The 2nd contains old C headers such as <stdio.h>, <string.h>. The version number can be different based on your software.

Hope this would help.

CURL and HTTPS, "Cannot resolve host"

I had the same problem. Coudn't resolve google.com. There was a bug somewhere in php fpm, which i am using. Restarting php-fpm solved it for me.

Invalid date in safari

I use moment to solve the problem. For example

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

Add a properties file to IntelliJ's classpath

Perhaps this is a bit off-topic, seeing as the question has already been answered, but I have experienced a similar problem. In my case only some of the unit test resources were copied to the output folder upon compilation. My persistence.xml in the META-INF folder got copied but nothing else.

In the end I "solved" the problem by renaming the problematic files, rebuiling the project and then changing the file names back to the original ones. Do not ask me why this worked but it did. My best guess is that, somehow, my IntelliJ project had gotten a bit out of sync with the file system and the renaming operation triggered some kind of internal "resource rescan".

iOS Launching Settings -> Restrictions URL Scheme

Here is something else I found:

  1. After I have the "prefs" URL Scheme defined, "prefs:root=Safari&path=ContentBlockers" is working on Simulator (iOS 9.1 English), but not working on Simulator (Simplified Chinese). It just jump to Safari, but not Content Blockers. If your app is international, be careful.
    Update: Don't know why, now I can't jump into ContentBlockers anymore, the same code, the same version, doesn't work now. :(

  2. On real devcies (mine is iPhone 6S & iPad mini 2), "Safari" should be "SAFARI", "Safari" not working on real device, "SAFARI" now working on simulator:

    #if arch(i386) || arch(x86_64)
        // Simulator
        let url = NSURL(string: "prefs:root=Safari")!
    #else
        // Device
        let url = NSURL(string: "prefs:root=SAFARI")!
    #endif
    
    if UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.sharedApplication().openURL(url)
    }
    
  3. So far, did not find any differences between iPhone and iPad.

How to validate a url in Python? (Malformed or not)

EDIT

As pointed out by @Kwame , the below code does validate the url even if the .com or .co etc are not present.

also pointed out by @Blaise, URLs like https://www.google is a valid URL and you need to do a DNS check for checking if it resolves or not, separately.

This is simple and works:

So min_attr contains the basic set of strings that needs to be present to define the validity of a URL, i.e http:// part and google.com part.

urlparse.scheme stores http:// and

urlparse.netloc store the domain name google.com

from urlparse import urlparse
def url_check(url):

    min_attr = ('scheme' , 'netloc')
    try:
        result = urlparse(url)
        if all([result.scheme, result.netloc]):
            return True
        else:
            return False
    except:
        return False

all() returns true if all the variables inside it return true. So if result.scheme and result.netloc is present i.e. has some value then the URL is valid and hence returns True.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

Remove pattern from string with gsub

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

Basic example for sharing text or image with UIActivityViewController in Swift

UIActivityViewController Example Project

Set up your storyboard with two buttons and hook them up to your view controller (see code below).

enter image description here

Add an image to your Assets.xcassets. I called mine "lion".

enter image description here

Code

import UIKit
class ViewController: UIViewController {

    // share text
    @IBAction func shareTextButton(_ sender: UIButton) {

        // text to share
        let text = "This is some text that I want to share."

        // set up activity view controller
        let textToShare = [ text ]
        let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)

    }

    // share image
    @IBAction func shareImageButton(_ sender: UIButton) {

        // image to share
        let image = UIImage(named: "Image")

        // set up activity view controller
        let imageToShare = [ image! ]
        let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)
    }

}

Result

Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.

enter image description here

Notes

  • I retested this with iOS 11 and Swift 4. I had to run it a couple times in the simulator before it worked because it was timing out. This may be because my computer is slow.
  • If you wish to hide some of these choices, you can do that with excludedActivityTypes as shown in the code above.
  • Not including the popoverPresentationController?.sourceView line will cause your app to crash when run on an iPad.
  • This does not allow you to share text or images to other apps. You probably want UIDocumentInteractionController for that.

See also

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

How do the post increment (i++) and pre increment (++i) operators work in Java?

Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.

Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

JavaFX 2.1 TableView refresh items

What a BUG ! Here is another workaround...

public void forceRefresh() {
  final TableColumn< Prospect, ? > firstColumn = view.getColumns().get( 0 );
  firstColumn.setVisible( false );
  new Timer().schedule( new TimerTask() { @Override public void run() {
     Platform.runLater( new Runnable() { @Override public void run() {
        firstColumn.setVisible( true  ); }});
     }}, 100 );
}

I've done a SSCCE to show the bug. I encourage everyone to fix it by another more elegant way because my workaround is very ugly!

MySQL Error #1133 - Can't find any matching row in the user table

In my case I had just renamed the Mysql user which was going to change his password on a gui based db tool (DbVisualizer). The terminal in which I tried to 'SET PASSWORD' did not work(MySQL Error #1133).

However this answer worked for me, even after changing the password the 'SET PASSWORD' command did not work yet.

After closing the terminal and opening new one the command worked very well.

Can I start the iPhone simulator without "Build and Run"?

First, add the iOS Simulator to Applications:

ln -s /Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app

From there you can open it in Finder or drag it to the launch bar.

Source: http://www.bram.us/2010/05/05/xcode-iphone-simulator-location/

Pretty-Print JSON Data to a File using Python

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

How to force an entire layout View refresh?

To clear a view extending ViewGroup, you just need to use the method removeAllViews()

Just like this (if you have a ViewGroup called myElement) :

myElement.removeAllViews()

How do I check if a string is unicode or ascii?

For py2/py3 compatibility simply use

import six if isinstance(obj, six.text_type)

Converting a string to a date in DB2

Based on your own answer, I'm guessing that your column has data formatted like this:

'DD/MM/YYYY HH:MI:SS'

The actual separators between Day/Month/Year don't matter, nor does anything that comes after the year.

You don't say what version of DB2 you are using or what platform it's running on, so I'm going to assume that it's on Linux, UNIX or Windows.

Almost any recent version of DB2 for Linux/UNIX/Windows (8.2 or later, possibly even older versions), you can do this using the TRANSLATE function:

select 
   date(translate('GHIJ-DE-AB',column_with_date,'ABCDEFGHIJ'))
from
   yourtable

With this solution it doesn't matter what comes after the date in your column.

In DB2 9.7, you can also use the TO_DATE function (similar to Oracle's TO_DATE):

date(to_date(column_with_date,'DD-MM-YYYY HH:MI:SS'))

This requires your data match the formatting string; it's easier to understand when looking at it, but not as flexible as the TRANSLATE option.

Loop through childNodes

If you do a lot of this sort of thing then it might be worth defining the function for yourself.

if (typeof NodeList.prototype.forEach == "undefined"){
    NodeList.prototype.forEach = function (cb){
        for (var i=0; i < this.length; i++) {
            var node = this[i];
            cb( node, i );
        }
    };
}

How to animate the change of image in an UIImageView?

CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"contents"];
fadeAnim.fromValue = (__bridge id)imageView.image.CGImage;
fadeAnim.toValue = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;
fadeAnim.duration = 2.0;
[imageView.layer addAnimation:fadeAnim forKey:@"contents"];
imageView.layer.contents = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;

Run Button is Disabled in Android Studio

I opened the wrong folder.... Verify is your root folder in Android studio has the build.gradle file.

What's the difference between 'git merge' and 'git rebase'?

While the accepted and most upvoted answer is great, I additionally find it useful trying to explain the difference only by words:

merge

  • “okay, we got two differently developed states of our repository. Let's merge them together. Two parents, one resulting child.”

rebase

  • “Give the changes of the main branch (whatever its name) to my feature branch. Do so by pretending my feature work started later, in fact on the current state of the main branch.”
  • “Rewrite the history of my changes to reflect that.” (need to force-push them, because normally versioning is all about not tampering with given history)
  • “Likely —if the changes I raked in have little to do with my work— history actually won't change much, if I look at my commits diff by diff (you may also think of ‘patches’).“

summary: When possible, rebase is almost always better. Making re-integration into the main branch easier.

Because? ? your feature work can be presented as one big ‘patch file’ (aka diff) in respect to the main branch, not having to ‘explain’ multiple parents: At least two, coming from one merge, but likely many more, if there were several merges. Unlike merges, multiple rebases do not add up. (another big plus)

mailto link with HTML body

As you can see in RFC 6068, this is not possible at all:

The special <hfname> "body" indicates that the associated <hfvalue> is the body of the message. The "body" field value is intended to contain the content for the first text/plain body part of the message. The "body" pseudo header field is primarily intended for the generation of short text messages for automatic processing (such as "subscribe" messages for mailing lists), not for general MIME bodies.

no such file to load -- rubygems (LoadError)

I had a similar problem on Ubuntu due to having multiple copies of ruby installed. (1.8 and 1.9.1) Unfortunately I need both of them. The solution is to use:

$ sudo update-alternatives --config ruby
There are 2 choices for the alternative ruby (providing /usr/bin/ruby).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/ruby1.8     50        auto mode
  1            /usr/bin/ruby1.8     50        manual mode
  2            /usr/bin/ruby1.9.1   10        manual mode

Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/ruby1.9.1 to provide /usr/bin/ruby (ruby) in manual mode.

After doing that bundle install succeeded.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Sorry for the "diggy up", but i just encoured this issue with an symfony3.8 project deploiement on shared hosting (php 7.3.18)...

I solved this issue by set the php memory limit in the command line options, a stuff like this:

php -dmemory_limit=-1 /path/to/the/executable

Is it possible to use if...else... statement in React render function?

If you need more than one condition, so you can try this out

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

HTML Image not displaying, while the src url works

Your file needs to be located inside your www directory. For example, if you're using wamp server on Windows, j3evn.jpg should be located,

C:/wamp/www/img/j3evn.jpg

and you can access it in html via

<img class="sealImage" alt="Image of Seal" src="../img/j3evn.jpg">

Look for the www, public_html, or html folder belonging to your web server. Place all your files and resources inside that folder.

Hope this helps!

How to printf "unsigned long" in C?

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

What's the purpose of SQL keyword "AS"?

The use is more obvious if you don't use 'SELECT *' (which is a bad habit you should get out of):

SELECT t1.colA, t2.colB, t3.colC FROM alongtablename AS t1, anotherlongtablename AS t2, yetanotherlongtablename AS t3 WHERE t1.colD = t2.colE...

Angular: Can't find Promise, Map, Set and Iterator

my file structure is as below:

project
 |--node-modules
 |   |--angular2
 |   |   |--typings
 |   |   |   |--browser.d.ts
 |--src
 |--app.ts

paste the below into the top of your app.ts and your problem solved

/// <reference path=">../../../node_modules/angular2/typings/browser.d.ts" />

How do I get the current GPS location programmatically in Android?

As of the second half of 2020, there is a much easier way to do this.

Excluding requesting permissions (which I will include at the bottom for devs newer to this), below is the code.

Just remember, you need to include at least this version of the library in your dependencies (in the app's build.gradle):

implementation 'com.google.android.gms:play-services-location:17.1.0'

... and of course the fine permission in your manifest:

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

Kotlin (first the setup):

private val fusedLocationClient: FusedLocationProviderClient by lazy {
    LocationServices.getFusedLocationProviderClient(applicationContext)
}

private var cancellationTokenSource = CancellationTokenSource()

Then the main code (for FINE_LOCATION):

private fun requestCurrentLocation() {
    // Check Fine permission
    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {

        // Main code
        val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
            PRIORITY_HIGH_ACCURACY,
            cancellationTokenSource.token
        )

        currentLocationTask.addOnCompleteListener { task: Task<Location> ->
            val result = if (task.isSuccessful) {
                val result: Location = task.result
                "Location (success): ${result.latitude}, ${result.longitude}"
            } else {
                val exception = task.exception
                "Location (failure): $exception"
            }

            Log.d(TAG, "getCurrentLocation() result: $result")
        }
    } else {
        // Request fine location permission (full code below).
}

If you prefer Java, it looks like this:

public class JavaVersion extends AppCompatActivity {

    private final String TAG = "MainActivity";

    // The Fused Location Provider provides access to location APIs.
    private FusedLocationProviderClient fusedLocationClient;

    // Allows class to cancel the location request if it exits the activity.
    // Typically, you use one cancellation source per lifecycle.
    private final CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }
    ...
    
    private void requestCurrentLocation() {
        Log.d(TAG, "requestCurrentLocation()");
        // Request permission
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
            
            // Main code
            Task<Location> currentLocationTask = fusedLocationClient.getCurrentLocation(
                    PRIORITY_HIGH_ACCURACY,
                    cancellationTokenSource.getToken()
            );

            currentLocationTask.addOnCompleteListener((new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {

                    String result = "";

                    if (task.isSuccessful()) {
                        // Task completed successfully
                        Location location = task.getResult();
                        result = "Location (success): " +
                                location.getLatitude() +
                                ", " +
                                location.getLongitude();
                    } else {
                        // Task failed with an exception
                        Exception exception = task.getException();
                        result = "Exception thrown: " + exception;
                    }

                    Log.d(TAG, "getCurrentLocation() result: " + result);
                }
            }));
        } else {
            // TODO: Request fine location permission
            Log.d(TAG, "Request fine location permission.");
        }
    }
    ...
}

The arguments:

  1. PRIORITY type is self-explanatory. (Other options are PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, and PRIORITY_NO_POWER.)
  2. CancellationToken - This allows you to cancel the request if, for instance, the user navigates away from your Activity.

Example (Kotlin):

override fun onStop() {
    super.onStop()
    // Cancels location request (if in flight).
    cancellationTokenSource.cancel()
}

That's it.

Now, this does use the FusedLocationProviderClient which is a Google Play Services APIs.

That means this works on all Android devices with the Google Play Store (which is a lot of them). However, for devices in China without the Play Store, this won't work, so take that into account.

For developers who are a little newer to this, you need to request the fine (or coarse) location permission if the user hasn't approved it yet, so in the code above, I would request the location permission.

Below is the full code (in Kotlin).

I hope that helps (and makes your live's a little easier)!

/**
 * Demonstrates how to easily get the current location via the [FusedLocationProviderClient.getCurrentLocation].
 * The main code is in this class's requestCurrentLocation() method.
 */
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    // The Fused Location Provider provides access to location APIs.
    private val fusedLocationClient: FusedLocationProviderClient by lazy {
        LocationServices.getFusedLocationProviderClient(applicationContext)
    }

    // Allows class to cancel the location request if it exits the activity.
    // Typically, you use one cancellation source per lifecycle.
    private var cancellationTokenSource = CancellationTokenSource()

    // If the user denied a previous permission request, but didn't check "Don't ask again", this
    // Snackbar provides an explanation for why user should approve, i.e., the additional rationale.
    private val fineLocationRationalSnackbar by lazy {
        Snackbar.make(
            binding.container,
            R.string.fine_location_permission_rationale,
            Snackbar.LENGTH_LONG
        ).setAction(R.string.ok) {
            requestPermissions(
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root

        setContentView(view)
    }

    override fun onStop() {
        super.onStop()
        // Cancels location request (if in flight).
        cancellationTokenSource.cancel()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        Log.d(TAG, "onRequestPermissionResult()")

        if (requestCode == REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE) {
            when {
                grantResults.isEmpty() ->
                    // If user interaction was interrupted, the permission request
                    // is cancelled and you receive an empty array.
                    Log.d(TAG, "User interaction was cancelled.")

                grantResults[0] == PackageManager.PERMISSION_GRANTED ->
                    Snackbar.make(
                        binding.container,
                        R.string.permission_approved_explanation,
                        Snackbar.LENGTH_LONG
                    )
                        .show()

                else -> {
                    Snackbar.make(
                        binding.container,
                        R.string.fine_permission_denied_explanation,
                        Snackbar.LENGTH_LONG
                    )
                        .setAction(R.string.settings) {
                            // Build intent that displays the App settings screen.
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            val uri = Uri.fromParts(
                                "package",
                                BuildConfig.APPLICATION_ID,
                                null
                            )
                            intent.data = uri
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            startActivity(intent)
                        }
                        .show()
                }
            }
        }
    }

    fun locationRequestOnClick(view: View) {
        Log.d(TAG, "locationRequestOnClick()")

        requestCurrentLocation()
    }

    /**
     * Gets current location.
     * Note: The code checks for permission before calling this method, that is, it's never called
     * from a method with a missing permission. Also, I include a second check with my extension
     * function in case devs just copy/paste this code.
     */
    private fun requestCurrentLocation() {
        Log.d(TAG, "requestCurrentLocation()")
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED) {

            // Returns a single current location fix on the device. Unlike getLastLocation() that
            // returns a cached location, this method could cause active location computation on the
            // device. A single fresh location will be returned if the device location can be
            // determined within reasonable time (tens of seconds), otherwise null will be returned.
            //
            // Both arguments are required.
            // PRIORITY type is self-explanatory. (Other options are PRIORITY_BALANCED_POWER_ACCURACY,
            // PRIORITY_LOW_POWER, and PRIORITY_NO_POWER.)
            // The second parameter, [CancellationToken] allows the activity to cancel the request
            // before completion.
            val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
                PRIORITY_HIGH_ACCURACY,
                cancellationTokenSource.token
            )

            currentLocationTask.addOnCompleteListener { task: Task<Location> ->
                val result = if (task.isSuccessful) {
                    val result: Location = task.result
                    "Location (success): ${result.latitude}, ${result.longitude}"
                } else {
                    val exception = task.exception
                    "Location (failure): $exception"
                }

                Log.d(TAG, "getCurrentLocation() result: $result")
                logOutputToScreen(result)
            }
        } else {
            val provideRationale = shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)

            if (provideRationale) {
                fineLocationRationalSnackbar.show()
            } else {
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE)
            }
        }
    }

    private fun logOutputToScreen(outputString: String) {
        val finalOutput = binding.outputTextView.text.toString() + "\n" + outputString
        binding.outputTextView.text = finalOutput
    }

    companion object {
        private const val TAG = "MainActivity"
        private const val REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE = 34
    }
}

wget: unable to resolve host address `http'

remove the http or https from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip . this worked fine for me.

Installation failed with message Invalid File

In my case , there was a single qutation ' in project directory and after removing it resolved

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

How to fit a smooth curve to my data in R?

I didn't see this method shown, so if someone else is looking to do this I found that ggplot documentation suggested a technique for using the gam method that produced similar results to loess when working with small data sets.

library(ggplot2)
x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)

df <- data.frame(x,y)
r <- ggplot(df, aes(x = x, y = y)) + geom_smooth(method = "gam", formula = y ~ s(x, bs = "cs"))+geom_point()
r

First with the loess method and auto formula Second with the gam method with suggested formula

Protect .NET code from reverse engineering?

Here's one idea: you could have a server hosted by your company that all instances of your software need to connect to. Simply having them connect and verify a registration key is not sufficient -- they'll just remove the check. In addition to the key check, you need to also have the server perform some vital task that the client can't perform itself, so it's impossible to remove. This of course would probably mean a lot of heavy processing on the part of your server, but it would make your software difficult to steal, and assuming you have a good key scheme (check ownership, etc), the keys will also be difficult to steal. This is probably more invasive than you want, since it will require your users to be connected to the internet to use your software.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

Not able to change TextField Border Color

  1. Inside your lib file

  2. Create a folder called colors.

  3. Inside the colors folder create a dart file and name it color.

  4. Paste this code inside it

    const MaterialColor primaryOrange = MaterialColor(
        _orangePrimaryValue,
        <int, Color>{
            50: Color(0xFFFF9480),
            100: Color(0xFFFF9480),
            200: Color(0xFFFF9480),
            300: Color(0xFFFF9480),
            400: Color(0xFFFF9480),
            500: Color(0xFFFF9480),
            600: Color(0xFFFF9480),
            700: Color(0xFFFF9480),
            800: Color(0xFFFF9480),
            900: Color(0xFFFF9480),
        },
    );
    const int _orangePrimaryValue = 0xFFFF9480;
    
  5. Go to your main.dart file and place this code in your theme

    theme:ThemeData(
        primarySwatch: primaryOrange,
    ),
    
  6. Import the color folder in your main.dart like this import 'colors/colors.dart';

How do I give PHP write access to a directory?

Best way in giving write access to a directory..

$dst = "path/to/directory";
mkdir($dst); 
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");

C# : changing listbox row color?

How about

      MyLB is a listbox

        Label ll = new Label();
        ll.Width = MyLB.Width;
        ll.Content = ss;
        if(///<some condition>///)
            ll.Background = Brushes.LightGreen;
        else
            ll.Background = Brushes.LightPink;
        MyLB.Items.Add(ll);

Today's Date in Perl in MM/DD/YYYY format

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Strings and character with printf

The thing is that the printf function needs a pointer as parameter. However a char is a variable that you have directly acces. A string is a pointer on the first char of the string, so you don't have to add the * because * is the identifier for the pointer of a variable.

Limit the length of a string with AngularJS

I know this is late, but in the latest version of angularjs (I'm using 1.2.16) the limitTo filter supports strings as well as arrays so you can limit the length of the string like this:

{{ "My String Is Too Long" | limitTo: 9 }}

which will output:

My String

img tag displays wrong orientation

It's the EXIF data that your Samsung phone incorporates.

How to unpack pkl file?

The pickle (and gzip if the file is compressed) module need to be used

NOTE: These are already in the standard Python library. No need to install anything new

Change all files and folders permissions of a directory to 644/755

The shortest one I could come up with is:

chmod -R a=r,u+w,a+X /foo

which works on GNU/Linux, and I believe on Posix in general (from my reading of: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/chmod.html).

What this does is:

  1. Set file/directory to r__r__r__ (0444)
  2. Add w for owner, to get rw_r__r__ (0644)
  3. Set execute for all if a directory (0755 for dir, 0644 for file).

Importantly, the step 1 permission clears all execute bits, so step 3 only adds back execute bits for directories (never files). In addition, all three steps happen before a directory is recursed into (so this is not equivalent to e.g.

chmod -R a=r /foo
chmod -R u+w /foo
chmod -R a+X /foo

since the a=r removes x from directories, so then chmod can't recurse into them.)

String index out of range: 4

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

CSS horizontal scroll

You can use display:inline-block with white-space:nowrap. Write like this:

.scrolls {
    overflow-x: scroll;
    overflow-y: hidden;
    height: 80px;
    white-space:nowrap
}
.imageDiv img {
    box-shadow: 1px 1px 10px #999;
    margin: 2px;
    max-height: 50px;
    cursor: pointer;
    display:inline-block;
    *display:inline;/* For IE7*/
    *zoom:1;/* For IE7*/
    vertical-align:top;
 }

Check this http://jsfiddle.net/YbrX3/

getting file size in javascript

You can't get the file size of local files with javascript in a standard way using a web browser.

But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver

Best way to check for IE less than 9 in JavaScript without library

If I were you I would use conditional compilation or feature detection.
Here's another alternative:

<!--[if lt IE 9]><!-->
<script>
    var LTEIE8 = true;
</script>
<!--<![endif]-->

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

adding line break

Give this a try.

        FirmNames = String.Join(", \n", FirmNameList);

Converting pixels to dp

To convert dp to pixel

public static int dp2px(Resources resource, int dp) {
    return (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dp,resource.getDisplayMetrics()
    );
}

To convert pixel to dp.

public static float px2dp(Resources resource, float px)  {
    return (float)TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_PX,
        px,
        resource.getDisplayMetrics()
    );
}

where resource is context.getResources().

Ant is using wrong java version

You can run the ant task echoproperties and look for "java.version" or ant -v and look for "Java version", e.g. on my machine

ant echoproperties | grep java.version

shows

[echoproperties] java.version=11.0.9.1

and

ant -v | grep -i "java version"

shows

Detected Java version: 11 in: /opt/java/zulu11.43.55-ca-jdk11.0.9.1-linux_x64

JavaScript array to CSV

I created this code for creating a nice, readable csv files:

var objectToCSVRow = function(dataObject) {
    var dataArray = new Array;
    for (var o in dataObject) {
        var innerValue = dataObject[o]===null?'':dataObject[o].toString();
        var result = innerValue.replace(/"/g, '""');
        result = '"' + result + '"';
        dataArray.push(result);
    }
    return dataArray.join(' ') + '\r\n';
}

var exportToCSV = function(arrayOfObjects) {

    if (!arrayOfObjects.length) {
        return;
    }

    var csvContent = "data:text/csv;charset=utf-8,";

    // headers
    csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));

    arrayOfObjects.forEach(function(item){
        csvContent += objectToCSVRow(item);
    }); 

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "customers.csv");
    document.body.appendChild(link); // Required for FF
    link.click();
    document.body.removeChild(link); 
}

In your case, since you use arrays in array instead of objects in array, You will skip the header part, but you could add the column names yourself by putting this instead of that part:

// headers
csvContent += '"Column name 1" "Column name 2" "Column name 3"\n';

The secret is that a space separates the columns in the csv file, and we put the column values in the double quotes to allow spaces, and escape any double quotes in the values themselves.

Also note that I replace null values with empty string, because that suited my needs, but you can change that and replace it with anything you like.

How can I concatenate two arrays in Java?

I think the best solution with generics would be:

/* This for non primitive types */
public static <T> T[] concatenate (T[]... elements) {

    T[] C = null;
    for (T[] element: elements) {
        if (element==null) continue;
        if (C==null) C = (T[]) Array.newInstance(element.getClass().getComponentType(), element.length);
        else C = resizeArray(C, C.length+element.length);

        System.arraycopy(element, 0, C, C.length-element.length, element.length);
    }

    return C;
}

/**
 * as far as i know, primitive types do not accept generics 
 * http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types
 * for primitive types we could do something like this:
 * */
public static int[] concatenate (int[]... elements){
    int[] C = null;
    for (int[] element: elements) {
        if (element==null) continue;
        if (C==null) C = new int[element.length];
        else C = resizeArray(C, C.length+element.length);

        System.arraycopy(element, 0, C, C.length-element.length, element.length);
    }
    return C;
}

private static <T> T resizeArray (T array, int newSize) {
    int oldSize =
            java.lang.reflect.Array.getLength(array);
    Class elementType =
            array.getClass().getComponentType();
    Object newArray =
            java.lang.reflect.Array.newInstance(
                    elementType, newSize);
    int preserveLength = Math.min(oldSize, newSize);
    if (preserveLength > 0)
        System.arraycopy(array, 0,
                newArray, 0, preserveLength);
    return (T) newArray;
}

Convert txt to csv python script

I suposse this is the output you need:

title,intro,tagline

2.9,Gardena,CA

It can be done with this changes to your code:

import csv
import itertools

with open('log.txt', 'r') as in_file:
    lines = in_file.read().splitlines()
    stripped = [line.replace(","," ").split() for line in lines]
    grouped = itertools.izip(*[stripped]*1)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        for group in grouped:
            writer.writerows(group)

How to "comment-out" (add comment) in a batch/cmd?

You can add comments to the end of a batch file with this syntax:

@echo off
:: Start of code
...
:: End of code

(I am a comment
So I am!
This can be only at the end of batch files

Just make sure you never use a closing parentheses.

Attributions: Leo Guttirez Ramirez on https://www.robvanderwoude.com/comments.php

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

(Windows Only)

To kill a process you first need to find the Process Id (pid)

By running the command :

netstat -ano | findstr :yourPortNumber

As shown in picture below

You will get your Process Id (PID), Now to kill the same process run this command:

taskkill /pid yourid /f

enter image description here

jQuery $(this) keyword

I'm going to show you an example that will help you to understand why it's important.

Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that?
Actually, that's why we use $(this)

**Please check the code and run it :) ** enter image description here

_x000D_
_x000D_
  (function(){ _x000D_
_x000D_
            jQuery(".single-content-area").hover(function(){_x000D_
                jQuery(this).find(".hidden-content").slideDown();_x000D_
            })_x000D_
_x000D_
            jQuery(".single-content-area").mouseleave(function(){_x000D_
                jQuery(this).find(".hidden-content").slideUp();_x000D_
            })_x000D_
             _x000D_
        })();
_x000D_
  .mycontent-wrapper {_x000D_
      display: flex;_x000D_
      width: 800px;_x000D_
      margin: auto;_x000D_
    }     _x000D_
    .single-content-area  {_x000D_
        background-color: #34495e;_x000D_
        color: white;  _x000D_
        text-align: center;_x000D_
        padding: 20px;_x000D_
        margin: 15px;_x000D_
        display: block;_x000D_
        width: 33%;_x000D_
    }_x000D_
    .hidden-content {_x000D_
        display: none;_x000D_
    }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="mycontent-wrapper">_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
_x000D_
    <div class="single-content-area">_x000D_
        <div class="content">_x000D_
            Name: John Doe <br/>_x000D_
            Age: 33  <br/>_x000D_
            Addres: Bangladesh_x000D_
        </div> <!--/.normal-content-->_x000D_
        <div class="hidden-content">_x000D_
            This is hidden content_x000D_
        </div> <!--/.hidden-content-->_x000D_
    </div><!--/.single-content-area-->_x000D_
_x000D_
</div><!--/.mycontent-wrapper-->
_x000D_
_x000D_
_x000D_

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

^[A-Za-z](\W|\w)*

(\W|\w) will ensure that every subsequent letter is word(\w) or non word(\W)

instead of (\W|\w)* you can also use .* where . means absolutely anything just like (\w|\W)

Javascript Print iframe contents only

an alternate option, which may or may not be suitable, but cleaner if it is:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.

initialize a numpy array

Array analogue for the python's

a = []
for i in range(5):
    a.append(i)

is:

import numpy as np

a = np.empty((0))
for i in range(5):
    a = np.append(a, i)

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

Using CookieContainer with WebClient class

Yes. IMHO, overriding GetWebRequest() is the best solution to WebClient's limited functionalty. Before I knew about this option, I wrote lots of really painful code at the HttpWebRequest layer because WebClient almost, but not quite, did what I needed. Derivation is much easier.

Another option is to use the regular WebClient class, but manually populate the Cookie header before making the request and then pull out the Set-Cookies header on the response. There are helper methods on the CookieContainer class which make creating and parsing these headers easier: CookieContainer.SetCookies() and CookieContainer.GetCookieHeader(), respectively.

I prefer the former approach since it's easier for the caller and requires less repetitive code than the second option. Also, the derivation approach works the same way for multiple extensibility scenarios (e.g. cookies, proxies, etc.).

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

How to open local file on Jupyter?

Install jupyter. Open terminal. Go to folder where you file is (in terminal ie.cd path/to/folder). Run jupyter notebook. And voila: you have something like this:

enter image description here

Notice that to open a notebook in the folder, you can either click on it in the browser or go to address:

http://localhost:8888/notebooks/name_of_your_file.ipynb

How to make Bootstrap carousel slider use mobile left/right swipe

If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.

NOTE: ngx-bootstrap is used.

import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';

@Directive({
  selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
  @Input() swipeThreshold = 50;
  private start: number;
  private stillMoving: boolean;
  private moveListener: Function;

  constructor(
    @Host() @Self() @Optional() private carousel: CarouselComponent,
    private renderer: Renderer2,
    private element: ElementRef
  ) {
  }

  ngOnInit(): void {
    if ('ontouchstart' in document.documentElement) {
      this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
      this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
    }
  }

  private onTouchStart(e: TouchEvent): void {
    if (e.touches.length === 1) {
      this.start = e.touches[0].pageX;
      this.stillMoving = true;
      this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
    }
  }

  private onTouchMove(e: TouchEvent): void {
    if (this.stillMoving) {
      const x = e.touches[0].pageX;
      const difference = this.start - x;
      if (Math.abs(difference) >= this.swipeThreshold) {
        this.cancelTouch();
        if (difference > 0) {
          if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
            this.carousel.activeSlide = this.carousel.activeSlide + 1;
          }
        } else {
          if (this.carousel.activeSlide > 0) {
            this.carousel.activeSlide = this.carousel.activeSlide - 1;
          }
        }
      }
    }
  }

  private onTouchEnd(e: TouchEvent): void {
    this.cancelTouch();
  }

  private cancelTouch() {
    if (this.moveListener) {
      this.moveListener();
      this.moveListener = undefined;
    }
    this.start = null;
    this.stillMoving = false;
  }
}

in html:

<carousel appCarouselSwipe>

    ...

</carousel>

Reference

Android Studio - Gradle sync project failed

I have encountered this problem And I solved it as follows: File->Sync Project with Gradle Files

good luck!

Configure DataSource programmatically in Spring Boot

If you're using latest spring boot (with jdbc starter and Hikari) you'll run into: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName. To solve this:

  1. In your application.properties:

datasource.oracle.url=youroracleurl

  1. In your application define as bean (@Primary is mandatory!):
@Bean
@Primary
@ConfigurationProperties("datasource.oracle")
public DataSourceProperties getDatasourceProperties() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("datasource.oracle")
public DataSource getDatasource() {
    return getDatasourceProperties().initializeDataSourceBuilder()
           .username("username")
           .password("password")
           .build();
}

Creating a jQuery object from a big HTML-string

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

Is Visual Studio Community a 30 day trial?

For my case the problem was in fact that i broke machine.config and looks like VS couldn't have a connection I've added the following lines to my machine.config

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
<!--
-->

After replacing the previous section to:

<!--
<system.net>
 <defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
 </defaultProxy>
</system.net>
-->

VS started to work.

How to check whether a Button is clicked by using JavaScript

Just hook up the onclick event:

<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>

cmake - find_library - custom library location

I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in

CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake

(which can be set through an environment variable). So for example the boost configuration is in the path

CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake

In that configuration you can set variables. My config file for boost looks like that:

set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS}) 
    set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
    set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )

Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.

Hope this this is helpful for other people.

Detecting which UIButton was pressed in a UITableView

I use a solution that subclass UIButton and I thought I should just share it here, codes in Swift:

class ButtonWithIndexPath : UIButton {
    var indexPath:IndexPath?
}

Then remember to update it's indexPath in cellForRow(at:)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let returnCell = tableView.dequeueReusableCell(withIdentifier: "cellWithButton", for: indexPath) as! cellWithButton
    ...
    returnCell.button.indexPath = IndexPath
    returnCell.button.addTarget(self, action:#selector(cellButtonPressed(_:)), for: .touchUpInside)

    return returnCell
}

So when responding to the button's event you can use it like

func cellButtonPressed(_ sender:UIButton) {
    if sender is ButtonWithIndexPath {
        let button = sender as! ButtonWithIndexPath
        print(button.indexPath)
    }
}

Hot deploy on JBoss - how do I make JBoss "see" the change?

Just my two cents:

  • Cold deployment is the way of deploying an application when you stop it (or stop the whole server), then you install the new version, and finally restart the application (or start the whole server). It's suitable for official production deployments, but it would be horrible slow to do this during development. Forget about rapid development if you are doing this.

  • Auto deployment is the ability the server has to re-scan periodically for a new EAR/WAR and deploy it automagically behind the scenes for you, or for the IDE (Eclipse) to deploy automagically the whole application when you make changes to the source code. JBoss does this, but JBoss's marketing department call this misleadingly "hot deployment". An auto deployment is not as slow compared to a cold deployment, but is really slow compared to a hot deployment.

  • Hot deployment is the ability to deploy behind the scenes "as you type". No need to redeploy the whole application when you make changes. Hot deployment ONLY deploys the changes. You change a Java source code, and voila! it's running already. You never noticed it was deploying it. JBoss cannot do this, unless you buy for JRebel (or similar) but this is too much $$ for me (I'm cheap).

Now my "sales pitch" :D

What about using Tomcat during development? Comes with hot deployment all day long... for free. I do that all the time during development and then I deploy on WebSphere, JBoss, or Weblogic. Don't get me wrong, these three are great for production, but are really AWFUL for rapid-development on your local machine. Development productivity goes down the drain if you use these three all day long.

In my experience, I stopped using WebSphere, JBoss, and Weblogic for rapid development. I still have them installed in my local environment, though, but only for the occasional test I may need to run. I don't pay for JRebel all the while I get awesome development speed. Did I mention Tomcat is fully compatible with JBoss?

Tomcat is free and not only has auto-deployment, but also REAL hot deployment (Java code, JSP, JSF, XHTML) as you type in Eclipse (Yes, you read well). MYKong has a page (https://www.mkyong.com/eclipse/how-to-configure-hot-deploy-in-eclipse/) with details on how to set it up.

Did you like my sales pitch?

Cheers!

c# open a new form then close the current form?

If you have two forms: frm_form1 and frm_form2 .The following code is use to open frm_form2 and close frm_form1.(For windows form application)

        this.Hide();//Hide the 'current' form, i.e frm_form1 
        //show another form ( frm_form2 )   
        frm_form2 frm = new frm_form2();
        frm.ShowDialog();
        //Close the form.(frm_form1)
        this.Close();

How to rename a file using svn?

Using TortoiseSVN worked easily on Windows for me.

http://tortoisesvn.net/

Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok

Using SVN 1.8.8 TortoiseSVN version 1.8.5

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

How can I check if a background image is loaded?

Something like this:

var $div = $('div'),
  bg = $div.css('background-image');
  if (bg) {
    var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
      $img = $('<img>').attr('src', src).on('load', function() {
        // do something, maybe:
        $div.fadeIn();
      });
  }
});

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

1.To install the virtualization driver:

Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager. After the download completes, execute /extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe. Follow the on-screen instructions to complete installation.

2.If it show any problem restart your computer and inter in BIOS an enable Virtualization Technology ...

3.To see your possessor is capable to virtualization go to the bellow link http://ark.intel.com/Products/VirtualizationTechnology

Modifying the "Path to executable" of a windows service

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:

sc config <service name> binPath= <binary path>

Note: the space after binPath= is important. You can also query the current configuration using:

sc qc <service name>

This displays output similar to:

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: ServiceName

    TYPE               : 10  WIN32_OWN_PROCESS
    START_TYPE         : 2   AUTO_START
    ERROR_CONTROL      : 1   NORMAL
    BINARY_PATH_NAME   : C:\Services\ServiceName
    LOAD_ORDER_GROUP   :
    TAG                : 0
    DISPLAY_NAME       : <Display name>
    DEPENDENCIES       :
    SERVICE_START_NAME : user-name@domain-name

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

How to extend / inherit components?

If anyone is looking for an updated solution, Fernando's answer is pretty much perfect. Except that ComponentMetadata has been deprecated. Using Component instead worked for me.

The full Custom Decorator CustomDecorator.ts file looks like this:

import 'zone.js';
import 'reflect-metadata';
import { Component } from '@angular/core';
import { isPresent } from "@angular/platform-browser/src/facade/lang";

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        // verify is annotation typeof function
        if(typeof annotation[key] === 'function'){
          annotation[key] = annotation[key].call(this, parentAnnotation[key]);
        }else if(
          // force override in annotation base
          !isPresent(annotation[key])
        ){
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    var metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

Then import it in to your new component sub-component.component.ts file and use @CustomComponent instead of @Component like this:

import { CustomComponent } from './CustomDecorator';
import { AbstractComponent } from 'path/to/file';

...

@CustomComponent({
  selector: 'subcomponent'
})
export class SubComponent extends AbstractComponent {

  constructor() {
    super();
  }

  // Add new logic here!
}

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I am adding it so that someone in a similar situation might find it helpful.

So, even after multiDexEnabled = true I was getting the same error. I had no duplicate libraries. None of the above solutions worked. Upon reading the error log, I found OutOfMemError issue to be the primary reason and thought of changing the heap size somehow. Hence, this -

dexOptions {
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }

Where "4g" means HeapSize of 4 GB. And it worked! I hope it does for you too.

Maximum number of rows in an MS Access database engine table?

Practical = 'useful in practice' - so the best you're going to get is anecdotal. Everything else is just prototyping and testing results.

I agree with others - determining 'a max quantity of records' is completely dependent on schema - # tables, # fields, # indexes.

Another anecdote for you: I recently hit 1.6GB file size with 2 primary data stores (tables), of 36 and 85 fields respectively, with some subset copies in 3 additional tables.

Who cares if data is unique or not - only material if context says it is. Data is data is data, unless duplication affects handling by the indexer.

The total row counts making up that 1.6GB is 1.72M.

How to set dropdown arrow in spinner?

One simple way is to wrap your Spinner + Drop Down Arrow Image inside a Layout. Set the background of Spinner as transparent so that the default arrow icon gets hidden. Something like this:

 <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:orientation="horizontal">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="4"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:spinnerMode="dropdown" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="showDropDown"
            android:src="@drawable/ic_chevron_down_blue" />

    </LinearLayout>

Here background.xml is a drawable to produce a box type background.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
    <corners android:radius="2dp" />
    <stroke
        android:width="1dp"
        android:color="#BDBDBD" />
</shape>

The above code produces this type of a Spinner and icon.

Spinner with a custom drop down arrow

When to use: Java 8+ interface default method, vs. abstract method

Default methods in Java Interface are to be used more for providing dummy implementation of a function thus saving any implementing class of that interface from the pain of declaring all the abstract methods even if they want to deal with only one. Default methods in interface are thus in a way more a replacement for the concept of adapter classes.

The methods in abstract class are however supposed to give a meaningful implementation which any child class should override only if needed to override a common functionality.

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

This tells you the date of the number of seconds in future from the moment you execute the code.

time = Time.new + 1000000000 #date in 1 billion seconds

puts(time)

according to the current time I am answering the question it prints 047-05-14 05:16:16 +0000 (1 billion seconds in future)

or if you want to count billion seconds from a particular time, it's in format Time.mktime(year, month,date,hours,minutes)

time = Time.mktime(1987,8,18,6,45) + 1000000000

puts("I would be 1 Billion seconds old on: "+time)

How to create a simple proxy in C#?

Proxy can work in the following way.

Step1, configure client to use proxyHost:proxyPort.

Proxy is a TCP server that is listening on proxyHost:proxyPort. Browser opens connection with Proxy and sends Http request. Proxy parses this request and tries to detect "Host" header. This header will tell Proxy where to open connection.

Step 2: Proxy opens connection to the address specified in the "Host" header. Then it sends HTTP request to that remote server. Reads response.

Step 3: After response is read from remote HTTP server, Proxy sends the response through an earlier opened TCP connection with browser.

Schematically it will look like this:

Browser                            Proxy                     HTTP server
  Open TCP connection  
  Send HTTP request  ----------->                       
                                 Read HTTP header
                                 detect Host header
                                 Send request to HTTP ----------->
                                 Server
                                                      <-----------
                                 Read response and send
                   <-----------  it back to the browser
Render content

TreeMap sort by value

A lot of people hear adviced to use List and i prefer to use it as well

here are two methods you need to sort the entries of the Map according to their values.

    static final Comparator<Entry<?, Double>> DOUBLE_VALUE_COMPARATOR = 
        new Comparator<Entry<?, Double>>() {
            @Override
            public int compare(Entry<?, Double> o1, Entry<?, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        };

        static final List<Entry<?, Double>> sortHashMapByDoubleValue(HashMap temp)
        {
            Set<Entry<?, Double>> entryOfMap = temp.entrySet();

            List<Entry<?, Double>> entries = new ArrayList<Entry<?, Double>>(entryOfMap);
            Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
            return entries;
        }

Xcode 10 Error: Multiple commands produce

The multiple produce error was being triggered by a hidden file for me (.gitkeep) Look at your compile sources closely, I believe this file was in Compile Sources but it shows up as an empty row. It doesn't actually say the hidden file's name, but I deleted the blank row and it fixed the issue, so I suspect the project navigator doesn't show hidden files.

How to recursively list all the files in a directory in C#?

Here is a version of B. Clay Shannon's code not static for excel-files:

class ExcelSearcher
{
    private List<string> _fileNames;

    public ExcelSearcher(List<string> filenames)
    {
        _fileNames = filenames;
    }
    public List<string> GetExcelFiles(string dir, List<string> filenames = null)
    {

        string dirName = dir;
        var dirNames = new List<string>();
        if (filenames != null)
        {
            _fileNames.Concat(filenames);
        }
        try
        {
            foreach (string f in Directory.GetFiles(dirName))
            {
                if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                {
                    _fileNames.Add(f);
                }
            }
            dirNames = Directory.GetDirectories(dirName).ToList();
            foreach (string d in dirNames)
            {
                GetExcelFiles(d, _fileNames);
            }
        }
        catch (Exception ex)
        {
            //Bam
        }
        return _fileNames;
    }

Why is null an object and what's the difference between null and undefined?

From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas

But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)

Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.

That said:

var game = null; //typeof(game) is "object"

game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {}; 
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;

Undefined case:

var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.

isset in jQuery?

if (($("#one").length > 0)){
   alert('yes');
}

if (($("#two").length > 0)){
   alert('yes');
}

if (($("#three").length > 0)){
   alert('yes');
}

if (($("#four")).length == 0){
   alert('no');
}

This is what you need :)

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

How do I set up Vim autoindentation properly for editing Python files?

A simpler option: just uncomment the following part of the configuration (which is originally commented out) in the /etc/vim/vimrc file:

    if has("autocmd")
      filetype plugin indent on
    endif

Count Rows in Doctrine QueryBuilder

Here is another way to format the query:

return $repository->createQueryBuilder('u')
            ->select('count(u.id)')
            ->getQuery()
            ->getSingleScalarResult();

What is IllegalStateException?

Illegal State Exception is an Unchecked exception.

It indicate that method has been invoked at wrong time.

example:

Thread t = new Thread();
t.start();
//
//
t.start();

output:

Runtime Excpetion: IllegalThreadStateException

We cant start the Thread again, it will throw IllegalStateException.

How to set NODE_ENV to production/development in OS X

On OSX I'd recommend adding export NODE_ENV=development to your ~/.bash_profile and/or ~/.bashrc and/or ~/.profile.

Personally I add that entry to my ~/.bashrc and then have the ~/.bash_profile ~/.profile import the contents of that file, so it's consistent across environments.

After making these additions, be sure to restart your terminal to pick up settings.

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

string minusvalue = TextBox1.Text.ToString();

if (Convert.ToDouble(minusvalue) < 0)
{ 
    // set color of text in TextBox1 to red color and bold.
    TextBox1.ForeColor = Color.Red;
}

Uninstall Django completely

Use Python shell to find out the path of Django:

>>> import django
>>> django
<module 'django' from '/usr/local/lib/python2.7/dist-packages/django/__init__.pyc'>

Then remove it manually:

sudo rm -rf /usr/local/lib/python2.7/dist-packages/django/

How to get a cross-origin resource sharing (CORS) post request working

For some reason, a question about GET requests was merged with this one, so I'll respond to it here.

This simple function will asynchronously get an HTTP status reply from a CORS-enabled page. If you run it, you'll see that only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.

The following can be easily modified to get the data held in the xmlHttpRequestObject object:

_x000D_
_x000D_
function checkCorsSource(source) {_x000D_
  var xmlHttpRequestObject;_x000D_
  if (window.XMLHttpRequest) {_x000D_
    xmlHttpRequestObject = new XMLHttpRequest();_x000D_
    if (xmlHttpRequestObject != null) {_x000D_
      var sUrl = "";_x000D_
      if (source == "google") {_x000D_
        var sUrl = "https://www.google.com";_x000D_
      } else {_x000D_
        var sUrl = "https://httpbin.org/get";_x000D_
      }_x000D_
      document.getElementById("txt1").innerHTML = "Request Sent...";_x000D_
      xmlHttpRequestObject.open("GET", sUrl, true);_x000D_
      xmlHttpRequestObject.onreadystatechange = function() {_x000D_
        if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response received!";_x000D_
        } else {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response failed!";_x000D_
        }_x000D_
      }_x000D_
      xmlHttpRequestObject.send();_x000D_
    } else {_x000D_
      window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Check if page is cors</title>_x000D_
</head>_x000D_
<body>_x000D_
  <p>A CORS-enabled source has one of the following HTTP headers:</p>_x000D_
  <ul>_x000D_
    <li>Access-Control-Allow-Headers: *</li>_x000D_
    <li>Access-Control-Allow-Headers: x-requested-with</li>_x000D_
  </ul>_x000D_
  <p>Click a button to see if the page allows CORS</p>_x000D_
  <form name="form1" action="" method="get">_x000D_
    <input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">_x000D_
    <input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">_x000D_
  </form>_x000D_
  <p id="txt1" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

How can I pass some data from one controller to another peer controller

Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    });