Programs & Examples On #Tesla

Nvidia Tesla is a brand of GPUs targeting the high performance computing market.

How can I change column types in Spark SQL's DataFrame?

Using Spark Sql 2.4.0 you can do that:

spark.sql("SELECT STRING(NULLIF(column,'')) as column_string")

AttributeError: 'module' object has no attribute 'urlretrieve'

Suppose you have following lines of code

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)

If you are receiving following error message

AttributeError: module 'urllib' has no attribute 'urlretrieve'

Then you should try following code to fix the issue:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

Awaiting multiple Tasks with different results

var dn = await Task.WhenAll<dynamic>(FeedCat(),SellHouse(),BuyCar());

if you want to access Cat, you do this:

var ct = (Cat)dn[0];

This is very simple to do and very useful to use, there is no need to go after a complex solution.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I had the similar issue for my Spring Boot - Gradle application running on Eclipse Luna. I could resolve it by manually adding an entry in my project's .classpath

<classpathentry sourcepath="C:/Users/<username>/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-simple/1.7.7/3150039466ad03e6ef1c7ec1c2cbb0d96710cf64/slf4j-simple-1.7.7-sources.jar" kind="lib" path="C:/Users/<username>/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-simple/1.7.7/8095d0b9f7e0a9cd79a663c740e0f8fb31d0e2c8/slf4j-simple-1.7.7.jar"/>

Idea is to follow this solution. But how to implement is dependent on case to case. One way of fixing is the one that I used above.

Hope this helps.

How to add 20 minutes to a current date?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

How to create a batch file to run cmd as administrator

this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.

@echo off
mkdir C:\Users\cmdfolder

if echo=="Access is denied." (goto :1A) else (goto :A4)

:A1
cls 
color 0d
echo restart this program as administator

:A4
pause

jquery multiple checkboxes array

If you have a class for each of your input box, then you can do it as

        var checked = []
        $('input.Booking').each(function ()
        {
            checked.push($(this).val());
        });

How to run a PowerShell script from a batch file

Small sample test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...

Where does Chrome store extensions?

Another alternative is to do right click on the chrome icon and then go to shortcut tab (according to windows 10). You will see there "Target", copy the path and remove "chrome.exe".

How do I install command line MySQL client on mac?

Using MacPorts you can install the client with:

sudo port install mysql57

You also need to select the installed version as your mysql

sudo port select mysql mysql57

The server is only installed if you append -server to the package name (e.g. mysql57-server)

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Image Example

How to install the JDK on Ubuntu Linux

You can install via apt-get:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt-get install oracle-java11-installer

After, do not forget to check the version:

java -version

How to use random in BATCH script?

now featuring all the colors of the dos rainbow

@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)
  ELSE set C=1&set D=A&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
set V=%D%

(IF %V% EQU 10 set V=A) 
    & (IF %V% EQU 11 set V=B)
    & (IF %V% EQU 12 set V=C)
    & (IF %V% EQU 13 set V=D) 
    & (IF %V% EQU 14 set V=E)
    & (IF %V% EQU 15 set V=F)
title %random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %V%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%
&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&IF %D% EQU 15 (set D=1)ELSE set /A D=%D%+1)
  ELSE set /A C=%C%+1)&goto Y

How to use a jQuery plugin inside Vue

There's a much, much easier way. Do this:

MyComponent.vue

<template>
  stuff here
</template>
<script>
  import $ from 'jquery';
  import 'selectize';

  $(function() {
      // use jquery
      $('body').css('background-color', 'orange');

      // use selectize, s jquery plugin
      $('#myselect').selectize( options go here );
  });

</script>

Make sure JQuery is installed first with npm install jquery. Do the same with your plugin.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Uncomment the line extension=php_mysql.dll in your "php.ini" file and restart Apache.

Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.

See more about installing MySQL extension in manual.

P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

PivotTable's Report Filter using "greater than"

In an Excel pivot table, you are correct that a filter only allows values that are explicitly selected. If the filter field is placed on the pivot table rows or columns, however, you get a much wider set of Label Filter conditions, including Greater Than. If you did that in your case, then the added benefit would be that the various probability levels that match your condition are shown in the body of the table.

How do I remove trailing whitespace using a regular expression?

The platform is not specified, but in C# (.NET) it would be:

Regular expression (presumes the multiline option - the example below uses it):

    [ \t]+(\r?$)

Replacement:

    $1

For an explanation of "\r?$", see Regular Expression Options, Multiline Mode (MSDN).

Code example

This will remove all trailing spaces and all trailing TABs in all lines:

string inputText = "     Hello, World!  \r\n" +
                   "  Some other line\r\n" +
                   "     The last line  ";
string cleanedUpText = Regex.Replace(inputText,
                                     @"[ \t]+(\r?$)", @"$1",
                                     RegexOptions.Multiline);

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder

for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I resolved the same issue by running Workbench as administrator.

...I guess it's because of restrictions on company computers, in my case...

How can I remove file extension from a website address?

just nearly the same with the first answer about, but some more advantage.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Just add up if you have a other file-extension in your sites

Node.js check if file exists

fs.exists has been deprecated since 1.0.0. You can use fs.stat instead of that.

var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this 
}  
else { // do this 
}});

Here is the link for the documentation fs.stats

Use async await with Array.map

I'd recommend using Promise.all as mentioned above, but if you really feel like avoiding that approach, you can do a for or any other loop:

const arr = [1,2,3,4,5];
let resultingArr = [];
for (let i in arr){
  await callAsynchronousOperation(i);
  resultingArr.push(i + 1)
}

Rounding a variable to two decimal places C#

You can round the result and use string.Format to set the precision like this:

decimal pay = 200.5555m;
pay = Math.Round(pay + bonus, 2);
string payAsString = string.Format("{0:0.00}", pay);

Running multiple async tasks and waiting for them all to complete

The best option I've seen is the following extension method:

public static Task ForEachAsync<T>(this IEnumerable<T> sequence, Func<T, Task> action) {
    return Task.WhenAll(sequence.Select(action));
}

Call it like this:

await sequence.ForEachAsync(item => item.SomethingAsync(blah));

Or with an async lambda:

await sequence.ForEachAsync(async item => {
    var more = await GetMoreAsync(item);
    await more.FrobbleAsync();
});

How can I convert a VBScript to an executable (EXE) file?

There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.

Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.

Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.

In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.

Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.

How can I add a hint text to WPF textbox?

You can do in a very simple way. The idea is to place a Label in the same place as your textbox. Your Label will be visible if textbox has no text and hasn't the focus.

 <Label Name="PalceHolder"  HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40" VerticalAlignment="Top" Width="239" FontStyle="Italic"  Foreground="BurlyWood">PlaceHolder Text Here
  <Label.Style>
    <Style TargetType="{x:Type Label}">
      <Setter Property="Visibility" Value="Hidden"/>
      <Style.Triggers>
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding ="{Binding ElementName=PalceHolder, Path=Text.Length}" Value="0"/>
            <Condition Binding ="{Binding ElementName=PalceHolder, Path=IsFocused}" Value="False"/>
          </MultiDataTrigger.Conditions>
          <Setter Property="Visibility" Value="Visible"/>
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>
  </Label.Style>
</Label>
<TextBox  Background="Transparent" Name="TextBox1" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40"TextWrapping="Wrap" Text="{Binding InputText,Mode=TwoWay}" VerticalAlignment="Top" Width="239" />

