Programs & Examples On #Oaw

OpenArchitectureWare is a framework of model-driven technologies, such as code generation (Xpand), language definition (Xtext) and model instance extension (Xtend).

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Format a datetime into a string with milliseconds

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

>>>> OUTPUT >>>>
2020-05-04 10:18:32.926

Note: For Python3, print requires parentheses:

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Convert string to int if string is a number

Here are a three functions that might be useful. First checks the string for a proper numeric format, second and third function converts a string to Long or Double.

Function IsValidNumericEntry(MyString As String) As Boolean
'********************************************************************************
'This function checks the string entry to make sure that valid digits are in the string.
'It checks to make sure the + and - are the first character if entered and no duplicates.
'Valid charcters are 0 - 9, + - and the .
'********************************************************************************
Dim ValidEntry As Boolean
Dim CharCode As Integer
Dim ValidDigit As Boolean
Dim ValidPlus As Boolean
Dim ValidMinus As Boolean
Dim ValidDecimal As Boolean
Dim ErrMsg As String

ValidDigit = False
ValidPlus = False
ValidMinus = False
ValidDecimal = False

ValidEntry = True
For x = 1 To Len(MyString)
    CharCode = Asc(Mid(MyString, x, 1))
    Select Case CharCode

    Case 48 To 57 ' Digits 0 - 9
        ValidDigit = True

    Case 43 ' Plus sign

    If ValidPlus Then 'One has already been detected and this is a duplicate
        ErrMsg = "Invalid entry....too many plus signs!"
        ValidEntry = False
        Exit For
    ElseIf x = 1 Then 'if in the first positon it is valide
        ValidPlus = True
    Else 'Not in first position and it is invalid
        ErrMsg = "Invalide entry....Plus sign not in the correct position! "
        ValidEntry = False
        Exit For
    End If

    Case 45 ' Minus sign

    If ValidMinus Then 'One has already been detected and this is a duplicate
        ErrMsg = "Invalide entry....too many minus signs! "
        ValidEntry = False
        Exit For
    ElseIf x = 1 Then 'if in the first position it is valid
        ValidMinus = True
    Else 'Not in first position and it is invalid
        ErrMsg = "Invalide entry....Minus sign not in the correct position! "
        ValidEntry = False
        Exit For
    End If

    Case 46 ' Period

    If ValidDecimal Then 'One has already been detected and this is a duplicate
        ErrMsg = "Invalide entry....too many decimals!"
        ValidEntry = False
        Exit For
    Else
        ValidDecimal = True
    End If

    Case Else
        ErrMsg = "Invalid numerical entry....Only digits 0-9 and the . + - characters are valid!"
        ValidEntry = False
        Exit For

    End Select

Next

    If ValidEntry And ValidDigit Then
        IsValidNumericEntry = True
    Else
        If ValidDigit = False Then
            ErrMsg = "Text string contains an invalid numeric format." & vbCrLf _
            & "Use only one of the following formats!" & vbCrLf _
            & "(+dd.dd  -dd.dd  +dd  -dd  dd.d or dd)! "
        End If
        MsgBox (ErrMsg & vbCrLf & vbCrLf & "You Entered:   " & MyString)
        IsValidNumericEntry = False
    End If

End Function

Function ConvertToLong(stringVal As String) As Long
'Assumes the user has verified the string contains a valide numeric entry.
'User should call the function IsValidNumericEntry first especially after any user input
'to verify that the user has entered a proper number.

 ConvertToLong = CLng(stringVal)


End Function
Function ConvertToDouble(stringVal As String) As Double
'Assumes the user has verified the string contains a valide numeric entry.
'User should call the function IsValidNumericEntry first especially after any user input
'to verify that the user has entered a proper number.

    ConvertToDouble = CDbl(stringVal)

End Function

What is an unhandled promise rejection?

This is when a Promise is completed with .reject() or an exception was thrown in an async executed code and no .catch() did handle the rejection.

A rejected promise is like an exception that bubbles up towards the application entry point and causes the root error handler to produce that output.

See also

Auto submit form on page load

Try this On window load submit your form.

window.onload = function(){
  document.forms['member_signup'].submit();
}

Django values_list vs values

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

jQuery AJAX form data serialize using PHP

try it , but first be sure what is you response console.log(response) on ajax success from server

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response === 1){
            //load chech.php file  
        }  else {
            //show error
        }
        }
    });
});
});

What is *.o file?

Ink-Jet is right. More specifically, an .o (.obj) -- or object file is a single source file compiled in to machine code (I'm not sure if the "machine code" is the same or similar to an executable machine code). Ultimately, it's an intermediate between an executable program and plain-text source file.

The linker uses the o files to assemble the file executable.

Wikipedia may have more detailed information. I'm not sure how much info you'd like or need.

Sleep/Wait command in Batch

timeout 5

to delay

timeout 5 >nul

to delay without asking you to press any key to cancel

Create XML file using java

Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.

dom4j - Quick start guide

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

Eclipse hangs on loading workbench

deleting workspace/.metadata/.lock and starting eclipse with -clean -refresh worked for me.

How do I check if a string contains another string in Swift?

In Swift 4.2

Use

func contains(_ str: String) -> Bool

Example

let string = "hello Swift"
let containsSwift = string.contains("Swift")
print(containsSwift) // prints true

How to exclude property from Json Serialization

Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.

If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json

//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
    private readonly HashSet<string> ignoreProps;
    public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
    {
        this.ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (this.ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

Usage

JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
        { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);

Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.

I've published the code here in case anyone wants to add anything

https://github.com/jitbit/JsonIgnoreProps

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.

$this->load->model('Order_Model','order_model');

You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well

$result = $this->order_model->get_order_details($orderID);

PHP cURL custom headers

$subscription_key  ='';
    $host = '';    
    $request_headers = array(
                    "X-Mashape-Key:" . $subscription_key,
                    "X-Mashape-Host:" . $host
                );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $season_data = curl_exec($ch);

    if (curl_errno($ch)) {
        print "Error: " . curl_error($ch);
        exit();
    }

    // Show me the result
    curl_close($ch);
    $json= json_decode($season_data, true);

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Calculate distance between two points in google maps V3

With google you can do it using the spherical api, google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);.

However, if the precision of a spherical projection or a haversine solution is not precise enough for you (e.g. if you're close to the pole or computing longer distances), you should use a different library.

Most information on the subject I found on Wikipedia here.

A trick to see if the precision of any given algorithm is adequate is to fill in the maximum and minimum radius of the earth and see if the difference might cause problems for your use case. Many more details can be found in this article

In the end the google api or haversine will serve most purposes without problems.

When should I use the Visitor Design Pattern?

The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).


1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

git fetch origin
git reset --hard origin/master
git pull

Explanation:

  • Fetch will download everything from another repository, in this case, the one marked as "origin".
  • Reset will discard changes and revert to the mentioned branch, "master" in repository "origin".
  • Pull will just get everything from a remote repository and integrate.

See documentation at http://git-scm.com/docs.

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

HashMaps and Null values?

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

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

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

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

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan

Shortcut to comment out a block of code with sublime text

With a non-US keyboard layout the default shortcut Ctrl+/ (Win/Linux) does not work.

I managed to change it into Ctrl+1 as per Robert's comment by writing

[
{
    "keys": ["ctrl+1"],
    "command": "toggle_comment",
    "args": { "block": false } 
}
,
{   "keys": ["ctrl+shift+1"],
    "command": "toggle_comment",
    "args": { "block": true }
}
]

to Preferences -> Key Bindings (on the right half, the user keymap).

Note that there should be only one set of brackets ('[]') at the right side; if you had there something already, copy paste this between the brackets and keep only the outermost brackets.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

How to add icons to React Native app

Coming in a bit late here but Android Studio has a very handy icon asset wizard. Its very self explanatory but has a few handy effects and its built right in:

enter image description here

Reading string by char till end of line C/C++

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

How to calculate a Mod b in Casio fx-991ES calculator

You can calculate A mod B (for positive numbers) using this:

Pol( -Rec( 1/r , 2πr × A/B ) , Y ) ( πr - Y ) B

Then press [CALC], and enter your values for A and B, and any value for Y.

/ indicates using the fraction key, and r means radians ( [SHIFT] [Ans] [2] )

How to overlay images

I just got done doing this exact thing in a project. The HTML side looked a bit like this:

<a href="[fullsize]" class="gallerypic" title="">
  <img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
  <span class="zoom-icon">
      <img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
  </span>
</a>

Then using CSS:

a.gallerypic{
  width:140px;
  text-decoration:none;
  position:relative;
  display:block;
  border:1px solid #666;
  padding:3px;
  margin-right:5px;
  float:left;
}

a.gallerypic span.zoom-icon{
  visibility:hidden;
  position:absolute;
  left:40%;
  top:35%;
  filter:alpha(opacity=50);
  -moz-opacity:0.5;
  -khtml-opacity: 0.5;
  opacity: 0.5;
}

a.gallerypic:hover span.zoom-icon{
  visibility:visible;
}

I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.

Hope this helps.

EDIT: To clarify for your example - you could ignore the visibility:hidden; and kill the :hover execution if you wanted, this was just the way I did it.

How can I set the PATH variable for javac so I can manually compile my .java works?

First thing I wann ans to this imp question: "Why we require PATH To be set?"

Answer : You need to set PATH to compile Java source code, create JAVA CLASS FILES and allow Operating System to load classes at runtime.

Now you will understand why after setting "javac" you can manually compile by just saying "Class_name.java"

Modify the PATH of Windows Environmental Variable by appending the location till bin directory where all exe file(for eg. java,javac) are present.

Example : ;C:\Program Files\Java\jre7\bin.

Mount current directory as a volume in Docker on Windows 10

This works for me in PowerShell:

docker run --rm -v ${PWD}:/data alpine ls /data

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

Provisioning Profiles menu item missing from Xcode 5

For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.

If anyone gets this far and is still struggling, here's what I did:

  1. Close xcode 5
  2. Open xcode 4.6.2
  3. Go to Window->Organizer->Provisioning Profiles
  4. Press Refresh arrow on bottom right

When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.

Unordered List (<ul>) default indent

Most html tags have some default properties. A css reset will help you change the default properties.

What I usually do is:

{ padding: 0; margin: 0; font-face:Arial; }

Although the font is up to you!

Placing a textview on top of imageview in android

you can try this too. I use just framelayout.

 <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/cover"
                android:gravity="bottom">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Hello !"
                    android:id="@+id/welcomeTV"
                    android:textColor="@color/textColor"
                    android:layout_gravity="left|bottom" />
            </FrameLayout>

PHP: HTTP or HTTPS?

You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).

See http://php.net/manual/en/reserved.variables.server.php.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Error inflating class android.support.design.widget.NavigationView

I had similar error. When i use

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>
    <item name="android:textColorPrimary">#212121</item>
    <item name="android:textColorSecondary">#727272</item>

</style>

works for me when i remove the android:textColorPrimary and android:textColorSecondary theme items.

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>

</style>

Try working with a very simple App theme to start off with.

EDIT:

This tutorial will help. My understanding is that using "android:textColorPrimary" requires minimum api level 21. Using the same tag without "android:" uses the design support library. Any support library widget will try to find the "textColorPrimary" item instead of "android:textColorPrimary" and if it fails to find the same it throws the above mentioned error.

Django auto_now and auto_now_add

class Feedback(models.Model):
   feedback = models.CharField(max_length=100)
   created = models.DateTimeField(auto_now_add=True)
   updated = models.DateTimeField(auto_now=True)

Here, we have created and updated columns that will have a timestamp when created, and when someone modified feedback.

auto_now_add will set time when an instance is created whereas auto_now will set time when someone modified his feedback.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The error also happens when trying to use the

with multiprocessing.Pool() as pool:
   # ...

with a Python version that is too old (like Python 2.X) and does not support using with together with multiprocessing pools.

(See this answer https://stackoverflow.com/a/25968716/1426569 to another question for more details)

Difference between TCP and UDP?

Simple Explanation by Analogy

TCP is like this.

Imagine you have a pen-pal on Mars (we communicated with written letters back in the good ol' days before the internet).

You need to send your pen pal the seven habits of highly effective people. So you decide to send it in seven separate letters:

  1. Letter 1 - Be proactive
  2. Letter 2 - Begin with the end in mind...

etc.

etc..Letter 7 - Sharpen the Saw

Requirements:

You want to make sure that your pen pal receives all your letters - in order and that they arrive perfectly. If your pen pay receives letter 7 before letter 1 - that's no good. if your pen pal receives all letters except letter 3 - that also is no good.

Here's how we ensure that our requirements are met:

  • Confirmation Letter: So your pen pal sends a confirmation letter to say "I have received letter 1". That way you know that your pen pal has received it. If a letter does not arrive, or arrives out of order, then you have to stop, and go back and re-send that letter, and all subsequent letters.
  • Flow Control: Around the time of Xmas you know that your pen pal will be receiving a lot of mail, so you slow down because you don't want to overwhelm your pen pal. (Your pen pal sends you constant updates about the number of unread messages there are in penpal's mailbox - if your pen pal says that the inbox is about to explode because it is so full, then you slow down sending your letters - because your pen pal won't be able to read them.
  • Perfect arrival. Sometimes while you send your letter in the mail, it can get torn, or a snail can eat half of it. How do you know that all your letter has arrived in perfect condition? Well your pen pal will give you a mechanism by which you can check whether they've got the full letter and that it was the exactly the letter that you sent. (e.g. via a word count etc. ). a basic analogy.

How to add a Hint in spinner in XML

In the adapter you can set the first item as disabled. Below is the sample code

@Override
public boolean isEnabled(int position) {
    if (position == 0) {
        // Disable the first item from Spinner
        // First item will be use for hint
        return false;
    } else {
        return true;
    }
}

And set the first item to grey color.

@Override
public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {
    View view = super.getDropDownView(position, convertView, parent);
    TextView tv = (TextView) view;
    if (position == 0) {
        // Set the hint text color gray
        tv.setTextColor(Color.GRAY);
    } else {
        tv.setTextColor(Color.BLACK);
    }
    return view;
}

And if the user selects the first item then do nothing.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedItemText = (String) parent.getItemAtPosition(position);
    // If user change the default selection
    // First item is disable and it is used for hint
    if (position > 0) {
        // Notify the selected item text
        Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
    }
}

Refer the below link for detail.

How to add a hint to Spinner in Android

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

How to reload .bashrc settings without logging out and back in again?

Depending on your environment, just typing

bash

may also work.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

python time + timedelta equivalent

The solution is in the link that you provided in your question:

datetime.combine(date.today(), time()) + timedelta(hours=1)

Full example:

from datetime import date, datetime, time, timedelta

dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()

Output:

00:25:00

How to ssh from within a bash script?

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

Only allow specific characters in textbox

For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.

Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

AsyncTask Android example

When you are in the worker thread, you can not directly manipulate UI elements on Android.

When you are using AsyncTask please understand the callback methods.

For example:

public class MyAyncTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        // Here you can show progress bar or something on the similar lines.
        // Since you are in a UI thread here.
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // After completing execution of given task, control will return here.
        // Hence if you want to populate UI elements with fetched data, do it here.
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // You can track you progress update here
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Here you are in the worker thread and you are not allowed to access UI thread from here.
        // Here you can perform network operations or any heavy operations you want.
        return null;
    }
}