Bonus:If you want to have default value for your textBox, be sure after to set it when submitting data (for example:"InputText"="PlaceHolder Text Here" if empty).

Create html documentation for C# code

The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).

How do function pointers in C work?

One of the big uses for function pointers in C is to call a function selected at run-time. For example, the C run-time library has two routines, qsort and bsearch, which take a pointer to a function that is called to compare two items being sorted; this allows you to sort or search, respectively, anything, based on any criteria you wish to use.

A very basic example, if there is one function called print(int x, int y) which in turn may require to call a function (either add() or sub(), which are of the same type) then what we will do, we will add one function pointer argument to the print() function as shown below:

#include <stdio.h>

int add()
{
   return (100+10);
}

int sub()
{
   return (100-10);
}

void print(int x, int y, int (*func)())
{
    printf("value is: %d\n", (x+y+(*func)()));
}

int main()
{
    int x=100, y=200;
    print(x,y,add);
    print(x,y,sub);

    return 0;
}

The output is:

value is: 410
value is: 390

Using Application context everywhere?

It is a good approach. I use it myself as well. I would only suggest to override onCreate to set the singleton instead of using a constructor.

And since you mentioned SQLiteOpenHelper: In onCreate () you can open the database as well.

Personally I think the documentation got it wrong in saying that There is normally no need to subclass Application. I think the opposite is true: You should always subclass Application.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

When I find myself thinking about using Manager or Helper in a class name, I consider it a code smell that means I haven't found the right abstraction yet and/or I'm violating the single responsibility principle, so refactoring and putting more effort into design often makes naming much easier.

But even well-designed classes don't (always) name themselves, and your choices partly depend on whether you're creating business model classes or technical infrastructure classes.

Business model classes can be hard, because they're different for every domain. There are some terms I use a lot, like Policy for strategy classes within a domain (e.g., LateRentalPolicy), but these usually flow from trying to create a "ubiquitous language" that you can share with business users, designing and naming classes so they model real-world ideas, objects, actions, and events.

Technical infrastructure classes are a bit easier, because they describe domains we know really well. I prefer to incorporate design pattern names into the class names, like InsertUserCommand, CustomerRepository, or SapAdapter. I understand the concern about communicating implementation instead of intent, but design patterns marry these two aspects of class design - at least when you're dealing with infrastructure, where you want the implementation design to be transparent even while you're hiding the details.

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
  • Here is an example of request execution process in its simplest form:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {
        response.close();
    }

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {
        httpclient.close();
    }

see the Reference to learn fundamentals.


@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something
    }

    //do something else with httpclient here
}

Find a pair of elements from an array whose sum equals a given number

Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:

def find_sum(arr,sum)
 result ={}
 h = Hash[arr.map {|i| [i,i]}]
 arr.each { |l| result[l] = sum-l  if h[sum-l] && !result[sum-l]  }
 result
end

To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l] instruction

How to change the new TabLayout indicator color and height

You can change this using xml

app:tabIndicatorColor="#fff"

Using ExcelDataReader to read Excel data starting from a particular cell

To be more clear, I will begin at the beginning.

I will rely on the sample code found in https://github.com/ExcelDataReader/ExcelDataReader, but with some modifications to avoid inconveniences.

The following code detects the file format, either xls or xlsx.

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader;

//1. Reading Excel file
if (Path.GetExtension(filePath).ToUpper() == ".XLS")
{
    //1.1 Reading from a binary Excel file ('97-2003 format; *.xls)
    excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
    //1.2 Reading from a OpenXml Excel file (2007 format; *.xlsx)
    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}

//2. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();

//3. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = false;

Now we can access the file contents in a more convenient way. I use DataTable for this. The following is an example to access a specific cell, and print its value in the console:

DataTable dt = result.Tables[0];
Console.WriteLine(dt.Rows[rowPosition][columnPosition]);

If you do not want to do a DataTable, you can do the same as follows:

Console.WriteLine(result.Tables[0].Rows[rowPosition][columnPosition]);

It is important not try to read beyond the limits of the table, for this you can see the number of rows and columns as follows:

Console.WriteLine(result.Tables[0].Rows.Count);
Console.WriteLine(result.Tables[0].Columns.Count);

Finally, when you're done, you should close the reader and free resources:

//5. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

I hope you find it useful.

(I understand that the question is old, but I make this contribution to enhance the knowledge base, because there is little material about particular implementations of this library).

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How do I use Notepad++ (or other) with msysgit?

git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Or, for 64-bit Windows and a 32-bit install of Notepad++:

git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Or, the following can be issued on the command line on either 32-bit or 64-bit Windows. It will pull the location of notepad++.exe from the registry and configure git to use it automatically:

FOR /F "usebackq tokens=2*" %A IN (`REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\notepad++.exe" /ve`) DO git config --global core.editor "'%B' -multiInst -notabbar -nosession -noPlugin"

If you wish to place the above from a .BAT or .CMD file, you must replace %A with %%A and %B with %%B

Should black box or white box testing be the emphasis for testers?

White Box Testing equals Software Unit Test. The developer or a development level tester (e.g. another developer) ensures that the code he has written is working properly according to the detailed level requirements before integrating it in the system.

Black Box Testing equals Integration Testing. The tester ensures that the system works according to the requirements on a functional level.

Both test approaches are equally important in my opinion.

A thorough unit test will catch defects in the development stage and not after the software has been integrated into the system. A system level black box test will ensure all software modules behave correctly when integrated together. A unit test in the development stage would not catch these defects since modules are usually developed independent from each other.

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

Custom pagination view in Laravel 5

For Laravel 5.3 (and may be in other 5.X versions) put custom pagination code in you view folder.

resources/views/pagination/default.blade.php

@if ($paginator->hasPages())
    <ul class="pagination">
        {{-- Previous Page Link --}}
        @if ($paginator->onFirstPage())
            <li class="disabled"><span>&laquo;</span></li>
        @else
            <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">&laquo;</a></li>
        @endif

        {{-- Pagination Elements --}}
        @foreach ($elements as $element)
            {{-- "Three Dots" Separator --}}
            @if (is_string($element))
                <li class="disabled"><span>{{ $element }}</span></li>
            @endif

            {{-- Array Of Links --}}
            @if (is_array($element))
                @foreach ($element as $page => $url)
                    @if ($page == $paginator->currentPage())
                        <li class="active"><span>{{ $page }}</span></li>
                    @else
                        <li><a href="{{ $url }}">{{ $page }}</a></li>
                    @endif
                @endforeach
            @endif
        @endforeach

        {{-- Next Page Link --}}
        @if ($paginator->hasMorePages())
            <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a></li>
        @else
            <li class="disabled"><span>&raquo;</span></li>
        @endif
    </ul>
@endif

then call this pagination view file from the main view file as

{{ $posts->links('pagination.default') }}

Update the pagination/default.blade.php however you want

It works in 8.x versions as well.

How to check if an int is a null

In Java there isn't Null values for primitive Data types. If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer. When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.

In this case you must use Inter instead of int

Try below snippet and see example for more info,

Integer id;
String name;

//Refer this example
    Integer val = 0;

`

if (val != null){
System.out.println("value is not null");
}

`

Also you can assign Null as below,

val = null;

Android Support Design TabLayout: Gravity Center and Mode Scrollable

I think a better approach will be to set app:tabMode="auto" and app:tabGravity="fill" because setting tabMode to fixed can make headings congested and cause headings to occupy multiple lines on the other side setting it to scrollable could make them leave spaces at the end in some screen sizes. manually setting tabMode would give a problem when dealing with multiple screen sizes

    <com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"       
    app:tabGravity="fill"
    android:textAlignment="center"
    app:tabMode="auto"
    />