FYI: To access the UI thread from a worker thread, you either use runOnUiThread() method or post method on your view.

For instance:

runOnUiThread(new Runnable() {
    textView.setText("something.");
});

or
    yourview.post(new Runnable() {
    yourview.setText("something");
});

This will help you know the things better. Hence in you case, you need to set your textview in the onPostExecute() method.

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

Proper way to set response status and JSON content in a REST API made with nodejs and express

You could do it this way:

res.status(400).json(json_response);

This will set the HTTP status code to 400, it works even in express 4.

Excel VBA Loop on columns

Just use the Cells function and loop thru columns. Cells(Row,Column)

SQLite add Primary Key

I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.

In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).

Suppose the table looks like:

CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);

Then I did the following:

BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;

Some tests (in sqlite shell):

sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How Do I Uninstall Yarn

I couldn't uninstall yarn on windows and I tried every single answer here, but every time I ran yarn -v, the command worked. But then I realized that there is another thing that can affect this.

If you on windows (not sure if this also happens in mac) and using nvm, one problem that can happen is that you have installed nvm without uninstalling npm, and the working yarn command is from your old yarn version from the old npm.

So what you need to do is follow this step from the nvm docs

You should also delete the existing npm install location (e.g. "C:\Users<user>\AppData\Roaming\npm"), so that the nvm install location will be correctly used instead. Backup the global npmrc config (e.g. C:\Users&lt;user>\AppData\Roaming\npm\etc\npmrc), if you have some important settings there, or copy the settings to the user config C:\Users&lt;user>.npmrc.

And to confirm that you problem is with the old npm, you will probably see the yarn.cmd file inside the C:\Users\<user>\AppData\Roaming\npm folder.

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

Using scp to copy a file to Amazon EC2 instance?

second directory is your target destination, don't use server name there. In other words, you don't need to mention machine name for the machine you're currently in.

scp -i /path/to/your/.pemkey -r /copy/from/path user@server:/copy/to/path

-r if it's a directory.

Is it possible to run a .NET 4.5 app on XP?

Sadly, no, you can't run 4.5 programs on XP.

And the relevant post from that Connect page:

Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.

How to create a simple http proxy in node.js?

Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    

SQL Inner join more than two tables

select * from Employee inner join [Order] 
On Employee.Employee_id=[Order].Employee_id
inner join Book 
On Book.Book_id=[Order].Book_id
inner join Book_Author
On Book_Author.Book_id=Book.Book_id
inner join Author
On Book_Author.Author_id=Author.Author_id;

How to delete all data from solr and hbase

I tried the below steps. It works well.

  • Please make sure the SOLR server it running
  • Just click the link Delete all SOLR data which will hit and delete all your SOLR indexed datas then you will get the following details on the screen as output.

    <response>
      <lst name="responseHeader">
        <int name="status">0</int>
        <int name="QTime">494</int>
      </lst>
    </response>
    
  • if you are not getting the above output then please make sure the following.

    • I used the default host (localhost) and port (8080) on the above link. please alter the host and port if it is different in your end.
    • The default core name should be collection / collection1. I used collection1 in the above link. please change it too if your core name is different.

Python - add PYTHONPATH during command line module run

This is for windows:

For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".

@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal

This script is located in "mygrapher". To run things, I would get into my command prompt, then do:

>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)

Excel Define a range based on a cell value

This should be close to what you are looking for your first example:

=SUM(INDIRECT("A1:A"&B1,TRUE))

This should be close to what you are looking for your final example:

=SUM(INDIRECT("A"&1+B1&":A"&B1,TRUE))

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Look here.

Basically you have to do bind params:

$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)"; 

$this->db->query($sql, '__COUNTRY_NAME__');

But, like Mr.E said, use joins:

$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?"; 

$this->db->query($sql, '__COUNTRY_NAME__');

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

How to get the first five character of a String

The problem with .Substring(,) is, that you need to be sure that the given string has at least the length of the asked number of characters, otherwise an ArgumentOutOfRangeException will be thrown.

Solution 1 (using 'Substring'):

var firstFive = stringValue != null ? 
                   stringValue.Substring(0, stringValue.Length >= 5 ? 5 : stringValue.Length) :
                   null;