Java Spring - How to use classpath to specify a file location?

looks like you have maven project and so resources are in classpath by

go for

getClass().getResource("classpath:storedProcedures.sql")

String index out of range: 4

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

What linux shell command returns a part of a string?

In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :

${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}

Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):

${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}

And of course, the much useful expansions that operate on whether the parameter is null:

${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}

They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution) combined with sed or any other external filter). But, they are so easily found by typing man bash that I don't feel it merits to further extend this post.

ASP.NET Core Get Json Array using IConfiguration

This worked for me to return an array of strings from my config:

var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
    .Get<string[]>();

My configuration section looks like this:

"AppSettings": {
    "CORS-Settings": {
        "Allow-Origins": [ "http://localhost:8000" ],
        "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
    }
}

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Remote desktop connection protocol error 0x112f

Server restart helped, I'm able to connect to server again.

How to filter an array from all elements of another array

The OA can also be implemented in ES6 as follows

ES6:

 const filtered = [1, 2, 3, 4].filter(e => {
    return this.indexOf(e) < 0;
  },[2, 4]);

Converting String to Double in Android

String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:

HTTP could not register URL http://+:12345/Foo.svc/]. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

How to set a default entity property value with Hibernate

i'am working with hibernate 5 and postgres, and this worked form me.

@Column(name = "ACCOUNT_TYPE", ***nullable***=false, columnDefinition="varchar2 default 'END_USER'")
@Enumerated(EnumType.STRING)
private AccountType accountType;

How do I convert a javascript object array to a string array of the object attribute I want?

Use the map() function native on JavaScript arrays:

var yourArray = [ {
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}];

var newArray = yourArray.map( function( el ){ 
                                return el.name; 
                               });

Spring configure @ResponseBody JSON format

You can configure the ObjectMapper as a bean in your Spring xml file. What holds a reference to the ObjectMapper is the MappingJacksonJsonView class. You then need to attach the view to a ViewResolver.

Something like this should work:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
      <property name="mediaTypes">
      <map>
        <entry key="json" value="application/json" />
        <entry key="html" value="text/html" />
      </map>
    </property>
    <property name="viewResolvers">
      <list>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/jsp/" />
          <property name="suffix" value=".jsp" />
        </bean>
      </list>
    </property>
    <property name="defaultViews">
      <list>
        <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
          <property name="prefixJson" value="false" />
          <property name="objectMapper" value="customObjectMapper" />
        </bean>
      </list>
    </property>
  </bean>

Where customObjectMapper is defined elsewhere in the xml file. Note that you can directly set Spring property values with the Enums Jackson defines; see this question.

Also, ContentNegotiatingViewResolver probably isn't required, it's just the code I am using in an existing project.

How do I add space between two variables after a print in Python

print( "hello " +k+ "  " +ln);

where k and ln are variables

`&mdash;` or `&#8212;` is there any difference in HTML output?

SGML parsers (or XML parsers in the case of XHTML) can handle &#8212; without having to process the DTD (which doesn't matter to browsers as they just slurp tag soup), while &mdash; is easier for humans to read and write in the source code.

Personally, I would stick to a literal em-dash and ensure that my character encoding settings were consistent.

java.util.regex - importance of Pattern.compile()?

When you compile the Pattern Java does some computation to make finding matches in Strings faster. (Builds an in-memory representation of the regex)

If you are going to reuse the Pattern multiple times you would see a vast performance increase over creating a new Pattern every time.

In the case of only using the Pattern once, the compiling step just seems like an extra line of code, but, in fact, it can be very helpful in the general case.

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

Import CSV file with mixed data types

I recommend looking at the dataset array.

The dataset array is a data type that ships with Statistics Toolbox. It is specifically designed to store hetrogeneous data in a single container.

The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features. The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".

http://www.mathworks.com/products/statistics/demos.html

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

How can one print a size_t variable portably using the printf family?

Looks like it varies depending on what compiler you're using (blech):

...and of course, if you're using C++, you can use cout instead as suggested by AraK.

How to create a responsive image that also scales up in Bootstrap 3

Try the following in your CSS stylesheet:

.img-responsive{
  max-width: 100%;
  height: auto;
}

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

Batch script: how to check for admin rights

I think the simplest way is trying to change the system date (that requires admin rights):

date %date%
if errorlevel 1 (
   echo You have NOT admin rights
) else (
   echo You have admin rights
)

If %date% variable may include the day of week, just get the date from last part of DATE command:

for /F "delims=" %%a in ('date ^<NUL') do set "today=%%a" & goto break
:break
for %%a in (%today%) do set "today=%%a"
date %today%
if errorlevel 1 ...

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).

Anyway, Safari keeps the dimensions of the previous image so the dimensions are always one image behind. I assume that this has something to do with cache. So the simplest solution is to just clone the image and add it to the DOM (it is important that it be added to the DOM the get the with and height). Give the image a visibility value of hidden (do not use display none because it will not work). After you get the dimensions remove the clone.

Here is my code using jQuery:

// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image

var cloned, 
    o_width, 
    o_height, 
    src = 'my_image.jpg', 
    img = [some existing image object];

$(img)
.load(function()
{
    $(this).removeAttr('height').removeAttr('width');
    cloned = $(this).clone().css({visibility:'hidden'});
    $('body').append(cloned);
    o_width = cloned.get(0).width; // I prefer to use native javascript for this
    o_height = cloned.get(0).height; // I prefer to use native javascript for this
    cloned.remove();
    $(this).attr({width:o_width, height:o_height});
})
.attr(src:src);

This solution works in any case.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

How do I find the data directory for a SQL Server instance?

It depends on whether default path is set for data and log files or not.

If the path is set explicitly at Properties => Database Settings => Database default locations then SQL server stores it at Software\Microsoft\MSSQLServer\MSSQLServer in DefaultData and DefaultLog values.

However, if these parameters aren't set explicitly, SQL server uses Data and Log paths of master database.

Bellow is the script that covers both cases. This is simplified version of the query that SQL Management Studio runs.

Also, note that I use xp_instance_regread instead of xp_regread, so this script will work for any instance, default or named.

declare @DefaultData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @DefaultData output

declare @DefaultLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @DefaultLog output

declare @DefaultBackup nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultBackup output