The drawback of using .Substring( is that you'll need to check the length of the given string.

Solution 2 (using 'Take'):

var firstFive = stringValue != null ? 
                    string.Join("", stringValue.Take(5)) : 
                    null;

Using 'Take' will prevent that you need to check the length of the given string.

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

In DB2 Display a table's definition

db2look -d <db_name> -e -z <schema_name> -t <table_name> -i <user_name> -w <password> > <file_name>.sql

For more information, please refer below:

    db2look [-h]

    -d: Database Name: This must be specified

    -e: Extract DDL file needed to duplicate database
   -xs: Export XSR objects and generate a script containing DDL statements
 -xdir: Path name: the directory in which XSR objects will be placed
    -u: Creator ID: If -u and -a are both not specified then $USER will be used
    -z: Schema name: If -z and -a are both specified then -z will be ignored
    -t: Generate statistics for the specified tables
   -tw: Generate DDLs for tables whose names match the pattern criteria (wildcard characters) of the table name
   -ap: Generate AUDIT USING Statements
  -wlm: Generate WLM specific DDL Statements
  -mod: Generate DDL statements for Module
  -cor: Generate DDL with CREATE OR REPLACE clause
 -wrap: Generates obfuscated versions of DDL statements
    -h: More detailed help message
    -o: Redirects the output to the given file name
    -a: Generate statistics for all creators
    -m: Run the db2look utility in mimic mode
        -c: Do not generate COMMIT statements for mimic
        -r: Do not generate RUNSTATS statements for mimic
    -l: Generate Database Layout: Database partition groups, Bufferpools and Tablespaces
    -x: Generate Authorization statements DDL excluding the original definer of the object
   -xd: Generate Authorization statements DDL including the original definer of the object
    -f: Extract configuration parameters and environment variables
   -td: Specifies x to be statement delimiter (default is semicolon(;))
    -i: User ID to log on to the server where the database resides
    -w: Password to log on to the server where the database resides

How to use RANK() in SQL Server

Change:

RANK() OVER (PARTITION BY ContenderNum ORDER BY totals ASC) AS xRank

to:

RANK() OVER (ORDER BY totals DESC) AS xRank

Have a look at this example:

SQL Fiddle DEMO

You might also want to have a look at the difference between RANK (Transact-SQL) and DENSE_RANK (Transact-SQL):

RANK (Transact-SQL)

If two or more rows tie for a rank, each tied rows receives the same rank. For example, if the two top salespeople have the same SalesYTD value, they are both ranked one. The salesperson with the next highest SalesYTD is ranked number three, because there are two rows that are ranked higher. Therefore, the RANK function does not always return consecutive integers.

DENSE_RANK (Transact-SQL)

Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.

Could not install packages due to an EnvironmentError: [Errno 13]

I already tried all suggestion posted in here, yet I'm still getting the errno 13,

I'm using Windows and my python version is 3.7.3

After 5 hours of trying to solve it, this step worked for me:

I try to open the command prompt by run as administrator

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

Why is this jQuery click function not working?

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

How to add action listener that listens to multiple buttons

The first problem is that button1 is a local variable of the main method, so the actionPerformed method doesn't have access to it.

The second problem is that the ActionListener interface is implemented by the class calc, but no instance of this class is created in the main method.

The usual way to do what you want is to create an instance of calc and make button1 a field of the calc class.

Label axes on Seaborn Barplot

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

How to Export Private / Secret ASC Key to Decrypt GPG Files

1.Export a Secret Key (this is what your boss should have done for you)

gpg --export-secret-keys yourKeyName > privateKey.asc

2.Import Secret Key (import your privateKey)

gpg --import privateKey.asc

3.Not done yet, you still need to ultimately trust a key. You will need to make sure that you also ultimately trust a key.

gpg --edit-key yourKeyName

Enter trust, 5, y, and then quit

Source: https://medium.com/@GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca

PDO Prepared Inserts multiple rows in single query

The Accepted Answer by Herbert Balagtas works well when the $data array is small. With larger $data arrays the array_merge function becomes prohibitively slow. My test file to create the $data array has 28 cols and is about 80,000 lines. The final script took 41s to complete.

Using array_push() to create $insert_values instead of array_merge() resulted in a 100X speed up with execution time of 0.41s.

The problematic array_merge():

$insert_values = array();

foreach($data as $d){
 $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
 $insert_values = array_merge($insert_values, array_values($d));
}

To eliminate the need for array_merge(), you can build the following two arrays instead:

//Note that these fields are empty, but the field count should match the fields in $datafields.
$data[] = array('','','','',... n ); 

//getting rid of array_merge()
array_push($insert_values, $value1, $value2, $value3 ... n ); 

These arrays can then be used as follows:

function placeholders($text, $count=0, $separator=","){
    $result = array();
    if($count > 0){
        for($x=0; $x<$count; $x++){
            $result[] = $text;
        }
    }

    return implode($separator, $result);
}

$pdo->beginTransaction();

foreach($data as $d){
 $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
}

$sql = "INSERT INTO table (" . implode(",", array_keys($datafield) ) . ") VALUES " . implode(',', $question_marks);

$stmt = $pdo->prepare($sql);
$stmt->execute($insert_values);
$pdo->commit();

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

what is the difference between ajax and jquery and which one is better?

A more simple English explanation: jQuery is something that makes AJAX and other JavaScript tasks much easier.

npm - EPERM: operation not permitted on Windows

After trying everything and nothing works. Moving my working project folder to diffrent destination worked for me.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

They're spelled out pretty well in intellisense. Just type System.Collections. or System.Collections.Generics (preferred) and you'll get a list and short description of what's available.

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

How to load my app from Eclipse to my Android phone instead of AVD

Thanks this helped. It was a little tricky getting the USB debugging option enabled on the Samsung G3 after the update.

See below Instructions on Samsung G3 Jellybean

  1. Settings
  2. Click --> About the phone
  3. Tap on the build number
  4. “You are now 4 steps away from being a developer.” Keep tapping until it says “You are now a developer.”
  5. Go back to Setting-->System --> Developer option: Enable USB Debugging

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

On your android phone go to:
settings -> application manager -> all -> samsung keyboard and then click on "clear cache"
(delete all data collected by this application).

Encoding URL query parameters in Java

String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";

I observed in case of Datetime (Timestamp) URLEncoder.encode(param,"UTF-8") does not work.

ComboBox.SelectedText doesn't give me the SelectedText

To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:

string myItem = comboBox1.SelectedItem.ToString(); //this does the trick

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I've encountered this error when I tried to access the 'canvas' outside of onDraw()

    private Canvas canvas;

    @Override
    protected void onDraw(Canvas canvas) {
        this.canvas = canvas;
        ....... }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) { 
            canvas.save(); // here

A very bad practice :/

Git push rejected "non-fast-forward"

I'm late to the party but I found some useful instructions in github help page and I wanted to share them here.

Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.

If another person has pushed to the same branch as you, Git won't be able to push your changes:

$ git push origin master
To https://github.com/USERNAME/REPOSITORY.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Or, you can simply use git pull to perform both commands at once:

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

PHP PDO returning single row

If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php

How to get everything after last slash in a URL?

One more (idio(ma)tic) way:

URL.split("/")[-1]

How to store Configuration file and read it using React

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

For React:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

Not sure if it covers your use case but it's been working pretty well for us.

How do I enumerate the properties of a JavaScript object?

for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}

SQL grammar for SELECT MIN(DATE)

SELECT  MIN(Date)  AS Date  FROM tbl_Employee /*To get First date Of Employee*/

How to get GET (query string) variables in Express.js on Node.js?

For Express.js you want to do req.params:

app.get('/user/:id', function(req, res) {
  res.send('user' + req.params.id);    
});

How can I debug a Perl script?

I would also recommend using the Perl debugger.

However, since you asked about something like shell's -x have a look at the Devel::Trace module which does something similar.

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Convert Pandas Series to DateTime in a DataFrame

df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])

type(df.<column name>)

example: if you want to convert day which is initially a string to a Timestamp in Pandas

df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])

type(df.day)

The output will be pandas.tslib.Timestamp

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Sending cookies with postman

You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.

Button Width Match Parent

Place your RaisedButton(...) in a SizedBox

SizedBox(
  width: double.infinity,
  child: RaisedButton(...),
)

How to create a new object instance from a Type

If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke(). Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL opcodes and DynamicMethod. Either way, the difference is huge when you start getting into tight loops or multiple calls.

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

How to use JavaScript with Selenium WebDriver Java

You can also try clicking by JavaScript:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

Merge up to a specific commit

Sure, being in master branch all you need to do is:

git merge <commit-id>

where commit-id is hash of the last commit from newbranch that you want to get in your master branch.

You can find out more about any git command by doing git help <command>. It that case it's git help merge. And docs are saying that the last argument for merge command is <commit>..., so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.

Using Pip to install packages to Anaconda Environment

All you have to do is open Anaconda Prompt and type

pip install package-name

It will automatically install to the anaconda environment without having to use

conda install package-name

Since some of the conda packages may lack support overtime it is required to install using pip and this is one way to do it

If you have pip installed in anaconda you can run the following in jupyter notebook or in your python shell that is linked to anaconda

pip.main(['install', 'package-name'])

Check your version of pip with pip.__version__. If it is version 10.x.x or above, then install your python package with this line of code

subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'package-name'])

In your jupyter notebook, you can install python packages through pip in a cell this way;

!pip install package-name

or you could use your python version associated with anaconda

!python3.6 -m pip install package-name

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

How to import Swagger APIs into Postman?

The accepted answer is correct but I will rewrite complete steps for java.

I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.

Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Step 2: Add configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
      public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
              DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());

    @Bean
    public Docket api() {
        Set<String> producesAndConsumes = new HashSet<>();
        producesAndConsumes.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(producesAndConsumes)
                .consumes(producesAndConsumes);

    }
}

Step 3: Setup complete and now you need to document APIs in controllers

    @ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @GetMapping(path = "/articles/users/{userId}")
    public List<Article> getArticlesByUser() {
       // Do your code
    }

Usage:

You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.

enter image description here

Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.

enter image description here

Lumen: get URL parameter in a Blade view

The shortest way i have used

{{ Request::get('a') }}

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

What is the list of supported languages/locales on Android?

List of locales supported as of API 22 (Android 5.1). Obtained from a Nexus 5 with locale set to "English (United States)" (locale affects the DisplayName output).

for (Locale locale : Locale.getAvailableLocales()) {
    Log.d("LOCALES", locale.getLanguage() + "_" + locale.getCountry() + " [" + locale.getDisplayName() + "]");
}


    af_ [Afrikaans]
    af_NA [Afrikaans (Namibia)]
    af_ZA [Afrikaans (South Africa)]
    agq_ [Aghem]
    agq_CM [Aghem (Cameroon)]
    ak_ [Akan]
    ak_GH [Akan (Ghana)]
    am_ [Amharic]
    am_ET [Amharic (Ethiopia)]
    ar_ [Arabic]
    ar_001 [Arabic (World)]
    ar_AE [Arabic (United Arab Emirates)]
    ar_BH [Arabic (Bahrain)]
    ar_DJ [Arabic (Djibouti)]
    ar_DZ [Arabic (Algeria)]
    ar_EG [Arabic (Egypt)]
    ar_EH [Arabic (Western Sahara)]
    ar_ER [Arabic (Eritrea)]
    ar_IL [Arabic (Israel)]
    ar_IQ [Arabic (Iraq)]
    ar_JO [Arabic (Jordan)]
    ar_KM [Arabic (Comoros)]
    ar_KW [Arabic (Kuwait)]
    ar_LB [Arabic (Lebanon)]
    ar_LY [Arabic (Libya)]
    ar_MA [Arabic (Morocco)]
    ar_MR [Arabic (Mauritania)]
    ar_OM [Arabic (Oman)]
    ar_PS [Arabic (Palestine)]
    ar_QA [Arabic (Qatar)]
    ar_SA [Arabic (Saudi Arabia)]
    ar_SD [Arabic (Sudan)]
    ar_SO [Arabic (Somalia)]
    ar_SS [Arabic (South Sudan)]
    ar_SY [Arabic (Syria)]
    ar_TD [Arabic (Chad)]
    ar_TN [Arabic (Tunisia)]
    ar_YE [Arabic (Yemen)]
    as_ [Assamese]
    as_IN [Assamese (India)]
    asa_ [Asu]
    asa_TZ [Asu (Tanzania)]
    az_ [Azerbaijani]
    az_ [Azerbaijani (Cyrillic)]
    az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
    az_ [Azerbaijani (Latin)]
    az_AZ [Azerbaijani (Latin,Azerbaijan)]
    bas_ [Basaa]
    bas_CM [Basaa (Cameroon)]
    be_ [Belarusian]
    be_BY [Belarusian (Belarus)]
    bem_ [Bemba]
    bem_ZM [Bemba (Zambia)]
    bez_ [Bena]
    bez_TZ [Bena (Tanzania)]
    bg_ [Bulgarian]
    bg_BG [Bulgarian (Bulgaria)]
    bm_ [Bambara]
    bm_ML [Bambara (Mali)]
    bn_ [Bengali]
    bn_BD [Bengali (Bangladesh)]
    bn_IN [Bengali (India)]
    bo_ [Tibetan]
    bo_CN [Tibetan (China)]
    bo_IN [Tibetan (India)]
    br_ [Breton]
    br_FR [Breton (France)]
    brx_ [Bodo]
    brx_IN [Bodo (India)]
    bs_ [Bosnian]
    bs_ [Bosnian (Cyrillic)]
    bs_BA [Bosnian (Cyrillic,Bosnia and Herzegovina)]
    bs_ [Bosnian (Latin)]
    bs_BA [Bosnian (Latin,Bosnia and Herzegovina)]
    ca_ [Catalan]
    ca_AD [Catalan (Andorra)]
    ca_ES [Catalan (Spain)]
    ca_FR [Catalan (France)]
    ca_IT [Catalan (Italy)]
    cgg_ [Chiga]
    cgg_UG [Chiga (Uganda)]
    chr_ [Cherokee]
    chr_US [Cherokee (United States)]
    cs_ [Czech]
    cs_CZ [Czech (Czech Republic)]
    cy_ [Welsh]
    cy_GB [Welsh (United Kingdom)]
    da_ [Danish]
    da_DK [Danish (Denmark)]
    da_GL [Danish (Greenland)]
    dav_ [Taita]
    dav_KE [Taita (Kenya)]
    de_ [German]
    de_AT [German (Austria)]
    de_BE [German (Belgium)]
    de_CH [German (Switzerland)]
    de_DE [German (Germany)]
    de_LI [German (Liechtenstein)]
    de_LU [German (Luxembourg)]
    dje_ [Zarma]
    dje_NE [Zarma (Niger)]
    dua_ [Duala]
    dua_CM [Duala (Cameroon)]
    dyo_ [Jola-Fonyi]
    dyo_SN [Jola-Fonyi (Senegal)]
    dz_ [Dzongkha]
    dz_BT [Dzongkha (Bhutan)]
    ebu_ [Embu]
    ebu_KE [Embu (Kenya)]
    ee_ [Ewe]
    ee_GH [Ewe (Ghana)]
    ee_TG [Ewe (Togo)]
    el_ [Greek]
    el_CY [Greek (Cyprus)]
    el_GR [Greek (Greece)]
    en_ [English]
    en_001 [English (World)]
    en_150 [English (Europe)]
    en_AG [English (Antigua and Barbuda)]
    en_AI [English (Anguilla)]
    en_AS [English (American Samoa)]
    en_AU [English (Australia)]
    en_BB [English (Barbados)]
    en_BE [English (Belgium)]
    en_BM [English (Bermuda)]
    en_BS [English (Bahamas)]
    en_BW [English (Botswana)]
    en_BZ [English (Belize)]
    en_CA [English (Canada)]
    en_CC [English (Cocos (Keeling) Islands)]
    en_CK [English (Cook Islands)]
    en_CM [English (Cameroon)]
    en_CX [English (Christmas Island)]
    en_DG [English (Diego Garcia)]
    en_DM [English (Dominica)]
    en_ER [English (Eritrea)]
    en_FJ [English (Fiji)]
    en_FK [English (Falkland Islands (Islas Malvinas))]
    en_FM [English (Micronesia)]
    en_GB [English (United Kingdom)]
    en_GD [English (Grenada)]
    en_GG [English (Guernsey)]
    en_GH [English (Ghana)]
    en_GI [English (Gibraltar)]
    en_GM [English (Gambia)]
    en_GU [English (Guam)]
    en_GY [English (Guyana)]
    en_HK [English (Hong Kong)]
    en_IE [English (Ireland)]
    en_IM [English (Isle of Man)]
    en_IN [English (India)]
    en_IO [English (British Indian Ocean Territory)]
    en_JE [English (Jersey)]
    en_JM [English (Jamaica)]
    en_KE [English (Kenya)]
    en_KI [English (Kiribati)]
    en_KN [English (Saint Kitts and Nevis)]
    en_KY [English (Cayman Islands)]
    en_LC [English (Saint Lucia)]
    en_LR [English (Liberia)]
    en_LS [English (Lesotho)]
    en_MG [English (Madagascar)]
    en_MH [English (Marshall Islands)]
    en_MO [English (Macau)]
    en_MP [English (Northern Mariana Islands)]
    en_MS [English (Montserrat)]
    en_MT [English (Malta)]
    en_MU [English (Mauritius)]
    en_MW [English (Malawi)]
    en_NA [English (Namibia)]
    en_NF [English (Norfolk Island)]
    en_NG [English (Nigeria)]
    en_NR [English (Nauru)]
    en_NU [English (Niue)]
    en_NZ [English (New Zealand)]
    en_PG [English (Papua New Guinea)]
    en_PH [English (Philippines)]
    en_PK [English (Pakistan)]
    en_PN [English (Pitcairn Islands)]
    en_PR [English (Puerto Rico)]
    en_PW [English (Palau)]
    en_RW [English (Rwanda)]
    en_SB [English (Solomon Islands)]
    en_SC [English (Seychelles)]
    en_SD [English (Sudan)]
    en_SG [English (Singapore)]
    en_SH [English (Saint Helena)]
    en_SL [English (Sierra Leone)]
    en_SS [English (South Sudan)]
    en_SX [English (Sint Maarten)]
    en_SZ [English (Swaziland)]
    en_TC [English (Turks and Caicos Islands)]
    en_TK [English (Tokelau)]
    en_TO [English (Tonga)]
    en_TT [English (Trinidad and Tobago)]
    en_TV [English (Tuvalu)]
    en_TZ [English (Tanzania)]
    en_UG [English (Uganda)]
    en_UM [English (U.S. Outlying Islands)]
    en_US [English (United States)]
    en_US [English (United States,Computer)]
    en_VC [English (St. Vincent & Grenadines)]
    en_VG [English (British Virgin Islands)]
    en_VI [English (U.S. Virgin Islands)]
    en_VU [English (Vanuatu)]
    en_WS [English (Samoa)]
    en_ZA [English (South Africa)]
    en_ZM [English (Zambia)]
    en_ZW [English (Zimbabwe)]
    eo_ [Esperanto]
    es_ [Spanish]
    es_419 [Spanish (Latin America)]
    es_AR [Spanish (Argentina)]
    es_BO [Spanish (Bolivia)]
    es_CL [Spanish (Chile)]
    es_CO [Spanish (Colombia)]
    es_CR [Spanish (Costa Rica)]
    es_CU [Spanish (Cuba)]
    es_DO [Spanish (Dominican Republic)]
    es_EA [Spanish (Ceuta and Melilla)]
    es_EC [Spanish (Ecuador)]
    es_ES [Spanish (Spain)]
    es_GQ [Spanish (Equatorial Guinea)]
    es_GT [Spanish (Guatemala)]
    es_HN [Spanish (Honduras)]
    es_IC [Spanish (Canary Islands)]
    es_MX [Spanish (Mexico)]
    es_NI [Spanish (Nicaragua)]
    es_PA [Spanish (Panama)]
    es_PE [Spanish (Peru)]
    es_PH [Spanish (Philippines)]
    es_PR [Spanish (Puerto Rico)]
    es_PY [Spanish (Paraguay)]
    es_SV [Spanish (El Salvador)]
    es_US [Spanish (United States)]
    es_UY [Spanish (Uruguay)]
    es_VE [Spanish (Venezuela)]
    et_ [Estonian]
    et_EE [Estonian (Estonia)]
    eu_ [Basque]
    eu_ES [Basque (Spain)]
    ewo_ [Ewondo]
    ewo_CM [Ewondo (Cameroon)]
    fa_ [Persian]
    fa_AF [Persian (Afghanistan)]
    fa_IR [Persian (Iran)]
    ff_ [Fulah]
    ff_SN [Fulah (Senegal)]
    fi_ [Finnish]
    fi_FI [Finnish (Finland)]
    fil_ [Filipino]
    fil_PH [Filipino (Philippines)]
    fo_ [Faroese]
    fo_FO [Faroese (Faroe Islands)]
    fr_ [French]
    fr_BE [French (Belgium)]
    fr_BF [French (Burkina Faso)]
    fr_BI [French (Burundi)]
    fr_BJ [French (Benin)]
    fr_BL [French (Saint Barthélemy)]
    fr_CA [French (Canada)]
    fr_CD [French (Congo (DRC))]
    fr_CF [French (Central African Republic)]
    fr_CG [French (Congo (Republic))]
    fr_CH [French (Switzerland)]
    fr_CI [French (Côte d’Ivoire)]
    fr_CM [French (Cameroon)]
    fr_DJ [French (Djibouti)]
    fr_DZ [French (Algeria)]
    fr_FR [French (France)]
    fr_GA [French (Gabon)]
    fr_GF [French (French Guiana)]
    fr_GN [French (Guinea)]
    fr_GP [French (Guadeloupe)]
    fr_GQ [French (Equatorial Guinea)]
    fr_HT [French (Haiti)]
    fr_KM [French (Comoros)]
    fr_LU [French (Luxembourg)]
    fr_MA [French (Morocco)]
    fr_MC [French (Monaco)]
    fr_MF [French (Saint Martin)]
    fr_MG [French (Madagascar)]
    fr_ML [French (Mali)]
    fr_MQ [French (Martinique)]
    fr_MR [French (Mauritania)]
    fr_MU [French (Mauritius)]
    fr_NC [French (New Caledonia)]
    fr_NE [French (Niger)]
    fr_PF [French (French Polynesia)]
    fr_PM [French (Saint Pierre and Miquelon)]
    fr_RE [French (Réunion)]
    fr_RW [French (Rwanda)]
    fr_SC [French (Seychelles)]
    fr_SN [French (Senegal)]
    fr_SY [French (Syria)]
    fr_TD [French (Chad)]
    fr_TG [French (Togo)]
    fr_TN [French (Tunisia)]
    fr_VU [French (Vanuatu)]
    fr_WF [French (Wallis and Futuna)]
    fr_YT [French (Mayotte)]
    ga_ [Irish]
    ga_IE [Irish (Ireland)]
    gl_ [Galician]
    gl_ES [Galician (Spain)]
    gsw_ [Swiss German]
    gsw_CH [Swiss German (Switzerland)]
    gsw_LI [Swiss German (Liechtenstein)]
    gu_ [Gujarati]
    gu_IN [Gujarati (India)]
    guz_ [Gusii]
    guz_KE [Gusii (Kenya)]
    gv_ [Manx]
    gv_IM [Manx (Isle of Man)]
    ha_ [Hausa]
    ha_ [Hausa (Latin)]
    ha_GH [Hausa (Latin,Ghana)]
    ha_NE [Hausa (Latin,Niger)]
    ha_NG [Hausa (Latin,Nigeria)]
    haw_ [Hawaiian]
    haw_US [Hawaiian (United States)]
    iw_ [Hebrew]
    iw_IL [Hebrew (Israel)]
    hi_ [Hindi]
    hi_IN [Hindi (India)]
    hr_ [Croatian]
    hr_BA [Croatian (Bosnia and Herzegovina)]
    hr_HR [Croatian (Croatia)]
    hu_ [Hungarian]
    hu_HU [Hungarian (Hungary)]
    hy_ [Armenian]
    hy_AM [Armenian (Armenia)]
    in_ [Indonesian]
    in_ID [Indonesian (Indonesia)]
    ig_ [Igbo]
    ig_NG [Igbo (Nigeria)]
    ii_ [Sichuan Yi]
    ii_CN [Sichuan Yi (China)]
    is_ [Icelandic]
    is_IS [Icelandic (Iceland)]
    it_ [Italian]
    it_CH [Italian (Switzerland)]
    it_IT [Italian (Italy)]
    it_SM [Italian (San Marino)]
    ja_ [Japanese]
    ja_JP [Japanese (Japan)]
    jgo_ [Ngomba]
    jgo_CM [Ngomba (Cameroon)]
    jmc_ [Machame]
    jmc_TZ [Machame (Tanzania)]
    ka_ [Georgian]
    ka_GE [Georgian (Georgia)]
    kab_ [Kabyle]
    kab_DZ [Kabyle (Algeria)]
    kam_ [Kamba]
    kam_KE [Kamba (Kenya)]
    kde_ [Makonde]
    kde_TZ [Makonde (Tanzania)]
    kea_ [Kabuverdianu]
    kea_CV [Kabuverdianu (Cape Verde)]
    khq_ [Koyra Chiini]
    khq_ML [Koyra Chiini (Mali)]
    ki_ [Kikuyu]
    ki_KE [Kikuyu (Kenya)]
    kk_ [Kazakh]
    kk_ [Kazakh (Cyrillic)]
    kk_KZ [Kazakh (Cyrillic,Kazakhstan)]
    kkj_ [Kako]
    kkj_CM [Kako (Cameroon)]
    kl_ [Kalaallisut]
    kl_GL [Kalaallisut (Greenland)]
    kln_ [Kalenjin]
    kln_KE [Kalenjin (Kenya)]
    km_ [Khmer]
    km_KH [Khmer (Cambodia)]
    kn_ [Kannada]
    kn_IN [Kannada (India)]
    ko_ [Korean]
    ko_KP [Korean (North Korea)]
    ko_KR [Korean (South Korea)]
    kok_ [Konkani]
    kok_IN [Konkani (India)]
    ks_ [Kashmiri]
    ks_ [Kashmiri (Arabic)]
    ks_IN [Kashmiri (Arabic,India)]
    ksb_ [Shambala]
    ksb_TZ [Shambala (Tanzania)]
    ksf_ [Bafia]
    ksf_CM [Bafia (Cameroon)]
    kw_ [Cornish]
    kw_GB [Cornish (United Kingdom)]
    ky_ [Kyrgyz]
    ky_ [Kyrgyz (Cyrillic)]
    ky_KG [Kyrgyz (Cyrillic,Kyrgyzstan)]
    lag_ [Langi]
    lag_TZ [Langi (Tanzania)]
    lg_ [Ganda]
    lg_UG [Ganda (Uganda)]
    lkt_ [Lakota]
    lkt_US [Lakota (United States)]
    ln_ [Lingala]
    ln_AO [Lingala (Angola)]
    ln_CD [Lingala (Congo (DRC))]
    ln_CF [Lingala (Central African Republic)]
    ln_CG [Lingala (Congo (Republic))]
    lo_ [Lao]
    lo_LA [Lao (Laos)]
    lt_ [Lithuanian]
    lt_LT [Lithuanian (Lithuania)]
    lu_ [Luba-Katanga]
    lu_CD [Luba-Katanga (Congo (DRC))]
    luo_ [Luo]
    luo_KE [Luo (Kenya)]
    luy_ [Luyia]
    luy_KE [Luyia (Kenya)]
    lv_ [Latvian]
    lv_LV [Latvian (Latvia)]
    mas_ [Masai]
    mas_KE [Masai (Kenya)]
    mas_TZ [Masai (Tanzania)]
    mer_ [Meru]
    mer_KE [Meru (Kenya)]
    mfe_ [Morisyen]
    mfe_MU [Morisyen (Mauritius)]
    mg_ [Malagasy]
    mg_MG [Malagasy (Madagascar)]
    mgh_ [Makhuwa-Meetto]
    mgh_MZ [Makhuwa-Meetto (Mozambique)]
    mgo_ [Meta']
    mgo_CM [Meta' (Cameroon)]
    mk_ [Macedonian]
    mk_MK [Macedonian (Macedonia (FYROM))]
    ml_ [Malayalam]
    ml_IN [Malayalam (India)]
    mn_ [Mongolian]
    mn_ [Mongolian (Cyrillic)]
    mn_MN [Mongolian (Cyrillic,Mongolia)]
    mr_ [Marathi]
    mr_IN [Marathi (India)]
    ms_ [Malay]
    ms_ [Malay (Latin)]
    ms_BN [Malay (Latin,Brunei)]
    ms_MY [Malay (Latin,Malaysia)]
    ms_SG [Malay (Latin,Singapore)]
    mt_ [Maltese]
    mt_MT [Maltese (Malta)]
    mua_ [Mundang]
    mua_CM [Mundang (Cameroon)]
    my_ [Burmese]
    my_MM [Burmese (Myanmar (Burma))]
    naq_ [Nama]
    naq_NA [Nama (Namibia)]
    nb_ [Norwegian Bokmål]
    nb_NO [Norwegian Bokmål (Norway)]
    nb_SJ [Norwegian Bokmål (Svalbard and Jan Mayen)]
    nd_ [North Ndebele]
    nd_ZW [North Ndebele (Zimbabwe)]
    ne_ [Nepali]
    ne_IN [Nepali (India)]
    ne_NP [Nepali (Nepal)]
    nl_ [Dutch]
    nl_AW [Dutch (Aruba)]
    nl_BE [Dutch (Belgium)]
    nl_BQ [Dutch (Caribbean Netherlands)]
    nl_CW [Dutch (Curaçao)]
    nl_NL [Dutch (Netherlands)]
    nl_SR [Dutch (Suriname)]
    nl_SX [Dutch (Sint Maarten)]
    nmg_ [Kwasio]
    nmg_CM [Kwasio (Cameroon)]
    nn_ [Norwegian Nynorsk]
    nn_NO [Norwegian Nynorsk (Norway)]
    nnh_ [Ngiemboon]
    nnh_CM [Ngiemboon (Cameroon)]
    nus_ [Nuer]
    nus_SD [Nuer (Sudan)]
    nyn_ [Nyankole]
    nyn_UG [Nyankole (Uganda)]
    om_ [Oromo]
    om_ET [Oromo (Ethiopia)]
    om_KE [Oromo (Kenya)]
    or_ [Oriya]
    or_IN [Oriya (India)]
    pa_ [Punjabi]
    pa_ [Punjabi (Arabic)]
    pa_PK [Punjabi (Arabic,Pakistan)]
    pa_ [Punjabi (Gurmukhi)]
    pa_IN [Punjabi (Gurmukhi,India)]
    pl_ [Polish]
    pl_PL [Polish (Poland)]
    ps_ [Pashto]
    ps_AF [Pashto (Afghanistan)]
    pt_ [Portuguese]
    pt_AO [Portuguese (Angola)]
    pt_BR [Portuguese (Brazil)]
    pt_CV [Portuguese (Cape Verde)]
    pt_GW [Portuguese (Guinea-Bissau)]
    pt_MO [Portuguese (Macau)]
    pt_MZ [Portuguese (Mozambique)]
    pt_PT [Portuguese (Portugal)]
    pt_ST [Portuguese (São Tomé and Príncipe)]
    pt_TL [Portuguese (Timor-Leste)]
    rm_ [Romansh]
    rm_CH [Romansh (Switzerland)]
    rn_ [Rundi]
    rn_BI [Rundi (Burundi)]
    ro_ [Romanian]
    ro_MD [Romanian (Moldova)]
    ro_RO [Romanian (Romania)]
    rof_ [Rombo]
    rof_TZ [Rombo (Tanzania)]
    ru_ [Russian]
    ru_BY [Russian (Belarus)]
    ru_KG [Russian (Kyrgyzstan)]
    ru_KZ [Russian (Kazakhstan)]
    ru_MD [Russian (Moldova)]
    ru_RU [Russian (Russia)]
    ru_UA [Russian (Ukraine)]
    rw_ [Kinyarwanda]
    rw_RW [Kinyarwanda (Rwanda)]
    rwk_ [Rwa]
    rwk_TZ [Rwa (Tanzania)]
    saq_ [Samburu]
    saq_KE [Samburu (Kenya)]
    sbp_ [Sangu]
    sbp_TZ [Sangu (Tanzania)]
    seh_ [Sena]
    seh_MZ [Sena (Mozambique)]
    ses_ [Koyraboro Senni]
    ses_ML [Koyraboro Senni (Mali)]
    sg_ [Sango]
    sg_CF [Sango (Central African Republic)]
    shi_ [Tachelhit]
    shi_ [Tachelhit (Latin)]
    shi_MA [Tachelhit (Latin,Morocco)]
    shi_ [Tachelhit (Tifinagh)]
    shi_MA [Tachelhit (Tifinagh,Morocco)]
    si_ [Sinhala]
    si_LK [Sinhala (Sri Lanka)]
    sk_ [Slovak]
    sk_SK [Slovak (Slovakia)]
    sl_ [Slovenian]
    sl_SI [Slovenian (Slovenia)]
    sn_ [Shona]
    sn_ZW [Shona (Zimbabwe)]
    so_ [Somali]
    so_DJ [Somali (Djibouti)]
    so_ET [Somali (Ethiopia)]
    so_KE [Somali (Kenya)]
    so_SO [Somali (Somalia)]
    sq_ [Albanian]
    sq_AL [Albanian (Albania)]
    sq_MK [Albanian (Macedonia (FYROM))]
    sq_XK [Albanian (Kosovo)]
    sr_ [Serbian]
    sr_ [Serbian (Cyrillic)]
    sr_BA [Serbian (Cyrillic,Bosnia and Herzegovina)]
    sr_ME [Serbian (Cyrillic,Montenegro)]
    sr_RS [Serbian (Cyrillic,Serbia)]
    sr_XK [Serbian (Cyrillic,Kosovo)]
    sr_ [Serbian (Latin)]
    sr_BA [Serbian (Latin,Bosnia and Herzegovina)]
    sr_ME [Serbian (Latin,Montenegro)]
    sr_RS [Serbian (Latin,Serbia)]
    sr_XK [Serbian (Latin,Kosovo)]
    sv_ [Swedish]
    sv_AX [Swedish (Åland Islands)]
    sv_FI [Swedish (Finland)]
    sv_SE [Swedish (Sweden)]
    sw_ [Swahili]
    sw_KE [Swahili (Kenya)]
    sw_TZ [Swahili (Tanzania)]
    sw_UG [Swahili (Uganda)]
    swc_ [Congo Swahili]
    swc_CD [Congo Swahili (Congo (DRC))]
    ta_ [Tamil]
    ta_IN [Tamil (India)]
    ta_LK [Tamil (Sri Lanka)]
    ta_MY [Tamil (Malaysia)]
    ta_SG [Tamil (Singapore)]
    te_ [Telugu]
    te_IN [Telugu (India)]
    teo_ [Teso]
    teo_KE [Teso (Kenya)]
    teo_UG [Teso (Uganda)]
    th_ [Thai]
    th_TH [Thai (Thailand)]
    ti_ [Tigrinya]
    ti_ER [Tigrinya (Eritrea)]
    ti_ET [Tigrinya (Ethiopia)]
    to_ [Tongan]
    to_TO [Tongan (Tonga)]
    tr_ [Turkish]
    tr_CY [Turkish (Cyprus)]
    tr_TR [Turkish (Turkey)]
    twq_ [Tasawaq]
    twq_NE [Tasawaq (Niger)]
    tzm_ [Central Atlas Tamazight]
    tzm_ [Central Atlas Tamazight (Latin)]
    tzm_MA [Central Atlas Tamazight (Latin,Morocco)]
    ug_ [Uyghur]
    ug_ [Uyghur (Arabic)]
    ug_CN [Uyghur (Arabic,China)]
    uk_ [Ukrainian]
    uk_UA [Ukrainian (Ukraine)]
    ur_ [Urdu]
    ur_IN [Urdu (India)]
    ur_PK [Urdu (Pakistan)]
    uz_ [Uzbek]
    uz_ [Uzbek (Arabic)]
    uz_AF [Uzbek (Arabic,Afghanistan)]
    uz_ [Uzbek (Cyrillic)]
    uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
    uz_ [Uzbek (Latin)]
    uz_UZ [Uzbek (Latin,Uzbekistan)]
    vai_ [Vai]
    vai_ [Vai (Latin)]
    vai_LR [Vai (Latin,Liberia)]
    vai_ [Vai (Vai)]
    vai_LR [Vai (Vai,Liberia)]
    vi_ [Vietnamese]
    vi_VN [Vietnamese (Vietnam)]
    vun_ [Vunjo]
    vun_TZ [Vunjo (Tanzania)]
    xog_ [Soga]
    xog_UG [Soga (Uganda)]
    yav_ [Yangben]
    yav_CM [Yangben (Cameroon)]
    yo_ [Yoruba]
    yo_BJ [Yoruba (Benin)]
    yo_NG [Yoruba (Nigeria)]
    zgh_ [Standard Moroccan Tamazight]
    zgh_MA [Standard Moroccan Tamazight (Morocco)]
    zh_ [Chinese]
    zh_ [Chinese (Simplified Han)]
    zh_CN [Chinese (Simplified Han,China)]
    zh_HK [Chinese (Simplified Han,Hong Kong)]
    zh_MO [Chinese (Simplified Han,Macau)]
    zh_SG [Chinese (Simplified Han,Singapore)]
    zh_ [Chinese (Traditional Han)]
    zh_HK [Chinese (Traditional Han,Hong Kong)]
    zh_MO [Chinese (Traditional Han,Macau)]
    zh_TW [Chinese (Traditional Han,Taiwan)]
    zu_ [Zulu]
    zu_ZA [Zulu (South Africa)]

How to exclude records with certain values in sql select

You can use EXCEPT syntax, for example:

SELECT var FROM table1
EXCEPT
SELECT var FROM table2

Why am I getting Unknown error in line 1 of pom.xml?

In my pom.xml file I had to downgrade the version from 2.1.6.RELEASE for spring-boot-starter-parent artifact to 2.1.4.RELEASE

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

to be changed to

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

And that weird Unknown error disappeared

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

You can do the following:

foreach (Control X in this.Controls)
{
    TextBox tb = X as TextBox;
    if (tb != null)
    {
        string text = tb.Text;
        // Do something to text...
        tb.Text = string.Empty; // Clears it out...
    }
}

How do I compare 2 rows from the same table (SQL Server)?

SELECT * FROM A AS b INNER JOIN A AS c ON b.a = c.a
WHERE b.a = 'some column value'

There is an error in XML document (1, 41)

I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.

How to combine two vectors into a data frame

Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

Check if key exists and iterate the JSON array using Python

if "my_data" in my_json_data:
         print json.dumps(my_json_data["my_data"])

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

How to build an android library with Android Studio and gradle?

Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.

TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/

Disclaimer: This is a project I am/was working on.

Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.

Project Root
+-- src
|   +-- main (your project)
|   |   +-- java (where your java code goes)
|   |   +-- res  (where your res go)
|   |   +-- assets (where your assets go)
|   |   \-- AndroidManifest.xml
|   \-- instrumentTest (test project)
|       \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle

If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.

Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.3'
    }
}

Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.