declare @MasterData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg0', @MasterData output
select @MasterData=substring(@MasterData, 3, 255)
select @MasterData=substring(@MasterData, 1, len(@MasterData) - charindex('\', reverse(@MasterData)))

declare @MasterLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg2', @MasterLog output
select @MasterLog=substring(@MasterLog, 3, 255)
select @MasterLog=substring(@MasterLog, 1, len(@MasterLog) - charindex('\', reverse(@MasterLog)))

select 
    isnull(@DefaultData, @MasterData) DefaultData, 
    isnull(@DefaultLog, @MasterLog) DefaultLog,
    isnull(@DefaultBackup, @MasterLog) DefaultBackup

You can achieve the same result by using SMO. Bellow is C# sample, but you can use any other .NET language or PowerShell.

using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
{
    var serverConnection = new ServerConnection(connection);
    var server = new Server(serverConnection);
    var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
    var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
}

It is so much simpler in SQL Server 2012 and above, assuming you have default paths set (which is probably always a right thing to do):

select 
    InstanceDefaultDataPath = serverproperty('InstanceDefaultDataPath'),
    InstanceDefaultLogPath = serverproperty('InstanceDefaultLogPath')

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Performance of Arrays vs. Lists

if you are just getting a single value out of either (not in a loop) then both do bounds checking (you're in managed code remember) it's just the list does it twice. See the notes later for why this is likely not a big deal.

If you are using your own for(int int i = 0; i < x.[Length/Count];i++) then the key difference is as follows:

  • Array:
    • bounds checking is removed
  • Lists
    • bounds checking is performed

If you are using foreach then the key difference is as follows:

  • Array:
    • no object is allocated to manage the iteration
    • bounds checking is removed
  • List via a variable known to be List.
    • the iteration management variable is stack allocated
    • bounds checking is performed
  • List via a variable known to be IList.
    • the iteration management variable is heap allocated
    • bounds checking is performed also Lists values may not be altered during the foreach whereas the array's can be.

The bounds checking is often no big deal (especially if you are on a cpu with a deep pipeline and branch prediction - the norm for most these days) but only your own profiling can tell you if that is an issue. If you are in parts of your code where you are avoiding heap allocations (good examples are libraries or in hashcode implementations) then ensuring the variable is typed as List not IList will avoid that pitfall. As always profile if it matters.

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

What is Vim recording and how can it be disabled?

It means you're in "record macro" mode. This mode is entered by typing q followed by a register name, and can be exited by typing q again.

How to change the URI (URL) for a remote Git repository?

  1. remove origin using command on gitbash git remote rm origin
  2. And now add new Origin using gitbash git remote add origin (Copy HTTP URL from your project repository in bit bucket) done

How to find the 'sizeof' (a pointer pointing to an array)?

In strings there is a '\0' character at the end so the length of the string can be gotten using functions like strlen. The problem with an integer array, for example, is that you can't use any value as an end value so one possible solution is to address the array and use as an end value the NULL pointer.

#include <stdio.h>
/* the following function will produce the warning:
 * ‘sizeof’ on array function parameter ‘a’ will
 * return size of ‘int *’ [-Wsizeof-array-argument]
 */
void foo( int a[] )
{
    printf( "%lu\n", sizeof a );
}
/* so we have to implement something else one possible
 * idea is to use the NULL pointer as a control value
 * the same way '\0' is used in strings but this way
 * the pointer passed to a function should address pointers
 * so the actual implementation of an array type will
 * be a pointer to pointer
 */
typedef char * type_t; /* line 18 */
typedef type_t ** array_t;
int main( void )
{
    array_t initialize( int, ... );
    /* initialize an array with four values "foo", "bar", "baz", "foobar"
     * if one wants to use integers rather than strings than in the typedef
     * declaration at line 18 the char * type should be changed with int
     * and in the format used for printing the array values 
     * at line 45 and 51 "%s" should be changed with "%i"
     */
    array_t array = initialize( 4, "foo", "bar", "baz", "foobar" );

    int size( array_t );
    /* print array size */
    printf( "size %i:\n", size( array ));

    void aprint( char *, array_t );
    /* print array values */
    aprint( "%s\n", array ); /* line 45 */

    type_t getval( array_t, int );
    /* print an indexed value */
    int i = 2;
    type_t val = getval( array, i );
    printf( "%i: %s\n", i, val ); /* line 51 */

    void delete( array_t );
    /* free some space */
    delete( array );

    return 0;
}
/* the output of the program should be:
 * size 4:
 * foo
 * bar
 * baz
 * foobar
 * 2: baz
 */
#include <stdarg.h>
#include <stdlib.h>
array_t initialize( int n, ... )
{
    /* here we store the array values */
    type_t *v = (type_t *) malloc( sizeof( type_t ) * n );
    va_list ap;
    va_start( ap, n );
    int j;
    for ( j = 0; j < n; j++ )
        v[j] = va_arg( ap, type_t );
    va_end( ap );
    /* the actual array will hold the addresses of those
     * values plus a NULL pointer
     */
    array_t a = (array_t) malloc( sizeof( type_t *) * ( n + 1 ));
    a[n] = NULL;
    for ( j = 0; j < n; j++ )
        a[j] = v + j;
    return a;
}
int size( array_t a )
{
    int n = 0;
    while ( *a++ != NULL )
        n++;
    return n;
}
void aprint( char *fmt, array_t a )
{
    while ( *a != NULL )
        printf( fmt, **a++ );   
}
type_t getval( array_t a, int i )
{
    return *a[i];
}
void delete( array_t a )
{
    free( *a );
    free( a );
}

jQuery textbox change event doesn't fire until textbox loses focus?

On modern browsers, you can use the input event:

DEMO

$("#textbox").on('input',function() {alert("Change detected!");});

How to convert a double to long without casting?

... And here is the rounding way which doesn't truncate. Hurried to look it up in the Java API Manual:

double d = 1234.56;
long x = Math.round(d); //1235

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

How can I reference a dll in the GAC from Visual Studio?

The relevant files and references can be found here:

http://msdn.microsoft.com/en-us/library/cc283981.aspx

Note the links off it about implementation/etc.

How to submit a form using Enter key in react.js?

I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!

const { useEffect } = require("react");

const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
    useEffect(() => {
        //https://stackoverflow.com/a/59147255/828184
        const listener = (event) => {
            if (event.code === "Enter" || event.code === "NumpadEnter") {
                handlePressEnter();
            }
        };

        document.addEventListener("keydown", listener);

        return () => {
            document.removeEventListener("keydown", listener);
        };
    }, []);

    const handlePressEnter = () => {
        //https://stackoverflow.com/a/54316368/828184
        const mouseClickEvents = ["mousedown", "click", "mouseup"];
        function simulateMouseClick(element) {
            mouseClickEvents.forEach((mouseEventType) =>
                element.dispatchEvent(
                    new MouseEvent(mouseEventType, {
                        view: window,
                        bubbles: true,
                        cancelable: true,
                        buttons: 1,
                    })
                )
            );
        }

        var element = document.querySelector(querySelectorToExecuteClick);
        simulateMouseClick(element);
    };
};

export default useEnterKeyListener;

This is how you use it:

useEnterKeyListener({
    querySelectorToExecuteClick: "#submitButton",
});

https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407

Saving to CSV in Excel loses regional date format

Place an apostrophe in front of the date and it should export in the correct format. Just found it out for myself, I found this thread searching for an answer.

Solutions for INSERT OR UPDATE on SQL Server

Does the race conditions really matter if you first try an update followed by an insert? Lets say you have two threads that want to set a value for key key:

Thread 1: value = 1
Thread 2: value = 2

Example race condition scenario

  1. key is not defined
  2. Thread 1 fails with update
  3. Thread 2 fails with update
  4. Exactly one of thread 1 or thread 2 succeeds with insert. E.g. thread 1
  5. The other thread fails with insert (with error duplicate key) - thread 2.

    • Result: The "first" of the two treads to insert, decides value.
    • Wanted result: The last of the 2 threads to write data (update or insert) should decide value

But; in a multithreaded environment, the OS scheduler decides on the order of the thread execution - in the above scenario, where we have this race condition, it was the OS that decided on the sequence of execution. Ie: It is wrong to say that "thread 1" or "thread 2" was "first" from a system viewpoint.

When the time of execution is so close for thread 1 and thread 2, the outcome of the race condition doesn't matter. The only requirement should be that one of the threads should define the resulting value.

For the implementation: If update followed by insert results in error "duplicate key", this should be treated as success.

Also, one should of course never assume that value in the database is the same as the value you wrote last.

Output to the same line overwriting previous output?

I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - https://github.com/spyder-ide/spyder/issues/3437

   #works in spyder ipython console - \r at start of string , end=""
import time
import sys
    for i in range(20):
        time.sleep(0.5)
        print(f"\rnumber{i}",end="")
        sys.stdout.flush()

Opening Android Settings programmatically

You can make another class for doing this kind of activities.

public class Go {

   public void Setting(Context context)
    {
        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

Trigger change event <select> using jquery

Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How to change the color of a CheckBox?

If textColorSecondary does not work for you, you might have defined colorControlNormal in your theme to be a different color. If so, just use

<style name="yourStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">your_color</item> <!-- for checked state -->
    <item name="colorControlNormal">your color</item> <!-- for unchecked state -->
</style>

Calling a rest api with username and password - how to

You can also use the RestSharp library for example

var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");            
client.Authenticator = new HttpBasicAuthenticator(userName, password);            
var request = new RestRequest(Method.POST); 
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");            
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Round double value to 2 decimal places

 value = (round(value*100)) / 100.0;

One line if statement not working

From what I know

3 one-liners

  1. a = 10 if <condition>

example:

a = 10 if true # a = 10
b = 10 if false # b = nil
  1. a = 10 unless <condition>

example:

a = 10 unless false # a = 10
b = 10 unless true # b = nil
  1. a = <condition> ? <a> : <b>

example:

a = true ? 10 : 100 # a = 10
a = false ? 10 : 100 # a = 100

I hope it helps.

jQuery: How to get to a particular child of a parent?

Calling .parents(".box .something1") will return all parent elements that match the selector .box .something. In other words, it will return parent elements that are .something1 and are inside of .box.

You need to get the children of the closest parent, like this:

$(this).closest('.box').children('.something1')

This code calls .closest to get the innermost parent matching a selector, then calls .children on that parent element to find the uncle you're looking for.

Open URL in same window and in same tab

Exactly like this window.open("www.youraddress.com","_self")

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

Timing Delays in VBA

The Timer function also applies to Access 2007, Access 2010, Access 2013, Access 2016, Access 2007 Developer, Access 2010 Developer, Access 2013 Developer. Insert this code to to pause time for certain amount of seconds

T0 = Timer
Do
    Delay = Timer - T0
Loop Until Delay = 1 'Change this value to pause time in second

Logical Operators, || or OR?

They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.

For example, the following is a Boolean condition:

if ($foo == $bar && $baz != $quxx) {

This differs from control flow:

doSomething() or die();

Undo scaffolding in Rails

You can undo whatever you did with

rails generate xxx

By

rails destroy xxx

For example this applies generators to migration, scaffold, model...etc

Count number of matches of a regex in Javascript

('my string'.match(/\s/g) || []).length;

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

How to determine whether a substring is in a different string

You can also try find() method. It determines if string str occurs in string, or in a substring of string.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Reading Data From Database and storing in Array List object

You are reusing the customer reference. Java works by reference for Obejcts. Not for primitives.

What you are doing is adding to the list the same customer and then modifying it. Thus setting the same values for all of objects. That's why you see the last. Because all are the same.

 while (rs.next()) {
        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));

        ...

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

jQuery $.cookie is not a function

add this cookie plugin for jquery.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

Remove all whitespace from C# string with regex

Regex.Replace does not modify its first argument (recall that strings are immutable in .NET) so the call

Regex.Replace(LastName, @"\s+", "");

leaves the LastName string unchanged. You need to call it like this:

LastName = Regex.Replace(LastName, @"\s+", "");

All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.

Cannot simply use PostgreSQL table name ("relation does not exist")

If a table name contains underscores or upper case, you need to surround it in double-quotes.

SELECT * from "Table_Name";

Javascript for "Add to Home Screen" on iPhone?

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

How to debug (only) JavaScript in Visual Studio?

First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.

enter image description here Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer). and then click Apply and OK and you are done ..

Now you can set breakpoints in your JS file and then hit the debug button in VS..

enter image description here

EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)

How to serialize an object to XML without getting xmlns="..."?

        XmlWriterSettings settings = new XmlWriterSettings
        {
            OmitXmlDeclaration = true
        };

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        StringBuilder sb = new StringBuilder();

        XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));

        using (XmlWriter xw = XmlWriter.Create(sb, settings))
        {
            xs.Serialize(xw, model, ns);
            xw.Flush();
            return sb.ToString();
        }

Bootstrap: add margin/padding space between columns

For those looking to control the space between a dynamic number of columns, try:

<div class="row no-gutters">
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <!-- etc. -->
</div>

CSS:

.col:not(:last-child) .inner {
  margin: 2px; // Or whatever you want your spacing to be
}

I have Python on my Ubuntu system, but gcc can't find Python.h

You need the python-dev package which contains Python.h

How to send an email using PHP?

Also look into the PEAR mail package Pear Mail Page

It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).

Here is an excerpt from this page showing how it is used. PEAR Mail send() usage

<?php
    include('Mail.php');

    $recipients = '[email protected]';

    $headers['From']    = '[email protected]';
    $headers['To']      = '[email protected]';
    $headers['Subject'] = 'Test message';

    $body = 'Test message';

    $smtpinfo["host"] = "smtp.server.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "smtp_user";
    $smtpinfo["password"] = "smtp_password";


    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory("smtp", $smtpinfo); 

    $mail_object->send($recipients, $headers, $body);
?> 

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

CakePHP 3.0 installation: intl extension missing from system

I had the same problem in windows The error was that I had installed several versions of PHP and the Environment Variables were routing to wrong Path of php see image example

How to extract duration time from ffmpeg output?

From my experience many tools offer the desired data in some kind of a table/ordered structure and also offer parameters to gather specific parts of that data. This applies to e.g. smartctl, nvidia-smi and ffmpeg/ffprobe, too. Simply speaking - often there's no need to pipe data around or to open subshells for such a task.

As a consequence I'd use the right tool for the job - in that case ffprobe would return the raw duration value in seconds, afterwards one could create the desired time format on his own:

$ ffmpeg --version
ffmpeg version 2.2.3 ...

The command may vary dependent on the version you are using.

#!/usr/bin/env bash
input_file="/path/to/media/file"

# Get raw duration value
ffprobe -v quiet -print_format compact=print_section=0:nokey=1:escape=csv -show_entries format=duration "$input_file"

An explanation:

"-v quiet": Don't output anything else but the desired raw data value

"-print_format": Use a certain format to print out the data

"compact=": Use a compact output format

"print_section=0": Do not print the section name

":nokey=1": do not print the key of the key:value pair

":escape=csv": escape the value

"-show_entries format=duration": Get entries of a field named duration inside a section named format

Reference: ffprobe man pages

How to get ip address of a server on Centos 7 in bash

SERVER_IP="$(ip addr show ens160 | grep 'inet ' | cut -f2 | awk '{ print $2}')"

replace ens160 with your interface name

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

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

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the background color code of an element in hex?

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405

Execution failed for task :':app:mergeDebugResources'. Android Studio

By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size for Android Studio processes, such as the core IDE, Gradle daemon, and Kotlin daemon.

If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust the heap sizes for your project manually. To do so, follow these steps:

Click File > Settings from the menu bar (or Android Studio > Preferences on macOS). Click Appearance & Behavior > System Settings > Memory Settings.

For more Info click

https://developer.android.com/studio/intro/studio-config

enter image description here

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

What's the difference between Git Revert, Checkout and Reset?

  • git checkout modifies your working tree,
  • git reset modifies which reference the branch you're on points to,
  • git revert adds a commit undoing changes.

RestTemplate: How to send URL and query parameters together

One-liner using TestRestTemplate.exchange function with parameters map.

restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])