build.gradle

apply plugin: "android"
android {
        compileSdkVersion 17
        /*
        defaultConfig {
            versionCode = 1
            versionName = "0.0.0"
        }
        */
    }

Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.

build.gradle

task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
    gradleVersion = '1.4'
}

So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.

Directory Structure:

Project Root
+-- src (see above)
+-- subProjects (where projects are held)
|   +-- reallyCoolProject1 (your first included project)
|       \-- See project structure for a normal app
|   \-- reallyCoolProject2 (your second included project)
|       \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle

settings.gradle:

include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'

The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library" instead of apply plugin: "android".

Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.

build.gradle

dependencies{
    compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
    compile project(":subProjects:reallyCoolProject1")
    compile project(':subProjects:reallyCoolProject2')
}

I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.

NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923

build.gradle

task copyNativeLibs(type: Copy) {
    from fileTree(dir: 'libs', include: '**/*.so' )  into  'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }

clean.dependsOn 'cleanCopyNativeLibs'

tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
  pkgTask.jniDir new File('build/native-libs')
}

Sources:

  1. http://tools.android.com/tech-docs/new-build-system/user-guide
  2. https://gist.github.com/khernyo/4226923
  3. https://github.com/ethankhall/driving-time-tracker/

What are OLTP and OLAP. What is the difference between them?

Here you will find a better solution OLTP vs. OLAP

  • OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.

  • OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

Django request.GET

Here is a good way to do it.

from django.utils.datastructures import MultiValueDictKeyError
try:
    message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
    message = 'You submitted nothing!'

You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.

How do I remove a file from the FileList

I know this is an old question but it's ranking high on search engines in regards to this issue.

properties in the FileList object cannot be deleted but at least on Firefox they can be changed. My workaround this issue was to add a property IsValid=true to those files that passed check and IsValid=false to those that didn't.

then I just loop through the list to make sure that only the properties with IsValid=true are added to FormData.

Navigation bar with UIImage for title

In order to get the image view with the proper size and in the center, you should use the following approach:

let width = 120 // choose the image width
let height = 20 // choose the image height
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) //44 is the standard size of the top bar
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width - width)/2, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit //choose other if it makes sense
imageView.image = UIImage(named: "your_image_name")
titleView.addSubview(imageView)
navigationItem.titleView = titleView

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">

You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools" and tools:ignore="GoogleAppIndexingWarning" to the <manifest> tag.

What Scala web-frameworks are available?

Both Sweet and Slinky seem to be unmaintanted for about a year. Sweet Maven repo sweetsoftwaredesign.com is dead so there's even no way to download dependencies.