The params map initialized like this is a groovy initializer*

Loading local JSON file

_x000D_
_x000D_
json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;_x000D_
obj = JSON.parse(json_str);_x000D_
_x000D_
console.log(obj[0]["name"]);
_x000D_
_x000D_
_x000D_

I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse

How to check if a network port is open on linux?

Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:

from contextlib import closing
import socket
class example:
    def __init__():

       self.machine_ip = socket.gethostbyname(socket.gethostname())
       self.ready:bool = self.check_socket()

    def check_socket(self)->bool:
        result:bool = True
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        modbus_tcp_port:int = 502
        if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
            result = False
        return result

Test process.env with Jest

You can use the setupFiles feature of the Jest configuration. As the documentation said that,

A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

  1. npm install dotenv dotenv that uses to access environment variable.

  2. Create your .env file to the root directory of your application and add this line into it:

    #.env
    APP_PORT=8080
    
  3. Create your custom module file as its name being someModuleForTest.js and add this line into it:

    // someModuleForTest.js
    require("dotenv").config()
    
  4. Update your jest.config.js file like this:

    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
  5. You can access an environment variable within all test blocks.

    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    

Change language for bootstrap DateTimePicker

Try this:

$( ".form_datetime" ).datepicker( $.datepicker.regional[ "zh-CN" ], { dateFormat: 'dd.mm.yyyy hh:ii' });

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

NSDate get year/month/day

Swift 2.x

extension NSDate {
    func currentDateInDayMonthYear() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "d LLLL yyyy"
        return dateFormatter.stringFromDate(self)
    }
}

You can use it as

NSDate().currentDateInDayMonthYear()

Output

6 March 2016

Automatically start a Windows Service on install

Use ServiceController to start your service from code.

Update: And more correct way to start service from the command line is to use "sc" (Service Controller) command instead of "net".

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

Pass parameters in setInterval function

I know this topic is so old but here is my solution about passing parameters in setInterval function.

Html:

var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);

JavaScript:

function startTimer(duration, display) {
    var timer = duration,
        minutes, seconds;

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

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

        display.textContent = minutes + ":" + seconds;
        --timer; // put boolean value for minus values.

    }, 1000);
}

Does an HTTP Status code of 0 have any meaning?

Know it's an old post. But these issues still exist.

Here are some of my findings on the subject, grossly explained.

"Status" 0 means one of 3 things, as per the XMLHttpRequest spec:

  • dns name resolution failed (that's for instance when network plug is pulled out)

  • server did not answer (a.k.a. unreachable or unresponding)

  • request was aborted because of a CORS issue (abortion is performed by the user-agent and follows a failing OPTIONS pre-flight).

If you want to go further, dive deep into the inners of XMLHttpRequest. I suggest reading the ready-state update sequence ([0,1,2,3,4] is the normal sequence, [0,1,4] corresponds to status 0, [0,1,2,4] means no content sent which may be an error or not). You may also want to attach listeners to the xhr (onreadystatechange, onabort, onerror, ontimeout) to figure out details.

From the spec (XHR Living spec):

const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

Initializing select with AngularJS and ng-repeat

As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

http://jsfiddle.net/FxM3B/3/

The JavaScript:

function AppCtrl($scope) {


    $scope.operators = [
        {value: 'eq', displayName: 'equals'},
        {value: 'neq', displayName: 'not equal'}
     ]

    $scope.filterCondition={
        operator: $scope.operators[0]
    }
}

The HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>

JSON datetime between Python and JavaScript

I've worked it out.

Let's say you have a Python datetime object, d, created with datetime.now(). Its value is:

datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)

You can serialize it to JSON as an ISO 8601 datetime string:

import json    
json.dumps(d.isoformat())

The example datetime object would be serialized as:

'"2011-05-25T13:34:05.787000"'

This value, once received in the Javascript layer, can construct a Date object:

var d = new Date("2011-05-25T13:34:05.787000");

As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:

d.toJSON()

Which would give you:

'2011-05-25T20:34:05.787Z'

This string, once received in Python, could be deserialized back to a datetime object:

datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')

This results in the following datetime object, which is the same one you started with and therefore correct:

datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

When trying to translate Excel file with .xlsx suffix, you need to add additional jar, xmlbeansxxx.jar. xxxx is version, such as xmlbeans-2.3.0.jar

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Find (and kill) process locking port 3000 on Mac

These two commands will help you find and kill server process

  1. lsof -wni tcp:3000
  2. kill -9 pid

How to block calls in android

In android-N, this feature is included in it. check Number-blocking update for android N

Android N now supports number-blocking in the platform and provides a framework API to let service providers maintain a blocked-number list. The default SMS app, the default phone app, and provider apps can read from and write to the blocked-number list. The list is not accessible to other app.

advantage of are:

  1. Numbers blocked on calls are also blocked on texts
  2. Blocked numbers can persist across resets and devices through the Backup & Restore feature
  3. Multiple apps can use the same blocked numbers list

For more information, see android.provider.BlockedNumberContract

Update an existing project.

To compile your app against the Android N platform, you need to use the Java 8 Developer Kit (JDK 8), and in order to use some tools with Android Studio 2.1, you need to install the Java 8 Runtime Environment (JRE 8).

Open the build.gradle file for your module and update the values as follows:

android {
  compileSdkVersion 'android-N'
  buildToolsVersion 24.0.0 rc1
  ...

  defaultConfig {
     minSdkVersion 'N'
     targetSdkVersion 'N'
     ...
  }
  ...
}

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

How do I get the max and min values from a set of numbers entered?

You just need to keep track of a max value like this:

int maxValue = 0;

Then as you iterate through the numbers, keep setting the maxValue to the next value if it is greater than the maxValue:

if (value > maxValue) {
    maxValue = value;
}

Repeat in the opposite direction for minValue.

ISO C90 forbids mixed declarations and code in C

Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:

function() {
    int i;
    i = 0;

    someCode();
}

How to change the floating label color of TextInputLayout

In my case I added this "app:hintTextAppearance="@color/colorPrimaryDark"in my TextInputLayout widget.

Maven dependency for Servlet 3.0 API?

Here is what I use. All of these are in the Central and have sources.

For Tomcat 7 (Java 7, Servlet 3.0)

Note - Servlet, JSP and EL APIs are provided in Tomcat. Only JSTL (if used) needs to be bundled with the web app.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

For Tomcat 8 (Java 8, Servlet 3.1)

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

How to remove empty lines with or without whitespace in Python

Using regex:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

Using regex + filter():

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

As seen on codepad.

How to convert QString to std::string?

You can use:

QString qs;
// do things
std::cout << qs.toStdString() << std::endl;

It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString.

How do I display a MySQL error in PHP for a long query that depends on the user input?

Use below code to print the error code :

echo mysqli_errno($this->db_link);

Error code will give you better idea about the error.

More info can be found at https://www.techqura.com/techqura.php?post=How-to-display-MySQL-error-in-PHP&pid=8&website=techqura.com

How to generate a unique hash code for string input in android...?

This is a class I use to create Message Digest hashes

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha1Hex {

    public String makeSHA1Hash(String input)
            throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
        }
}

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

Detecting endianness programmatically in a C++ program