How to read embedded resource text file

The answer is quite simple, simply do this if you added the file directly from the resources.resx.

string textInResourceFile = fileNameSpace.Properties.Resources.fileName;

With that line of code, the text from the file is directly read from the file and put into the string variable.

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

I want to remove double quotes from a String

Assuming:

var someStr = 'He said "Hello, my name is Foo"';
console.log(someStr.replace(/['"]+/g, ''));

That should do the trick... (if your goal is to replace all double quotes).

Here's how it works:

  • ['"] is a character class, matches both single and double quotes. you can replace this with " to only match double quotes.
  • +: one or more quotes, chars, as defined by the preceding char-class (optional)
  • g: the global flag. This tells JS to apply the regex to the entire string. If you omit this, you'll only replace a single char.

If you're trying to remove the quotes around a given string (ie in pairs), things get a bit trickier. You'll have to use lookaround assertions:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove foo delimiting quotes
str = 'remove only "foo" delimiting "';//note trailing " at the end
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove only foo delimiting "<-- trailing double quote is not removed

Regex explained:

  • ": literal, matches any literal "
  • (: begin capturing group. Whatever is between the parentheses (()) will be captured, and can be used in the replacement value.
  • [^"]+: Character class, matches all chars, except " 1 or more times
  • (?="): zero-width (as in not captured) positive lookahead assertion. The previous match will only be valid if it's followed by a " literal
  • ): end capturing group, we've captured everything in between the opening closing "
  • ": another literal, cf list item one

The replacement is '$1', this is a back-reference to the first captured group, being [^" ]+, or everyting in between the double quotes. The pattern matches both the quotes and what's inbetween them, but replaces it only with what's in between the quotes, thus effectively removing them.
What it does is some "string with" quotes -> replaces "string with" with -> string with. Quotes gone, job done.

If the quotes are always going to be at the begining and end of the string, then you could use this:

str.replace(/^"(.+(?="$))"$/, '$1');

or this for double and single quotes:

str.replace(/^["'](.+(?=["']$))["']$/, '$1');

With input remove "foo" delimiting ", the output will remain unchanged, but change the input string to "remove "foo" delimiting quotes", and you'll end up with remove "foo" delimiting quotes as output.

Explanation:

  • ^": matches the beginning of the string ^ and a ". If the string does not start with a ", the expression already fails here, and nothing is replaced.
  • (.+(?="$)): matches (and captures) everything, including double quotes one or more times, provided the positive lookahead is true
  • (?="$): the positive lookahead is much the same as above, only it specifies that the " must be the end of the string ($ === end)
  • "$: matches that ending quote, but does not capture it

The replacement is done in the same way as before: we replace the match (which includes the opening and closing quotes), with everything that was inside them.
You may have noticed I've omitted the g flag (for global BTW), because since we're processing the entire string, this expression only applies once.
An easier regex that does, pretty much, the same thing (there are internal difference of how the regex is compiled/applied) would be:

someStr.replace(/^"(.+)"$/,'$1');

As before ^" and "$ match the delimiting quotes at the start and end of a string, and the (.+) matches everything in between, and captures it. I've tried this regex, along side the one above (with lookahead assertion) and, admittedly, to my surprize found this one to be slightly slower. My guess would be that the lookaround assertion causes the previous expression to fail as soon as the engine determines there is no " at the end of the string. Ah well, but if this is what you want/need, please do read on:

However, in this last case, it's far safer, faster, more maintainable and just better to do this:

if (str.charAt(0) === '"' && str.charAt(str.length -1) === '"')
{
    console.log(str.substr(1,str.length -2));
}

Here, I'm checking if the first and last char in the string are double quotes. If they are, I'm using substr to cut off those first and last chars. Strings are zero-indexed, so the last char is the charAt(str.length -1). substr expects 2 arguments, where the first is the offset from which the substring starts, the second is its length. Since we don't want the last char, anymore than we want the first, that length is str.length - 2. Easy-peazy.

Tips:

More on lookaround assertions can be found here
Regex's are very useful (and IMO fun), can be a bit baffeling at first. Here's some more details, and links to resources on the matter.
If you're not very comfortable using regex's just yet, you might want to consider using:

var noQuotes = someStr.split('"').join('');

If there's a lot of quotes in the string, this might even be faster than using regex

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

Fundamental difference between Hashing and Encryption algorithms

Use hashes when you don't want to be able to get back the original input, use encryption when you do.

Hashes take some input and turn it into some bits (usually thought of as a number, like a 32 bit integer, 64 bit integer, etc). The same input will always produce the same hash, but you PRINCIPALLY lose information in the process so you can't reliably reproduce the original input (there are a few caveats to that however).

Encryption principally preserves all of the information you put into the encryption function, just makes it hard (ideally impossible) for anyone to reverse back to the original input without possessing a specific key.

Simple Example of Hashing

Here's a trivial example to help you understand why hashing can't (in the general case) get back the original input. Say I'm creating a 1-bit hash. My hash function takes a bit string as input and sets the hash to 1 if there are an even number of bits set in the input string, else 0 if there were an odd number.

Example:

Input    Hash
0010     0
0011     1
0110     1
1000     0

Note that there are many input values that result in a hash of 0, and many that result in a hash of 1. If you know the hash is 0, you can't know for sure what the original input was.

By the way, this 1-bit hash isn't exactly contrived... have a look at parity bit.

Simple Example of Encryption

You might encrypt text by using a simple letter substitution, say if the input is A, you write B. If the input is B, you write C. All the way to the end of the alphabet, where if the input is Z, you write A again.

Input   Encrypted
CAT     DBU
ZOO     APP

Just like the simple hash example, this type of encryption has been used historically.

Python code to remove HTML tags from a string

Python has several XML modules built in. The simplest one for the case that you already have a string with the full HTML is xml.etree, which works (somewhat) similarly to the lxml example you mention:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

Converting XML to JSON using Python?

jsonpickle or if you're using feedparser, you can try feed_parser_to_json.py

How to abort makefile if variable not set?

Use the shell function test:

foo:
    test $(something)

Usage:

$ make foo
test 
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

Rolling back local and remote git repository by 1 commit

There are many way you can do this. Based on your requirement choose anything from below.

1. By REVERTing commit:

If you want to REVERT all the changes from you last COMMIT that means If you ADD something in your file that will be REMOVED after revert has been done. If you REMOVE something in your file the revert process will ADD those file.

You can REVERT the very last COMMIT. Like:

1.git revert head^
2.git push origin <Branch-Name>

Or you can revert to any previous commit using the hash of that commit.Like:

1.git revert <SHA>
2.git push origin  <Branch-Name>

2. By RESETing previous Head

If you want to just point to any previous commit use reset; it points your local environment back to a previous commit. You can reset your head to previous commit or reset your head to previous any commit.

Reset to previous commit.

1.git reset head^
2.git push -f origin <Branch-name>

Reset to any previous commit:

1.git reset <SHA>
2.git push -f origin <Branch-name>

Trade of between REVERT & RESET:

Why would you choose to do a revert over a reset operation? If you have already pushed your chain of commits to the remote repository (where others may have pulled your code and started working with it), a revert is a nicer way to cancel out changes for them. This is because the Git workflow works well for picking up additional commits at the end of a branch, but it can be challenging if a set of commits is no longer seen in the chain when someone resets the branch pointer back.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

Tools to get a pictorial function call graph of code

Understand does a very good job of creating call graphs.

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

How to compare a local git branch with its remote branch?

Setup

git config alias.udiff 'diff @{u}'

Diffing HEAD with HEAD@{upstream}

git fetch  # Do this if you want to compare with the network state of upstream; if the current local state is enough, you can skip this
git udiff

Diffing with an Arbitrary Remote Branch

This answers the question in your heading ("its remote"); if you want to diff against "a remote" (that isn't configured as the upstream for the branch), you need to target it directly. You can see all remote branches with the following:

git branch -r

You can see all configured remotes with the following:

git remote show

You can see the branch/tracking configuration for a single remote (e.g. origin) as follows:

git remote show origin

Once you determine the appropriate origin branch, just do a normal diff :)

git diff [MY_LOCAL] MY_REMOTE_BRANCH

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

If you are interested in reading all sheets and merging them together. The best and fastest way to do it

sheet_to_df_map = pd.read_excel('path_to_file.xls', sheet_name=None)
mdf = pd.concat(sheet_to_df_map, axis=0, ignore_index=True)

This will convert all the sheet into a single data frame m_df

Error in Eclipse: "The project cannot be built until build path errors are resolved"

In my case, all libraries in the build path were OK.

To solve it, I deleted all project metadata (.project, .classpath, .settings) and re-imported the project as a Maven project.

Is it possible to change the location of packages for NuGet?

In order to change the path for projects using PackageReference instead of packages.config you need to use globalPackagesFolder

From https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file

globalPackagesFolder (projects using PackageReference only)

The location of the default global packages folder. The default is %userprofile%.nuget\packages (Windows) or ~/.nuget/packages (Mac/Linux). A relative path can be used in project-specific nuget.config files. This setting is overridden by the NUGET_PACKAGES environment variable, which takes precedence.

repositoryPath (packages.config only)

The location in which to install NuGet packages instead of the default $(Solutiondir)/packages folder. A relative path can be used in project-specific nuget.config files. This setting is overridden by the NUGET_PACKAGES environment variable, which takes precedence.

<config>
    <add key="globalPackagesFolder" value="c:\packageReferences" />
    <add key="repositoryPath" value="c:\packagesConfig" />
</config>

I put Nuget.config next to my solution file and it worked.

How to set user environment variables in Windows Server 2008 R2 as a normal user?

I created a godmode folder on the desktop. just create a new folder on the desktop and call it GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} it will name the folder as godmode and populate the content with various config options, you can then just type in ENVIRO in the search to find the relevant config option, open it and it opens sysdm.cpl in the advanced tab, you can change the environment variables from there.

apache redirect from non www to www

If you are using Apache 2.4 ,without the need to enable the rewrite apache module you can use something like this:

# non-www to www
<If "%{HTTP_HOST} = 'domain.com'">
  Redirect 301 "/" "http://www.domain.com/"
</If>

SQL How to Select the most recent date item

With SQL Server try:

SELECT TOP 1 * FROM dbo.youTable WHERE user_id = 'userid' ORDER BY date_added desc

Python recursive folder read

If you are using Python 3.5 or above, you can get this done in 1 line.

import glob

# root_dir needs a trailing slash (i.e. /root/dir/)
for filename in glob.iglob(root_dir + '**/*.txt', recursive=True):
     print(filename)

As mentioned in the documentation

If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories.

If you want every file, you can use

import glob

for filename in glob.iglob(root_dir + '**/**', recursive=True):
     print(filename)

How to Delete Session Cookie?

you can do this by setting the date of expiry to yesterday.

My new set of posts about cookies in JavaScript could help you.

http://www.markusnordhaus.de/2012/01/20/using-cookies-in-javascript-part-1/

PHP replacing special characters like à->a, è->e

CodeIgniter way:

$this->load->helper('text');

$string = convert_accented_characters($string);

This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

<DIV> inside link (<a href="">) tag

Nesting of 'a' will not be possible. However if you badly want to keep the structure and still make it work like the way you want, then override the anchor tag click in javascript /jquery .

so you can have 2 event listeners for the two and control them accordingly.

How do I use an image as a submit button?

Just remove the border and add a background image in css

Example:

_x000D_
_x000D_
$("#form").on('submit', function() {_x000D_
   alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
  background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
  background-size: cover;_x000D_
  border: none;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  cursor: pointer;_x000D_
  color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to refresh token with Google API client?

The answer posted by @uri-weg worked for me but as I did not find his explanations very clear, let me reword it a little.

During the first access permission sequence, in the callback, when you get to the point where you receive an authentication code, you must save the access token and the refresh token as well.

The reason is google api sends you an access token with a refresh token only when prompting for access permission. The next access tokens will be sent without any refresh token (unless you use the approval_prompt=force option).

The refresh token you received the first time stays valid until the user revokes access permission.

In simplistic php, an example of the callback sequence would be:

// init client
// ...

$authCode = $_GET['code'];
$accessToken = $client->authenticate($authCode);
// $accessToken needs to be serialized as json
$this->saveAccessToken(json_encode($accessToken));
$this->saveRefreshToken($accessToken['refresh_token']);

And later on, in simplistic php, the connection sequence would be:

// init client
// ...

$accessToken = $this->loadAccessToken();
// setAccessToken() expects json
$client->setAccessToken($accessToken);

if ($client->isAccessTokenExpired()) {
    // reuse the same refresh token
    $client->refreshToken($this->loadRefreshToken());
    // save the new access token (which comes without any refresh token)
    $this->saveAccessToken($client->getAccessToken());
}

How to implement infinity in Java?

double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

prints

Infinity
NaN
-Infinity

note: Infinity - Infinity is Not A Number.

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Disabling browser print options (headers, footers, margins) from page?

Since you mentioned "within their browser" and firefox, if you are using Internet Explorer, you can disable the page header/footer by temporarily setting of the value in the registry, see here for an example. AFAIK I have not heard of a way to do this within other browsers. Both Daniel's and Mickel's answers seems to collide with each other, I guess that there could be a similar setting somewhere in the registry for firefox to remove headers/footers or customize them. Have you checked it out?

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

How to set Google Chrome in WebDriver

I'm using this since the begin and it always work. =)

System.setProperty("webdriver.chrome.driver", "C:\\pathto\\my\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");

Relational Database Design Patterns?

There's a book in Martin Fowler's Signature Series called Refactoring Databases. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.

I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.

Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns.

Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model

Is it possible to get a history of queries made in postgres

Not logging but if you're troubleshooting slow running queries in realtime, you can query the pg_stat_activity view to see which queries are active, the user/connection they came from, when they started, etc. Eg...

SELECT *
FROM pg_stat_activity
WHERE state = 'active'

See the pg_stat_activity view docs.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

Difference between File.separator and slash in paths

"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:

c:\Program Files\Java\jdk1.6.0_11\demo/jfc

will parse just fine. Take note of the last (Unix-style) separator.

It's tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.

I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Cocoa: What's the difference between the frame and the bounds?

Frame its relative to its SuperView whereas Bounds relative to its NSView.

Example:X=40,Y=60.Also contains 3 Views.This Diagram shows you clear idea.

FRAME

BOUNDS

Failed to resolve: com.android.support:appcompat-v7:28.0

some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy i used this free proxy for android studio 3.2 https://github.com/freedomofdevelopers/fod just to to Settings (Ctrl + Alt + S) and search HTTP proxy then check Manual proxy configuration then add fodev.org for host name and 8118 for Port number

Screenshot of proxy settings in android studio

Tab space instead of multiple non-breaking spaces ("nbsp")?

If you needed only one tab, the following worked for me.

<style>
  .tab {
    position: absolute;
    left: 10em;
   }
</style>

with the HTML something like:

<p><b>asdf</b> <span class="tab">99967</span></p>
<p><b>hjkl</b> <span class="tab">88868</span></p> 

You can add more "tabs" by adding additional "tab" styles and changing the HTML such as:

<style>
  .tab {
    position: absolute;
    left: 10em;
   }
  .tab1 {
    position: absolute;
    left: 20em;
   }
</style>

with the HTML something like:

<p><b>asdf</b> <span class="tab">99967</span><span class="tab1">hear</span></p>
<p><b>hjkl</b> <span class="tab">88868</span><span class="tab1">here</span></p>

Integer.toString(int i) vs String.valueOf(int i)

The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.

NB Profiling results

Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)

public class StringIntTest {


    public static long intToString () {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = Integer.toString(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static long stringValueOf () {

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = String.valueOf(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static void main(String[] args) {
        long intToStringElapsed = 0;
        long stringValueOfElapsed = 0;
        for (int i = 0; i < 10; i++) {
            intToStringElapsed += intToString();
            stringValueOfElapsed+= stringValueOf();
        }
        System.out.println("Average intToString = "+ (intToStringElapsed /10));
        System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
    }
}

Column/Vertical selection with Keyboard in SublimeText 3

Alright, here's the best solution I've found that meets all the requirements:

  1. Download the Sublime-Text-Advanced-CSV Sublime plugin and install.
  2. Specify a delimiter for your column (default is ","), via the "CSV: Set Delimiter" command.
  3. Hit "ctrl + , s" (or select from Command Palette) and your column will be selected.

No need for mouse interaction whatsoever.

Cannot access wamp server on local network

Turn off your firewall for port 80 from any address. Turn off 443 if you need https (SSL) access. Open the configuration file (http.conf) and find the lines that say:

Allow from 127.0.0.1

Change them to read

Allow from all

Restart the wampserver. It will now work. Enjoy!!

How can I jump to class/method definition in Atom text editor?

The functionality is already present in atom via the Symbols View package you don't need to install anything.

The command you are searching for is symbols-view:go-to-declaration (Jump to the symbol under the cursor) which is bound by default to cmd-alt-down on macOS and ctrl-alt-down on Linux.

just note that it will work only if you will have generated tags for your project, either via this package or via ctags (exuberant or not)

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

Disable submit button when form invalid with AngularJS

If you are using Reactive Forms you can use this:

<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});