This is normally done at compile time (specially for performance reason) by using the header files available from the compiler or create your own. On linux you have the header file "/usr/include/endian.h"

Redirecting to previous page after login? PHP

You can save a page using php, like this:

$_SESSION['current_page'] = $_SERVER['REQUEST_URI']

And return to the page with:

header("Location: ". $_SESSION['current_page'])

Remove numbers from string sql server

One more approach using Recursive CTE..

declare @string varchar(100)
set @string ='te165st1230004616161616'

;With cte
as
(
select @string as string,0  as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc


**Output:**   
  test

Android "hello world" pushnotification example

you can follow this tutorial

http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/

it helped me to do a push notification; or you can follow this other tutorial

http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html

but it's in spanish but you can download the code.

How can I make a div not larger than its contents?

You can do it simply by using display: inline; (or white-space: nowrap;).

I hope you find this useful.

How to print jquery object/array

What you have from the server is a string like below:

var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';

Then you can use JSON.parse function to change it to an object. Then you access the category like below:

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

Create a file if it doesn't exist

First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.

That said, you can do it as That One Random Scrub proposed, using try: ... except:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".

But you can also easily test for existence:

import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
    fh = open(fn, "r")
else:
    fh = open(fn, "w")

Note: use raw_input() instead of input(), because input() will try to execute the entered text. If you accidently want to test for file "import", you'd get a SyntaxError.

How to parse data in JSON format?

For URL or file, use json.load(). For string with .json content, use json.loads().

#! /usr/bin/python

import json
# from pprint import pprint

json_file = 'my_cube.json'
cube = '1'

with open(json_file) as json_data:
    data = json.load(json_data)

# pprint(data)

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']

How do I redirect a user when a button is clicked?

$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})

Fluid width with equally spaced DIVs

See: http://jsfiddle.net/thirtydot/EDp8R/

  • This works in IE6+ and all modern browsers!
  • I've halved your requested dimensions just to make it easier to work with.
  • text-align: justify combined with .stretch is what's handling the positioning.
  • display:inline-block; *display:inline; zoom:1 fixes inline-block for IE6/7, see here.
  • font-size: 0; line-height: 0 fixes a minor issue in IE6.

_x000D_
_x000D_
#container {_x000D_
  border: 2px dashed #444;_x000D_
  height: 125px;_x000D_
  text-align: justify;_x000D_
  -ms-text-justify: distribute-all-lines;_x000D_
  text-justify: distribute-all-lines;_x000D_
  /* just for demo */_x000D_
  min-width: 612px;_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box2,_x000D_
.box3,_x000D_
.box4 {_x000D_
  width: 150px;_x000D_
  height: 125px;_x000D_
  vertical-align: top;_x000D_
  display: inline-block;_x000D_
  *display: inline;_x000D_
  zoom: 1_x000D_
}_x000D_
_x000D_
.stretch {_x000D_
  width: 100%;_x000D_
  display: inline-block;_x000D_
  font-size: 0;_x000D_
  line-height: 0_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box3 {_x000D_
  background: #ccc_x000D_
}_x000D_
_x000D_
.box2,_x000D_
.box4 {_x000D_
  background: #0ff_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="box1"></div>_x000D_
  <div class="box2"></div>_x000D_
  <div class="box3"></div>_x000D_
  <div class="box4"></div>_x000D_
  <span class="stretch"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The extra span (.stretch) can be replaced with :after.

This still works in all the same browsers as the above solution. :after doesn't work in IE6/7, but they're using distribute-all-lines anyway, so it doesn't matter.

See: http://jsfiddle.net/thirtydot/EDp8R/3/

There's a minor downside to :after: to make the last row work perfectly in Safari, you have to be careful with the whitespace in the HTML.

Specifically, this doesn't work:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div>
</div>

And this does:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div></div>

You can use this for any arbitrary number of child divs without adding a boxN class to each one by changing

.box1, .box2, .box3, .box4 { ...

to

#container > div { ...

This selects any div that is the first child of the #container div, and no others below it. To generalize the background colors, you can use the CSS3 nth-order selector, although it's only supported in IE9+ and other modern browsers:

.box1, .box3 { ...

becomes:

#container > div:nth-child(odd) { ...

See here for a jsfiddle example.

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

The only thing that worked for me is:

sudo install_name_tool -change libmysqlclient.18.dylib \
/usr/local/mysql-5.6.23-osx10.8-x86_64/lib/libmysqlclient.18.dylib \
/Library/Ruby/Gems/2.0.0/gems/mysql2-0.4.3/lib/mysql2/mysql2.bundle

Replace the paths of mysql and gems to fit your system.

Recommended method for escaping HTML in Java

org.apache.commons.lang3.StringEscapeUtils is now deprecated. You must now use org.apache.commons.text.StringEscapeUtils by

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>${commons.text.version}</version>
    </dependency>

How to include duplicate keys in HashMap?

hashMaps can't have duplicate keys. That said, you can create a map with list values:

Map<Integer, List<String>>

However, using this approach will have performance implications.

Google Chrome forcing download of "f.txt" file

This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.

  • Some time around the summer of 2014, IT Security Engineer Michele Spagnuolo (apparently employed at Google Zurich) developed a proof-of-concept exploit and supporting tool called Rosetta Flash that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
    • Known affected browsers: Chrome, IE
    • Possibly unaffected browsers: Firefox
  • Adobe has released at least 5 different fixes over the past year while trying to comprehensively fix this vulnerability, but various major websites also introduced their own fixes earlier on in order to prevent mass vulnerability to their userbases. Among the sites to do so: Google, Youtube, Facebook, Github, and others. One component of the ad-hoc mitigation implemented by these website owners was to force the HTTP Header Content-Disposition: attachment; filename=f.txt on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.
  • In conclusion, the websites you were visiting when this file spontaneously downloaded are not bad or malicious, but some domain serving content on their pages (usually ads) had content with this exploit inside it. Note that this issue will be random and intermittent in nature because even visiting the same pages consecutively will often produce different ad content. For example, the advertisement domain ad.doubleclick.net probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.
  • The only way I'm aware that you could stop this f.txt file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htm
  • Short list of domains you could block (by no means a comprehensive list). Most of these are highly associated with adware and malware:
    • ad.doubleclick.net
    • adclick.g.doubleclick.net
    • secure-us.imrworldwide.com
    • d.turn.com
    • ad.turn.com
    • secure.insightexpressai.com
    • core.insightexpressai.com

Why use 'git rm' to remove a file instead of 'rm'?

However, if you do end up using rm instead of git rm. You can skip the git add and directly commit the changes using:

git commit -a

"Parse Error : There is a problem parsing the package" while installing Android application

As a couple of the other answers have mentioned, there can be problems when installing from the SD card. In my case I was distributing my app via email attachment, and it usually worked fine. Just open the email and download the attachment (it apparently goes to the SD card) and click on it again and it gets installed.

But then one day it didn't work, and it turned out it was because I had the phone connected to my development PC via USB, and that placed the SD card in a different mode or something. So the solution was simply to disconnect the phone from the PC and then send the e-mail again and download the attachment again. Or else place the USB connection in "charging only" mode so the SD card is not "connected" to the PC.

std::enable_if to conditionally compile a member function

One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.

template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};

template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};

template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
    typedef FooImpl<T, boost::is_integer<T> > inherited;

    // you will need to use "inherited::" if you want to name any of the 
    // members of those inherited classes.
};

The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.

Ex:

template<class T, bool condition> class Goo;
// repeat pattern above.

template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
    typedef Goo<T, boost::test<T> > inherited:
    // etc. etc.
};

How do I trim whitespace?

#how to trim a multi line string or a file

s=""" line one
\tline two\t
line three """

#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.

s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']

print [i.strip() for i in s1]
['line one', 'line two', 'line three']




#more details:

#we could also have used a forloop from the begining:
for line in s.splitlines():
    line=line.strip()
    process(line)

#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
    line=line.strip()
    process(line)

#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']

Calculating distance between two geographic locations

There is only one user Location, so you can iterate List of nearby places can call the distanceTo() function to get the distance, you can store in an array if you like.

From what I understand, distanceBetween() is for far away places, it's output is a WGS84 ellipsoid.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

C compile error: Id returned 1 exit status

1d returned 1 exit status error

First of all you have to create a project by clicking file new and then project and give project name select the language c or c++ and select empty also. Then your program is under that project... And then give a program name save it.... Ensure that your under some project to compile and run a program...

Getting ssh to execute a command in the background on target machine

If you don't/can't keep the connection open you could use screen, if you have the rights to install it.

user@localhost $ screen -t remote-command
user@localhost $ ssh user@target # now inside of a screen session
user@remotehost $ cd /some/directory; program-to-execute &

To detach the screen session: ctrl-a d

To list screen sessions:

screen -ls

To reattach a session:

screen -d -r remote-command

Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.

user@localhost $ tmux
user@localhost $ ssh user@target # now inside of a tmux session
user@remotehost $ cd /some/directory; program-to-execute &

To detach the tmux session: ctrl-b d

To list screen sessions:

tmux list-sessions

To reattach a session:

tmux attach <session number>

The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.

Change color of Back button in navigation bar

You can change the global tint color in your storyboard by clicking on an empty space on the board and select in the right toolbar "Show the file inspector", and you will see in the bottom of the toolbar the "Global Tint" option.

Global Tint option in storyboard

Error after upgrading pip: cannot import name 'main'

This error may be a permission one. So, test executing the command with -H flag:

sudo -H pip3 install numpy

Test if object implements interface

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How to completely remove borders from HTML table

Using TinyMCE editor, the only way I was able to remove all borders was to use border:hidden in the style like this:

<style>
table, tr {border:hidden;}
td, th {border:hidden;}
</style>

And in the HTML like this:

<table style="border:hidden;"</table>

Cheers

Delete column from pandas DataFrame

Use:

columns = ['Col1', 'Col2', ...]
df.drop(columns, inplace=True, axis=1)

This will delete one or more columns in-place. Note that inplace=True was added in pandas v0.13 and won't work on older versions. You'd have to assign the result back in that case:

df = df.drop(columns, axis=1)

Standard Android Button with a different color

The way I do a different styled button that works quite well is to subclass the Button object and apply a colour filter. This also handles enabled and disabled states by applying an alpha to the button.

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.Button;

public class DimmableButton extends Button {

    public DimmableButton(Context context) {
        super(context);
    }

    public DimmableButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DimmableButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setBackgroundDrawable(Drawable d) {
        // Replace the original background drawable (e.g. image) with a LayerDrawable that
        // contains the original drawable.
        DimmableButtonBackgroundDrawable layer = new DimmableButtonBackgroundDrawable(d);
        super.setBackgroundDrawable(layer);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void setBackground(Drawable d) {
        // Replace the original background drawable (e.g. image) with a LayerDrawable that
        // contains the original drawable.
        DimmableButtonBackgroundDrawable layer = new DimmableButtonBackgroundDrawable(d);
        super.setBackground(layer);
    }

    /**
     * The stateful LayerDrawable used by this button.
     */
    protected class DimmableButtonBackgroundDrawable extends LayerDrawable {

        // The color filter to apply when the button is pressed
        protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
        // Alpha value when the button is disabled
        protected int _disabledAlpha = 100;
        // Alpha value when the button is enabled
        protected int _fullAlpha = 255;

        public DimmableButtonBackgroundDrawable(Drawable d) {
            super(new Drawable[] { d });
        }

        @Override
        protected boolean onStateChange(int[] states) {
            boolean enabled = false;
            boolean pressed = false;

            for (int state : states) {
                if (state == android.R.attr.state_enabled)
                    enabled = true;
                else if (state == android.R.attr.state_pressed)
                    pressed = true;
            }

            mutate();
            if (enabled && pressed) {
                setColorFilter(_pressedFilter);
            } else if (!enabled) {
                setColorFilter(null);
                setAlpha(_disabledAlpha);
            } else {
                setColorFilter(null);
                setAlpha(_fullAlpha);
            }

            invalidateSelf();

            return super.onStateChange(states);
        }

        @Override
        public boolean isStateful() {
            return true;
        }
    }

}

How to extract Month from date in R

Her is another R base approach:

From your example: Some date:

Some_date<-"01/01/1979"

We tell R, "That is a Date"

Some_date<-as.Date(Some_date)

We extract the month:

months(Some_date)

output: [1] "January"

Finally, we can convert it to a numerical variable:

as.numeric(as.factor(months(Some_date)))

outpt: [1] 1

Check existence of directory and create if doesn't exist

Here's the simple check, and creates the dir if doesn't exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

Android getResources().getDrawable() deprecated API 22

You can use

ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);

that's work for me

Command CompileSwift failed with a nonzero exit code in Xcode 10

I also encountered the same issue and I did what @cdeerinck suggested and got to the following link which suggested adding a user-defined variable to the Build Settings to disable batch mode i.e. add a new user defined variable named SWIFT_ENABLE_BATCH_MODE and set it to NO, I was able to get more insights into the issue and I got to know that the error was in a framework using CommonCrypto which was added to it(by me) but since Xcode 10 it is exposed natively as part of Swift (for Apple platforms only), and adding it (or its existence from the previous version) was causing a name collision and hence it was throwing the error. To know more refer to the this link which explains the issue in more detail.

How to Animate Addition or Removal of Android ListView Rows

call listView.scheduleLayoutAnimation(); before changing the list

Run php function on button click

You can use isset().

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" />

</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(isset($_POST('submit')))
{
   testfun();
}

?>

Bulk Insert to Oracle using .NET

The solution of Rob Stevenson-Legget is slow because he doesn't bind his values but he uses string.Format( ).

When you ask Oracle to execute a sql statement it starts with calculating the has value of this statement. After that it looks in a hash table whether it already knows this statement. If it already knows it statement it can retrieve its execution path from this hash table and execute this statement really fast because Oracle has executed this statement before. This is called the library cache and it doesn't work properly if you don't bind your sql statements.

For example don't do:

int n;

    for (n = 0; n < 100000; n ++)
    {
      mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
      mycommand.ExecuteNonQuery();
    }

but do:

      OracleParameter myparam = new OracleParameter();
      int n;

      mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
      mycommand.Parameters.Add(myparam);

      for (n = 0; n < 100000; n ++)
      {
        myparam.Value = n + 1;
        mycommand.ExecuteNonQuery();
      }

Not using parameters can also cause sql injection.

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

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

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

How to write inside a DIV box with javascript

I would suggest Jquery:

$("#log").html("Type what you want to be shown to the user");   

Disable click outside of bootstrap modal area to close modal

You can also do this without using JQuery, like so:

<div id="myModal">

var modal = document.getElementById('myModal');
modal.backdrop = "static";
modal.keyboard = false;

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this using the DateFormat class:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.