Programs & Examples On #Realbasic

REALbasic is an object-oriented version of the BASIC language intended for cross-platform development.

C# switch on type

See gjvdkamp's answer below; this feature now exists in C#


I usually use a dictionary of types and delegates.
var @switch = new Dictionary<Type, Action> {
    { typeof(Type1), () => ... },
    { typeof(Type2), () => ... },
    { typeof(Type3), () => ... },
};

@switch[typeof(MyType)]();

It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.

Disable output buffering

The following works in Python 2.6, 2.7, and 3.2:

import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
    os.environ['PYTHONUNBUFFERED'] = '1'
    buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

How can I obfuscate (protect) JavaScript?

A non-open-source Javascript-based application is fairly silly. Javascript is a client-side interpreted language.. Obfuscation isn't much protection..

JS obfuscation is usually done to reduce the size of the script, rather than "protect" it. If you are in a situation where you don't want your code to be public, Javascript isn't the right language..

There are plenty of tools around, but most have the word "compressor" (or "minifier") in its name for a reason..

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Critical t values in R

Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:

critical.t <- function(){
    cat("\n","\bEnter Alpha Level","\n")
    alpha<-scan(n=1,what = double(0),quiet=T)
    cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
    tt <- scan(n=1,what = double(0),quiet=T)
    cat("\n","\bEnter Number of Observations","\n")
    n <- scan(n=1,what = double(0),quiet=T)
    cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}

critical.t()

How can I build for release/distribution on the Xcode 4?

XCode>Product>Schemes>Edit Schemes>Run>Build Configuration

Where does git config --global get written to?

When is the global .gitconfig file created?

First off, git doesn't automatically create the global config file (.gitconfig) during its installation. The file is not created until it is written to for the first time. If you have never set a system variable, it will not be on your file system. I'm guessing that might be the source of the problem.

One way to ask Git to create it is to request an edit. Doing so will force the file's creation.

git config --global --edit

If you monitor the user's home folder when you issue this command, you will see the .gitconfig file magically appear.

Where is git configuration stored?

Here's a quick rundown of the the name and location of the configuration files associated with the three Git scopes, namely system, global and local:

  • System Git configuration: File named gitconfig located in -git-install-location-/ming<32>/etc
  • Global Git configuraiton: File named .gitconfig located in the user's home folder (C:\Users\git user)
  • Local Git configuration: File named config in the .git folder of the local repo

Of course, seeing is believing, so here's an image showing each file and each location. I pulled the image from an article I wrote on the topic.

Windows Git configuration file locations (TheServerSide.com)

Location of Git configuration files

App can't be opened because it is from an unidentified developer

I had got the same error. Because of security reasons, I could not see option for allowing Apps downloaded from Anywhere in System preference-> Security Tab.

I removed the extended attribute from Zip file by below command.

xattr -d com.apple.quarantine [Zip file path] 

And then got below error:- org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: javax/annotation/PostConstruct

Resolved it by uninstalling all different versions of java and installed just 1.8.0_231.

Worked finally.

How to show SVG file on React Native?

import React from 'react'
import SvgUri from 'react-native-svg-uri';

export default function Splash() {
  return (
    <View style={styles.container}>
      {/* provided the svg file is stored locally */}
      <SvgUri
        width="400"
        height="200"
        source={require('./logo.svg')}
      />
      {/* if the svg is online */}
      <SvgUri
        width="200"
        height="200"
        source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
      />

      <Text style={styles.logoText}>
        Text
      </Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  logoText: {
    fontSize: 50
  }
});

window.print() not working in IE

function printDiv() {
    var divToPrint = document.getElementById('printArea');
    newWin= window.open();
    newWin.document.write(divToPrint.innerHTML);
    newWin.location.reload();
    newWin.focus();
    newWin.print();
    newWin.close();
}

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

The best and perfect solution for this issue:

I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!

Click here to see the full solution

var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);

How to remove focus border (outline) around text/input boxes? (Chrome)

This border is used to show that the element is focused (i.e. you can type in the input or press the button with Enter). You can remove it with outline property, though:

textarea:focus, input:focus{
    outline: none;
}

You may want to add some other way for users to know what element has keyboard focus though for usability.

Chrome will also apply highlighting to other elements such as DIV's used as modals. To prevent the highlight on those and all other elements as well, you can do:

*:focus {
    outline: none;
}


?? Accessibility warning

Please notice that removing outline from input is an accessibility bad practice. Users using screen readers will not be able to see where their pointer is focused at. More info at a11yproject

Django set field value after a form is initialized

If you've already initialized the form, you can use the initial property of the field. For example,

form = CustomForm()
form.fields["Email"].initial = GetEmailString()

error C2065: 'cout' : undeclared identifier

In Visual studio use all your header filer below "stdafx.h".

How to check if one of the following items is in a list?

Simple.

_new_list = []
for item in a:
    if item in b:
        _new_list.append(item)
    else:
        pass

Android 8: Cleartext HTTP traffic not permitted

Just add android:usesCleartextTraffic="true" inside the in AndroidManifest.xml file

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

First you need to set the android:imeOptions attribute equal to actionDone for your target EditText as seen below. That will change your ‘RETURN’ button in your EditText’s soft keyboard to a ‘DONE’ button.

<EditText 
    android:id="@+id/edittext_done"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter some text"
    android:imeOptions="actionDone"
    android:singleLine="true"
    />

HTML code for INR

Use this for Indian rupee sign:

&#2352; — र

Import SQL file into mysql

For localhost on XAMPP. Open a cmd window and type

cd C:\xampp\mysql\bin
mysql.exe -u root -p

Attention! No semi-colon after -p Enter your password and type

use database_name;

to select the database you need.

Check if your table is there

show tables;

Import from your sql file

source sqlfile.sql;

I have put my file on C:\xampp\mysql\bin location in order to don't mix up with locations of sql file.

Android - Pulling SQlite database android device

Based on the answer given by Lam Vinh, here is a simple batch file that works for me on my 1st gen Nexus 7. It prompts the user to enter the package name and then the database name (without the .sqlite extension) and puts it in c:\temp. This assumes you have the Android sdk set in the environment variables.

@echo off
cd c:\temp\

set /p UserInputPackage= Enter the package name: 
set /p UserInputDB= Enter the database name: 

@echo on
adb shell "run-as %UserInputPackage% chmod 666 /data/data/%UserInputPackage%/databases/%UserInputDB%.sqlite"
adb pull /data/data/%UserInputPackage%/databases/%UserInputDB%.sqlite
@echo off
pause

Which maven dependencies to include for spring 3.0?

You can add spring-context dependency for spring jars. You will get the following jars along with it.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

Spring context dependencies

if you also want web components, you can use spring-webmvc dependency.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

Spring webmvc dependencies

You can use whatever version of that you want. I have used 5.0.5.RELEASE here.

Get first day of week in SQL Server

Googled this script:

create function dbo.F_START_OF_WEEK
(
    @DATE           datetime,
    -- Sun = 1, Mon = 2, Tue = 3, Wed = 4
    -- Thu = 5, Fri = 6, Sat = 7
    -- Default to Sunday
    @WEEK_START_DAY     int = 1 
)
/*
Find the fisrt date on or before @DATE that matches 
day of week of @WEEK_START_DAY.
*/
returns     datetime
as
begin
declare  @START_OF_WEEK_DATE    datetime
declare  @FIRST_BOW     datetime

-- Check for valid day of week
if @WEEK_START_DAY between 1 and 7
    begin
    -- Find first day on or after 1753/1/1 (-53690)
    -- matching day of week of @WEEK_START_DAY
    -- 1753/1/1 is earliest possible SQL Server date.
    select @FIRST_BOW = convert(datetime,-53690+((@WEEK_START_DAY+5)%7))
    -- Verify beginning of week not before 1753/1/1
    if @DATE >= @FIRST_BOW
        begin
        select @START_OF_WEEK_DATE = 
        dateadd(dd,(datediff(dd,@FIRST_BOW,@DATE)/7)*7,@FIRST_BOW)
        end
    end

return @START_OF_WEEK_DATE

end
go

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47307

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How to capture the browser window close event?

My answer is aimed at providing simple benchmarks.

HOW TO

See @SLaks answer.

$(window).on("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
})

How long does the browser take to finally shut your page down?

Whenever an user closes the page (x button or CTRL + W), the browser executes the given beforeunload code, but not indefinitely. The only exception is the confirmation box (return 'Do you really want to close?) which will wait until for the user's response.

Chrome: 2 seconds.
Firefox: 8 (or double click, or force on close)
Edge: 8 (or double click)
Explorer 11: 0 seconds.
Safari: TODO

What we used to test this out:

  • A Node.js Express server with requests log
  • The following short HTML file

What it does is to send as many requests as it can before the browser shut downs its page (synchronously).

<html>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
    function request() {
        return $.ajax({
            type: "GET",
            url: "http://localhost:3030/" + Date.now(),
            async: true
        }).responseText;
    }
    window.onbeforeunload = () => {
        while (true) {
            request();
        }
        return null;
    }
    </script>
</body>
</html>

Chrome output:

GET /1480451321041 404 0.389 ms - 32  
GET /1480451321052 404 0.219 ms - 32  
...  
GET /hello/1480451322998 404 0.328 ms - 32

1957ms ˜ 2 seconds // we assume it's 2 seconds since requests can take few milliseconds to be sent.

Find most frequent value in SQL column

Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.

Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;

Method call if not null in C#

This article by Ian Griffiths gives two different solutions to the problem that he concludes are neat tricks that you should not use.

What's the best way to trim std::string?

This version trims internal whitespace and non-alphanumerics:

static inline std::string &trimAll(std::string &s)
{   
    if(s.size() == 0)
    {
        return s;
    }

    int val = 0;
    for (int cur = 0; cur < s.size(); cur++)
    {
        if(s[cur] != ' ' && std::isalnum(s[cur]))
        {
            s[val] = s[cur];
            val++;
        }
    }
    s.resize(val);
    return s;
}

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I agree with some of the others' answers. The <head> and <header> tags have two unique and very unrelated functions. The <header> tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body> tag. The <head> tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:

<!DOCTYPE html/>
<html lang="es">
    <head>
        <!--crazy meta stuff here-->
    </head>
    <body>
        <header>
            <!--Optional nav tag-->
            <nav>
            </nav>
        </header>
        <!--Body content-->
    </body>
</html>

How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

Search all tables, all columns for a specific value SQL Server

You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:

select 'select * from '+name from sys.tables

will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:

select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables

You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.

Uncaught TypeError: Cannot read property 'split' of undefined

Your question answers itself ;) If og_date contains the date, it's probably a string, so og_date.value is undefined.

Simply use og_date.split('-') instead of og_date.value.split('-')

How to prevent a click on a '#' link from jumping to top of page?

If you want to use a anchor you can use http://api.jquery.com/event.preventDefault/ like the other answers suggested.

You can also use any other element like a span and attach the click event to that.

$("span.clickable").click(function(){
alert('Yeah I was clicked');
});

SQL: Combine Select count(*) from multiple tables

select sum(counts) from (
select count(1) as counts from foo 
union all
select count(1) as counts from bar)

How to find length of a string array?

In Java, we declare a String of arrays (eg. car) as

String []car;
String car[];

We create the array using new operator and by specifying its type:-

String []car=new String[];
String car[]=new String[];

This assigns a reference, to an array of Strings, to car. You can also create the array by initializing it:-

String []car={"Sedan","SUV","Hatchback","Convertible"};

Since you haven't initialized an array and you're trying to access it, a NullPointerException is thrown.

Android Facebook style slide

Android added the navigation drawer. Refer this

link

How to find first element of array matching a boolean condition in JavaScript?

foundElement = myArray[myArray.findIndex(element => //condition here)];

Is there a vr (vertical rule) in html?

You can use css for simulate a vertical line, and use the class on the div

.vhLine {
  border-left: thick solid #000000;
}

Best way to store data locally in .NET (C#)

A lot of the answers in this thread attempt to overengineer the solution. If I'm correct, you just want to store user settings.

Use an .ini file or App.Config file for this.

If I'm wrong, and you are storing data that is more than just settings, use a flat text file in csv format. These are fast and easy without the overhead of XML. Folks like to poo poo these since they aren't as elegant, don't scale nicely and don't look as good on a resume, but it might be the best solution for you depending on what you need.

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

How to convert a set to a list in python?

Python is a dynamically typed language, which means that you cannot define the type of the variable as you do in C or C++:

type variable = value

or

type variable(value)

In Python, you use coercing if you change types, or the init functions (constructors) of the types to declare a variable of a type:

my_set = set([1,2,3])
type my_set

will give you <type 'set'> for an answer.

If you have a list, do this:

my_list = [1,2,3]
my_set = set(my_list)

Can someone explain how to implement the jQuery File Upload plugin?

I struggled with this plugin for a while on Rails, and then someone gemified it obsoleting all the code I had created.

Although it looks like you're not using this in Rails, however if anyone is using it checkout this gem. The source is here --> jQueryFileUpload Rails.

Update:

In order to satisfy the commenter I've updated my answer. Essentially "use this gem, here is the source code" If it disappears then do it the long way.

Error:Cause: unable to find valid certification path to requested target

I just encountered the similar problem and found a series of steps did help me. Of course few of them is to Change the network to a stronger,better one.or if you have only one network then try Reconnecting to the network and then simply INVALIDATE/RESTART your android studio. If it still shows the error you need to add the "maven" in repositories and point it out to the link as shown below: maven { url "http://jcenter.bintray.com"}

Finally,Go to *File *Settings *Build,Execution and deployment *Gradle *Android Studio --------And check Enable maven repository option.

After that simply clean and rebuild your APP and you will be good to go.

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

Git: How configure KDiff3 as merge tool and diff tool

For Mac users

Here is @Joseph's accepted answer, but with the default Mac install path location of kdiff3

(Note that you can copy and paste this and run it in one go)

git config --global --add merge.tool kdiff3 
git config --global --add mergetool.kdiff3.path  "/Applications/kdiff3.app/Contents/MacOS/kdiff3" 
git config --global --add mergetool.kdiff3.trustExitCode false

git config --global --add diff.guitool kdiff3
git config --global --add difftool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add difftool.kdiff3.trustExitCode false

__init__() missing 1 required positional argument

You're receiving this error because you did not pass a data variable to the DHT constructor.

aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data in the class constructor like this:

class DHT:
   def __init__(self, data=None):
      if data is None:
         data = {}
      else:
         self.data = data
      self.data['one'] = '1'
      self.data['two'] = '2'
      self.data['three'] = '3'
   def showData(self):
      print(self.data)

And then calling the method showData like this:

DHT().showData()

Or like this:

DHT({'six':6,'seven':'7'}).showData()

or like this:

# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()

What is the Angular equivalent to an AngularJS $watch?

This does not answer the question directly, but I have on different occasions landed on this Stack Overflow question in order to solve something I would use $watch for in angularJs. I ended up using another approach than described in the current answers, and want to share it in case someone finds it useful.

The technique I use to achieve something similar $watch is to use a BehaviorSubject (more on the topic here) in an Angular service, and let my components subscribe to it in order to get (watch) the changes. This is similar to a $watch in angularJs, but require some more setup and understanding.

In my component:

export class HelloComponent {
  name: string;
  // inject our service, which holds the object we want to watch.
  constructor(private helloService: HelloService){
    // Here I am "watching" for changes by subscribing
    this.helloService.getGreeting().subscribe( greeting => {
      this.name = greeting.value;
    });
  }
}

In my service

export class HelloService {
  private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
  constructor(){}
  // similar to using $watch, in order to get updates of our object 
  getGreeting(): Observable<{value:string}> {
    return this.helloSubject;
  }
  // Each time this method is called, each subscriber will receive the updated greeting.
  setGreeting(greeting: string) {
    this.helloSubject.next({value: greeting});
  }
}

Here is a demo on Stackblitz

scp via java

Take a look here

That is the source code for Ants' SCP task. The code in the "execute" method is where the nuts and bolts of it are. This should give you a fair idea of what is required. It uses JSch i believe.

Alternatively you could also directly execute this Ant task from your java code.

How to terminate a thread when main program ends?

Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.

E.g. for Python 3:

while threading.main_thread().isAlive():
    do.you.subthread.thing()
gracefully.close.the.thread()

See Check if the Main Thread is still alive from another thread.

How to iterate a loop with index and element in Swift

Swift 5.x:

I personally prefer using the forEach method:

list.enumerated().forEach { (index, element) in
    ...
}

You can also use the short version:

list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }

How to print an exception in Python?

One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.

assert type(A) is type(""), "requires a string"

What is the quickest way to HTTP GET in Python?

It's simple enough with the powerful urllib3 library.

Import it like this:

import urllib3

http = urllib3.PoolManager()

And make a request like this:

response = http.request('GET', 'https://example.com')

print(response.data) # Raw data.
print(response.data.decode('utf-8')) # Text.
print(response.status) # Status code.
print(response.headers['Content-Type']) # Content type.

You can add headers too:

response = http.request('GET', 'https://example.com', headers={
    'key1': 'value1',
    'key2': 'value2'
})

More info can be found on the urllib3 documentation.

urllib3 is much safer and easier to use than the builtin urllib.request or http modules and is stable.

Checkbox value true/false

jQuery.is() function does not have a signature for .is('selector', function).

I guess you want to do something like this:

      if($("#checkbox1").is(':checked')){
          $("#checkbox1").attr('value', 'true');
      }

How do I get the value of a textbox using jQuery?

Possible Duplicate:

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

 var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

 var txt=$('input:text[name=DrugDurationLength]').val();

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked

ORA-28000: the account is locked error getting frequently

One of the reasons of your problem could be the password policy you are using.

And if there is no such policy of yours then check your settings for the password properties in the DEFAULT profile with the following query:

SELECT resource_name, limit
FROM dba_profiles 
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';

And If required, you just need to change the PASSWORD_LIFE_TIME to unlimited with the following query:

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

And this Link might be helpful for your problem.

Passing by reference in C

What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)

The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)

#include <stdio.h>

void f(int &j) {    //j is reference variable to i same as int &j = i
  j++;
}

int main() {
  int i = 20;
  f(i);
  printf("i = %d\n", i);

  return 0;
}

Output:-

3:12: error: expected ';', ',' or ')' before '&' token
             void f(int &j);
                        ^
9:3:  warning: implicit declaration of function 'f'
               f(a);
               ^

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

C compile : collect2: error: ld returned 1 exit status

This issue appears when you have a running console at the time you try to run other (or the same) program.

I had this problem during executing a program on Sublime Text while I had another one running on DevC++ already.

Selecting empty text input using jQuery

I'd recommend:

$('input:text:not([value])')

Why do we use arrays instead of other data structures?

For O(1) random access, which can not be beaten.

How to increase memory limit for PHP over 2GB?

Input the following to your Apache configuration:

php_value memory_limit 2048M

CORS Access-Control-Allow-Headers wildcard being ignored?

here's the incantation for nginx, inside a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

prevent property from being serialized in web API

Almost same as greatbear302's answer, but i create ContractResolver per request.

1) Create a custom ContractResolver

public class MyJsonContractResolver : DefaultContractResolver
{
    public List<Tuple<string, string>> ExcludeProperties { get; set; }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (ExcludeProperties?.FirstOrDefault(
            s => s.Item2 == member.Name && s.Item1 == member.DeclaringType.Name) != null)
        {
            property.ShouldSerialize = instance => { return false; };
        }

        return property;
    }
}

2) Use custom contract resolver in action

public async Task<IActionResult> Sites()
{
    var items = await db.Sites.GetManyAsync();

    return Json(items.ToList(), new JsonSerializerSettings
    {
        ContractResolver = new MyJsonContractResolver()
        {
            ExcludeProperties = new List<Tuple<string, string>>
            {
                Tuple.Create("Site", "Name"),
                Tuple.Create("<TypeName>", "<MemberName>"),
            }
        }
    });
}

Edit:

It didn't work as expected(isolate resolver per request). I'll use anonymous objects.

public async Task<IActionResult> Sites()
{
    var items = await db.Sites.GetManyAsync();

    return Json(items.Select(s => new
    {
        s.ID,
        s.DisplayName,
        s.Url,
        UrlAlias = s.Url,
        NestedItems = s.NestedItems.Select(ni => new
        {
            ni.Name,
            ni.OrdeIndex,
            ni.Enabled,
        }),
    }));
}

How to change font of UIButton with Swift

If you're having font size issues (your font isn't responding to size changes)...

@codester has the right code:

myButton.titleLabel!.font =  UIFont(name: YourfontName, size: 20)

However, my font size wasn't changing. It turns out that I asking for a font that didn't exist ("HelveticaNeue-Regular"). It wasn't causing a crash, but seemed to be just ignoring that font statement because of it. Once I changed the font to something that does exist, changes to "size: x" did render.

How do I get the resource id of an image if I know its name?

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

ResourceDictionary in a separate assembly

I'm working with .NET 4.5 and couldn't get this working... I was using WPF Custom Control Library. This worked for me in the end...

<ResourceDictionary Source="/MyAssembly;component/mytheme.xaml" />

source: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/11a42336-8d87-4656-91a3-275413d3cc19

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Is there a function to copy an array in C/C++?

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

So, the C++ solution where the arrays are defined as pointers:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersize with 1:

  1. Copies all elements in the range [first, last) starting from first and proceeding to last - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

How to resolve TypeError: can only concatenate str (not "int") to str

instead of using " + " operator

print( "Alireza" + 1980)

Use comma " , " operator

print( "Alireza" , 1980)

how to display full stored procedure code?

use pgAdmin or use pg_proc to get the source of your stored procedures. pgAdmin does the same.

check if a key exists in a bucket in s3 using boto3

This could check both prefix and key, and fetches at most 1 key.

def prefix_exits(bucket, prefix):
    s3_client = boto3.client('s3')
    res = s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=1)
    return 'Contents' in res

RecyclerView - Get view at particular position

You can as well do this, this will help when you want to modify a view after clicking a recyclerview position item

@Override
public void onClick(View view, int position) {

            View v =  rv_notifications.getChildViewHolder(view).itemView;
            TextView content = v.findViewById(R.id.tv_content);
            content.setText("Helloo");

        }

Displaying the build date

I needed a universal solution that worked with a NETStandard project on any platform (iOS, Android, and Windows.) To accomplish this, I decided to automatically generate a CS file via a PowerShell script. Here is the PowerShell script:

param($outputFile="BuildDate.cs")

$buildDate = Get-Date -date (Get-Date).ToUniversalTime() -Format o
$class = 
"using System;
using System.Globalization;

namespace MyNamespace
{
    public static class BuildDate
    {
        public const string BuildDateString = `"$buildDate`";
        public static readonly DateTime BuildDateUtc = DateTime.Parse(BuildDateString, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
    }
}"

Set-Content -Path $outputFile -Value $class

Save the PowerScript file as GenBuildDate.ps1 and add it your project. Finally, add the following line to your Pre-Build event:

powershell -File $(ProjectDir)GenBuildDate.ps1 -outputFile $(ProjectDir)BuildDate.cs

Make sure BuildDate.cs is included in your project. Works like a champ on any OS!

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

Combine two columns of text in pandas dataframe

This solution uses an intermediate step compressing two columns of the DataFrame to a single column containing a list of the values. This works not only for strings but for all kind of column-dtypes

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
df['list']=df[['Year','quarter']].values.tolist()
df['period']=df['list'].apply(''.join)
print(df)

Result:

   Year quarter        list  period
0  2014      q1  [2014, q1]  2014q1
1  2015      q2  [2015, q2]  2015q2

Eclipse reported "Failed to load JNI shared library"

Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems

This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.

How to compress a String in Java?

Take a look at the Huffman algorithm.

https://codereview.stackexchange.com/questions/44473/huffman-code-implementation

The idea is that each character is replaced with sequence of bits, depending on their frequency in the text (the more frequent, the smaller the sequence).

You can read your entire text and build a table of codes, for example:

Symbol Code

a 0

s 10

e 110

m 111

The algorithm builds a symbol tree based on the text input. The more variety of characters you have, the worst the compression will be.

But depending on your text, it could be effective.

PHP CURL & HTTPS

One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.

  1. Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)

  2. Use this code

".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
  1. Upload the code to live server and test.

How to replace all spaces in a string

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

Remove items from one list in another

Here ya go..

    List<string> list = new List<string>() { "1", "2", "3" };
    List<string> remove = new List<string>() { "2" };

    list.ForEach(s =>
        {
            if (remove.Contains(s))
            {
                list.Remove(s);
            }
        });

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

Parsing JSON Array within JSON Object

line 2 should be

for (int i = 0; i < jsonMainArr.size(); i++) {  // **line 2**

For line 3, I'm having to do

    JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());

Graphviz's executables are not found (Python 3.4)

If you are on Win10, install Graphviz and then use following command to add the path.

import os
os.environ["PATH"] += os.pathsep + 'C:\Program Files (x86)\Graphviz2.38/bin/'

What's the bad magic number error?

I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem

How do I format axis number format to thousands with a comma in matplotlib?

Short answer without importing matplotlib as mpl

plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))

Modified from @AlexG's answer

In R, how to find the standard error of the mean?

Remembering that the mean can also by obtained using a linear model, regressing the variable against a single intercept, you can use also the lm(x~1) function for this!

Advantages are:

  • You obtain immediately confidence intervals with confint()
  • You can use tests for various hypothesis about the mean, using for example car::linear.hypothesis()
  • You can use more sophisticated estimates of the standard deviation, in case you have some heteroskedasticity, clustered-data, spatial-data etc, see package sandwich
## generate data
x <- rnorm(1000)

## estimate reg
reg <- lm(x~1)
coef(summary(reg))[,"Std. Error"]
#> [1] 0.03237811

## conpare with simple formula
all.equal(sd(x)/sqrt(length(x)),
          coef(summary(reg))[,"Std. Error"])
#> [1] TRUE

## extract confidence interval
confint(reg)
#>                   2.5 %    97.5 %
#> (Intercept) -0.06457031 0.0625035

Created on 2020-10-06 by the reprex package (v0.3.0)

PL/SQL block problem: No data found error

There is an alternative approach I used when I couldn't rely on the EXCEPTION block at the bottom of my procedure. I had variables declared at the beginning:

my_value VARCHAR := 'default';
number_rows NUMBER := 0;
.
.
.
SELECT count(*) FROM TABLE INTO number_rows (etc.)

IF number_rows > 0 -- Then obtain my_value with a query or constant, etc.
END IF;

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

New functionality in the framework and support libs allow exactly this. There are three 'pieces of the puzzle':

  1. Using Toolbar so that you can embed your action bar into your view hierarchy.
  2. Making DrawerLayout fitsSystemWindows so that it is layed out behind the system bars.
  3. Disabling Theme.Material's normal status bar coloring so that DrawerLayout can draw there instead.

I'll assume that you will use the new appcompat.

First, your layout should look like this:

<!-- The important thing to note here is the added fitSystemWindows -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Your normal content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- We use a Toolbar so that our drawer can be displayed
             in front of the action bar -->
        <android.support.v7.widget.Toolbar  
            android:id="@+id/my_awesome_toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

        <!-- The rest of your content view -->

    </LinearLayout>

    <!-- Your drawer view. This can be any view, LinearLayout
         is just an example. As we have set fitSystemWindows=true
         this will be displayed under the status bar. -->
    <LinearLayout
        android:layout_width="304dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:fitsSystemWindows="true">

        <!-- Your drawer content -->

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

Then in your Activity/Fragment:

public void onCreate(Bundled savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Your normal setup. Blah blah ...

    // As we're using a Toolbar, we should retrieve it and set it
    // to be our ActionBar
    Toolbar toolbar = (...) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);

    // Now retrieve the DrawerLayout so that we can set the status bar color.
    // This only takes effect on Lollipop, or when using translucentStatusBar
    // on KitKat.
    DrawerLayout drawerLayout = (...) findViewById(R.id.my_drawer_layout);
    drawerLayout.setStatusBarBackgroundColor(yourChosenColor);
}

Then you need to make sure that the DrawerLayout is visible behind the status bar. You do that by changing your values-v21 theme:

values-v21/themes.xml

<style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>

Note: If a <fragment android:name="fragments.NavigationDrawerFragment"> is used instead of

<LinearLayout
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true">

    <!-- Your drawer content -->

</LinearLayout>

the actual layout, the desired effect will be achieved if you call fitsSystemWindows(boolean) on a view that you return from onCreateView method.

@Override
public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View mDrawerListView = inflater.inflate(
        R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setFitsSystemWindows(true);
    return mDrawerListView;
}

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

http://docs.python.org/reference/datamodel.html#object.new

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

UIScrollView not scrolling

If you cannot scroll the view even after you set contentSize correctly, make sure you uncheck "Use AutoLayout" in Interface Builder -> File Inspector.

How to create an HTTPS server in Node.js?

If you need it only locally for local development, I've created utility exactly for this task - https://github.com/pie6k/easy-https

import { createHttpsDevServer } from 'easy-https';

async function start() {
  const server = await createHttpsDevServer(
    async (req, res) => {
      res.statusCode = 200;
      res.write('ok');
      res.end();
    },
    {
      domain: 'my-app.dev',
      port: 3000,
      subdomains: ['test'], // will add support for test.my-app.dev
      openBrowser: true,
    },
  );
}

start();

It:

  • Will automatically add proper domain entries to /etc/hosts
  • Will ask you for admin password only if needed on first run / domain change
  • Will prepare https certificates for given domains
  • Will trust those certificates on your local machine
  • Will open the browser on start pointing to your local server https url

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

Capitalize only first character of string and leave others alone? (Rails)

What about classify method on string ?

'somESTRIng'.classify

output:

#rails => 'SomESTRIng'

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

How to leave a message for a github.com user

Although GitHub removed the private messaging feature, there's still an alternative.

GitHub host git repositories. If the user you're willing to communicate with has ever committed some code, there are good chances you may reach your goal. Indeed, within each commit is stored some information about the author of the change or the one who accepted it.

Provided you're really dying to exchange with user user_test

  • Display the public activity page of the user: https://github.com/user_test?tab=activity
  • Search for an event stating "user_test pushed to [branch] at [repository]". There are usually good chances, they may have pushed one of his own commits. Ensure this is the case by clicking on the "View comparison..." link and make sure the user is listed as one of the committers.
  • Clone on your local machine the repository they pushed to: git clone https://github.com/..../repository.git
  • Checkout the branch they pushed to: git checkout [branch]
  • Display the latest commits: git log -50

As a committer/author, an email should be displayed along with the commit data.

Note: Every warning related to unsolicited email should apply there. Do not spam.

Changing API level Android Studio

In Android studio open build.gradle and edit the following section:

defaultConfig {
    applicationId "com.demo.myanswer"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}

here you can change minSdkVersion from 12 to 14

Is there an easy way to reload css without reloading the page?

On the "edit" page, instead of including your CSS in the normal way (with a <link> tag), write it all to a <style> tag. Editing the innerHTML property of that will automatically update the page, even without a round-trip to the server.

<style type="text/css" id="styles">
    p {
        color: #f0f;
    }
</style>

<textarea id="editor"></textarea>
<button id="preview">Preview</button>

The Javascript, using jQuery:

jQuery(function($) {
    var $ed = $('#editor')
      , $style = $('#styles')
      , $button = $('#preview')
    ;
    $ed.val($style.html());
    $button.click(function() {
        $style.html($ed.val());
        return false;
    });
});

And that should be it!

If you wanted to be really fancy, attach the function to the keydown on the textarea, though you could get some unwanted side-effects (the page would be changing constantly as you type)

Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: http://jsbin.com/owapi

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Chromedriver is a WebDriver. WebDriver is an open-source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. When you run this driver, it will enable your scripts to access this and run commands on Google Chrome.

This can be done via scripts running in the local network (Only local connections are allowed.) or via scripts running on outside networks (All remote connections are allowed.). It is always safer to use the Local Connection option. By default your Chromedriver is accessible via port 9515.

To answer the question, it is just an informational message. You don't have to worry about it.

Given below are both options.

$ chromedriver

Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.

This is by whitelisting all IPs.

$ chromedriver --whitelisted-ips=""

Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
All remote connections are allowed. Use a whitelist instead!
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.

Python: avoiding pylint warnings about too many arguments

Python has some nice functional programming tools that are likely to fit your needs well. Check out lambda functions and map. Also, you're using dicts when it seems like you'd be much better served with lists. For the simple example you provided, try this idiom. Note that map would be better and faster but may not fit your needs:

def mysum(d):
   s = 0  
   for x in d:
        s += x
   return s

def mybigfunction():
   d = (x1, x2, x3, x4, x5, x6, x7, x8, x9)
   return mysum(d)

You mentioned having a lot of local variables, but frankly if you're dealing with lists (or tuples), you should use lists and factor out all those local variables in the long run.

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

HTML meta tag for content language

<meta name="language" content="Spanish">

This isn't defined in any specification (including the HTML5 draft)

<meta http-equiv="content-language" content="es">

This is a poor man's version of a real HTTP header and should really be expressed in the headers. For example:

Content-language: es
Content-type: text/html;charset=UTF-8

It says that the document is intended for Spanish language speakers (it doesn't, however mean the document is written in Spanish; it could, for example, be written in English as part of a language course for Spanish speakers).

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

If you want to state that a document is written in Spanish then use:

<html lang="es">

Register DLL file on Windows Server 2008 R2

You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>

How to properly overload the << operator for an ostream?

You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

Import/Index a JSON file into Elasticsearch

As of Elasticsearch 7.7, you have to specify the content type also:

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/_bulk --data-binary @<absolute path to JSON file>

SQL to LINQ Tool

Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).

LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.


Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.

How can I render a list select box (dropdown) with bootstrap?

Skelly's nice and easy answer is now outdated with the changes to the dropdown syntax in Bootstap. Instead use this:

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.form-group').find('button[data-toggle="dropdown"]').html(selText+' <span class="caret"></span>');
});

css 'pointer-events' property alternative for IE

Use OnClientClick = "return false;"

HashSet vs LinkedHashSet

LinkedHashSet's constructors invoke the following base class constructor:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}

As you can see, the internal map is a LinkedHashMap. If you look inside LinkedHashMap, you'll discover the following field:

private transient Entry<K, V> header;

This is the linked list in question.

Convert string to binary then back again using PHP

That's funny how Stefan Gehrig his answer is actually the correct one. You don't need to convert a string into a "011010101" string to store it in BINARY field in a database. Anyway since this is the first answer that comes up when you google for "php convert string to binary string". Here is my contribution to this problem.

The most voted answer by Francois Deschenes goes wrong for long strings (either bytestrings or bitstrings) that is because

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

From: https://secure.php.net/manual/en/function.base-convert.php

To work around this limitation you can chop up the input string into chunks. The functions below implement this technique.

<?php

function bytesToBits(string $bytestring) {
  if ($bytestring === '') return '';

  $bitstring = '';
  foreach (str_split($bytestring, 4) as $chunk) {
    $bitstring .= str_pad(base_convert(unpack('H*', $chunk)[1], 16, 2), strlen($chunk) * 8, '0', STR_PAD_LEFT);
  }

  return $bitstring;
}

function bitsToBytes(string $bitstring) {
  if ($bitstring === '') return '';

  // We want all bits to be right-aligned
  $bitstring_len = strlen($bitstring);
  if ($bitstring_len % 8 > 0) {
    $bitstring = str_pad($bitstring, intdiv($bitstring_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  $bytestring = '';
  foreach (str_split($bitstring, 32) as $chunk) {
    $bytestring .= pack('H*', str_pad(base_convert($chunk, 2, 16), strlen($chunk) / 4, '0', STR_PAD_LEFT));
  }

  return $bytestring;
}

for ($i = 0; $i < 10000; $i++) {
  $bytestring_in = substr(hash('sha512', uniqid('', true)), 0, rand(0, 128));
  $bits = bytesToBits($bytestring_in);
  $bytestring_out = bitsToBytes($bits);
  if ($bytestring_in !== $bytestring_out) {
    printf("IN  : %s\n", $bytestring_in);
    printf("BITS: %s\n", $bits);
    printf("OUT : %s\n", $bytestring_out);
    var_dump($bytestring_in, $bytestring_out); // printf() doesn't show some characters ..
    die('Error in functions [1].');
  }
}


for ($i = 0; $i < 10000; $i++) {
  $len = rand(0, 128);
  $bitstring_in = '';
  for ($j = 0; $j <= $len; $j++) {
    $bitstring_in .= (string) rand(0,1);
  }
  $bytes = bitsToBytes($bitstring_in);
  $bitstring_out = bytesToBits($bytes);

  // since converting to byte we always have a multitude of 4, so we need to correct the bitstring_in to compare ..
  $bitstring_in_old = $bitstring_in;
  $bitstring_in_len = strlen($bitstring_in);
  if ($bitstring_in_len % 8 > 0) {
    $bitstring_in = str_pad($bitstring_in, intdiv($bitstring_in_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  if ($bitstring_in !== $bitstring_out) {
    printf("IN1  : %s\n", $bitstring_in_old);
    printf("IN2  : %s\n", $bitstring_in);
    printf("BYTES: %s\n", $bytes);
    printf("OUT  : %s\n", $bitstring_out);
    var_dump($bytes); // printf() doesn't show some characters ..
    die('Error in functions [2].');
  }
}

echo 'All ok!' . PHP_EOL;

Note that if you insert a bitstring that is not a multitude of 8 (example: "101") you will not be able to recover the original bitstring when you converted to bytestring. From the bytestring converting back, uyou will get "00000101" which is numerically the same (unsigned 8 bit integer) but has a different string length. Therefor if the bitstring length is important to you you should save the length in a separate variable and chop of the first part of the string after converting.

$bits_in = "101";
$bits_in_len = strlen($bits_in); // <-- keep track if input length
$bits_out = bytesToBits(bitsToBytes("101"));
var_dump($bits_in, $bits_out, substr($bits_out, - $bits_in_len)); // recover original length with substr

Why does pycharm propose to change method to static

It might be a bit messy, but sometimes you just don't need to access self, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

If your method only has side effects and you don't care about what it returns:

def bar(self):
    doing_something_without_self()
    return self

If you do need the return value:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

Now your method is using self, and the warning goes away!

Initializing select with AngularJS and ng-repeat

Thanks to TheSharpieOne for pointing out the ng-selected option. If that had been posted as an answer rather than as a comment, I would have made that the correct answer.

Here's a working JSFiddle: http://jsfiddle.net/coverbeck/FxM3B/5/.

I also updated the fiddle to use the title attribute, which I had left out in my original post, since it wasn't the cause of the problem (but it is the reason I want to use ng-repeat instead of ng-options).

HTML:

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

JS:

function AppCtrl($scope) {

    $scope.filterCondition={
        operator: 'eq'
    }

    $scope.operators = [
        {value: 'eq', displayName: 'equals', title: 'The equals operator does blah, blah'},
        {value: 'neq', displayName: 'not equal', title: 'The not equals operator does yada yada'}
     ]
}

How to name Dockerfiles

If you want to use the autobuilder at hub.docker.com, it has to be Dockerfile. So there :)

Unable to show a Git tree in terminal

tig

If you want a interactive tree, you can use tig. It can be installed by brew on OSX and apt-get in Linux.

brew install tig
tig

This is what you get:

enter image description here

Auto-click button element on page load using jQuery

I tried the following ways in first jQuery, then JavaScript:

jQuery:

 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');  

This is the best way in JavaScript:

 document.getElementById("id").click();

create array from mysql query php

You do need to iterate through...

$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);

if ($result) {
    while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

Arduino IDE can't find ESP8266WiFi.h file

Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):

  • Start Arduino, go to File > Preferences
  • Add the following link to the Additional Boards Manager URLs: http://arduino.esp8266.com/stable/package_esp8266com_index.json and press OK button
  • Click Tools > Boards menu > Boards Manager, search for ESP8266 and install ESP8266 platform from ESP8266 community (and don't forget to select your ESP8266 boards from Tools > Boards menu after installation)

To install additional ESP8266WiFi library:

  • Click Sketch > Include Library > Manage Libraries, search for ESP8266WiFi and then install with the latest version.

After above steps, you should compile the sketch normally.

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

Python assigning multiple variables to same value? list behavior

If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a as a "variable", and start thinking of it as a "name".

a, b, and c aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.

Names don't have any of that. Values do, of course, and you can have lots of names for the same value.

If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog. If you change the first element of a to 1, the first elements of b and c are 1.

If you want to know if two names are naming the same object, use the is operator:

>>> a=b=c=[0,3,5]
>>> a is b
True

You then ask:

what is different from this?

d=e=f=3
e=4
print('f:',f)
print('e:',e)

Here, you're rebinding the name e to the value 4. That doesn't affect the names d and f in any way.

In your previous version, you were assigning to a[0], not to a. So, from the point of view of a[0], you're rebinding a[0], but from the point of view of a, you're changing it in-place.

You can use the id function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is can't help:

>>> a=b=c=[0,3,5]
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261120
>>> id(b[0])
4297261120

>>> a[0] = 1
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261216
>>> id(b[0])
4297261216

Notice that a[0] has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0] is also now a name for that same new value. That's because a and b are still naming the same object.


Under the covers, a[0]=1 is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1).) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1). Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1.


user570826 asked:

What if we have, a = b = c = 10

That's exactly the same situation as a = b = c = [1, 2, 3]: you have three names for the same value.

But in this case, the value is an int, and ints are immutable. In either case, you can rebind a to a different value (e.g., a = "Now I'm a string!"), but the won't affect the original value, which b and c will still be names for. The difference is that with a list, you can change the value [1, 2, 3] into [1, 2, 3, 4] by doing, e.g., a.append(4); since that's actually changing the value that b and c are names for, b will now b [1, 2, 3, 4]. There's no way to change the value 10 into anything else. 10 is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).


* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.

Facebook Callback appends '#_=_' to Return URL

A workaround that worked for me (using Backbone.js), was to add "#/" to the end of the redirect URL passed to Facebook. Facebook will keep the provided fragment, and not append its own "_=_".

Upon return, Backbone will remove the "#/" part. For AngularJS, appending "#!" to the return URL should work.

Note that the fragment identifier of the original URL is preserved on redirection (via HTTP status codes 300, 301, 302 and 303) by most browsers, unless the redirect URL also has a fragment identifier. This seems to be recommended behaviour.

If you use a handler script that redirects the user elsewhere, you can append "#" to the redirect URL here to replace the fragment identifier with an empty string.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

I think it's better to timeout at the end of the function.

function main(){
    var something; 
    make=function(walkNr){
         if(walkNr===0){
           // var something for this step      
           // do something
         }
         else if(walkNr===1){
           // var something for that step 
           // do something different
         }

         // ***
         // finally
         else if(walkNr===10){
           return something;
         }
         // show progress if you like
         setTimeout(funkion(){make(walkNr)},15,walkNr++);  
   }
return make(0);
}   

This three functions are necessary because vars in the second function will be overwritten with default value each time. When the program pointer reach the setTimeout one step is already calculated. Then just the screen needs a little time.

Insert default value when parameter is null

The easiest way to do this is to modify the table declaration to be

CREATE TABLE Demo
(
    MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'
)

Now, in your stored procedure you can do something like.

CREATE PROCEDURE InsertDemo
    @MyColumn VARCHAR(10) = null
AS
INSERT INTO Demo (MyColumn) VALUES(@MyColumn)

However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.

Validate Dynamically Added Input fields

In case you have a form you can add a class name as such:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

Amazon S3 - HTTPS/SSL - Is it possible?

As previously stated, it's not directly possible, but you can set up Apache or nginx + SSL on a EC2 instance, CNAME your desired domain to that, and reverse-proxy to the (non-custom domain) S3 URLs.

I can not find my.cnf on my windows computer

Here is my answer:

  1. Win+R (shortcut for 'run'), type services.msc, Enter
  2. You should find an entry like 'MySQL56', right click on it, select properties
  3. You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Full answer here: https://stackoverflow.com/a/20136523/1316649

Android Studio: Default project directory

At some point I too tried to do this, but the Android Studio doesn’t work quite like Eclipse does.

It's simpler: if you create a project at, say /home/USER/Projects/AndroidStudio/MyApplication from there on all new projects will default to /home/USER/Projects/AndroidStudio.

You can also edit ~/.AndroidStudioPreview/config/options/ide.general.xml (in linux) and change the line that reads <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" /> to <option name="lastProjectLocation" value="$USER_HOME$/Projects/AndroidStudio" />, but be aware that as soon as you create a project anywhere else this will change to that place and all new projects will default to it.

Hope this helps, but the truth is there really isn't much more to it other than what I explained here.

Let me know if you need anything else.

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

How do you clear the focus in javascript?

dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

HTML Agility pack - parsing tables

Line from above answer:

HtmlDocument doc = new HtmlDocument();

This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument any more.

Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb and check out this link for some sample code.

How can I delete all Git branches which have been merged?

My Bash script contribution is based loosely on mmrobin's answer.

It takes some useful parameters specifying includes and excludes, or to examine/remove only local or remote branches instead of both.

#!/bin/bash

# exclude branches regex, configure as "(branch1|branch2|etc)$"
excludes_default="(master|next|ag/doc-updates)$"
excludes="__NOTHING__"
includes=
merged="--merged"
local=1
remote=1

while [ $# -gt 0 ]; do
  case "$1" in
  -i) shift; includes="$includes $1" ;;
  -e) shift; excludes="$1" ;;
  --no-local) local=0 ;;
  --no-remote) remote=0 ;;
  --all) merged= ;;
  *) echo "Unknown argument $1"; exit 1 ;;
  esac
  shift   # next option
done

if [ "$includes" == "" ]; then
  includes=".*"
else
  includes="($(echo $includes | sed -e 's/ /|/g'))"
fi

current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
  echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching branches...\n"

git remote update --prune
remote_branches=$(git branch -r $merged | grep -v "/$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
local_branches=$(git branch $merged | grep -v "$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
  echo "No existing branches have been merged into $current_branch."
else
  echo "This will remove the following branches:"
  if [ "$remote" == 1 -a -n "$remote_branches" ]; then
    echo "$remote_branches"
  fi
  if [ "$local" == 1 -a -n "$local_branches" ]; then
    echo "$local_branches"
  fi
  read -p "Continue? (y/n): " -n 1 choice
  echo
  if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
    if [ "$remote" == 1 ]; then
      remotes=$(git remote)
      # Remove remote branches
      for remote in $remotes
      do
        branches=$(echo "$remote_branches" | grep "$remote/" | sed "s/$remote\/\(.*\)/:\1 /g" | tr -d '\n')
        git push $remote $branches
      done
    fi

    if [ "$local" == 1 ]; then
      # Remove local branches
      locals=$(echo "$local_branches" | sed 's/origin\///g' | tr -d '\n')
      if [ -z "$locals" ]; then
        echo "No branches removed."
      else
        git branch -d $(echo "$locals" | tr -d '\n')
      fi
    fi
  fi
fi

SQL Server : Transpose rows to columns

SQL Server has a PIVOT command that might be what you are looking for.

select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;

If the columns are not constant, you'll have to combine this with some dynamic SQL.

DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);

select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);

SELECT @sql =

'SELECT *
FROM TAG
PIVOT 
(
  MAX(Value) 
  FOR TagID IN( ' + @columns + ' )) as TagTime;';

 execute(@sql);

Convert string to float?

String s = "3.14";
float f = Float.parseFloat(s);

Can I append an array to 'formdata' in javascript?

This works for me when I sent file + text + array:

const uploadData = new FormData();
if (isArray(value)) {
  const k = `${key}[]`;
  uploadData.append(k, value);
} else {
  uploadData.append(key, value);
}


const headers = {
  'Content-Type': 'multipart/form-data',
};

What is the difference between __str__ and __repr__?

From the book Fluent Python:

A basic requirement for a Python object is to provide usable string representations of itself, one used for debugging and logging, another for presentation to end users. That is why the
special methods __repr__ and __str__ exist in the data model.

Set up git to pull and push all branches

Including the + in the push spec is probably a bad idea, as it means that git will happily do a non-fast-forward push even without -f, and if the remote server is set up to accept those, you can lose history.

Try just this:

$ git config --add remote.origin.push 'refs/heads/*:refs/heads/*'
$ git config --add remote.origin.push 'refs/tags/*:refs/tags/*'
$ git config --add remote.origin.fetch 'refs/heads/*:refs/remotes/origin/*'
$ git config --add remote.origin.fetch 'refs/tags/*:refs/tags/*'

Selenium Webdriver submit() vs click()

The submit() function is there to make life easier. You can use it on any element inside of form tags to submit that form.

You can also search for the submit button and use click().

So the only difference is click() has to be done on the submit button and submit() can be done on any form element.

It's up to you.

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms

Spring CORS No 'Access-Control-Allow-Origin' header is present

Following on Omar's answer, I created a new class file in my REST API project called WebConfig.java with this configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*");
  }
} 

This allows any origin to access the API and applies it to all controllers in the Spring project.

SQL query: Delete all records from the table except latest N?

Just wanted to throw this into the mix for anyone using Microsoft SQL Server instead of MySQL. The keyword 'Limit' isn't supported by MSSQL, so you'll need to use an alternative. This code worked in SQL 2008, and is based on this SO post. https://stackoverflow.com/a/1104447/993856

-- Keep the last 10 most recent passwords for this user.
DECLARE @UserID int; SET @UserID = 1004
DECLARE @ThresholdID int -- Position of 10th password.
SELECT  @ThresholdID = UserPasswordHistoryID FROM
        (
            SELECT ROW_NUMBER()
            OVER (ORDER BY UserPasswordHistoryID DESC) AS RowNum, UserPasswordHistoryID
            FROM UserPasswordHistory
            WHERE UserID = @UserID
        ) sub
WHERE   (RowNum = 10) -- Keep this many records.

DELETE  UserPasswordHistory
WHERE   (UserID = @UserID)
        AND (UserPasswordHistoryID < @ThresholdID)

Admittedly, this is not elegant. If you're able to optimize this for Microsoft SQL, please share your solution. Thanks!

How do you extract IP addresses from files using a regex in a linux shell?

If you are not given a specific file and you need to extract IP address then we need to do it recursively. grep command -> Searches a text or file for matching a given string and displays the matched string .

grep -roE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

-r We can search the entire directory tree i.e. the current directory and all levels of sub-directories. It denotes recursive searching.

-o Print only the matching string

-E Use extended regular expression

If we would not have used the second grep command after the pipe we would have got the IP address along with the path where it is present

Use mysql_fetch_array() with foreach() instead of while()

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

The opposite of Intersect()

You can use

a.Except(b).Union(b.Except(a));

Or you can use

var difference = new HashSet(a);
difference.SymmetricExceptWith(b);

"Logging out" of phpMyAdmin?

As said here and i quote:

just change this line on config.inc.php

$cfg['Servers'][$i]['auth_type'] = 'config'; 

to

$cfg['Servers'][$i]['auth_type'] = 'cookie'; 

then you will be prompted to login when you refreshed the page. Afterwards, the log out icon will appear next to home icon.

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

CURRENT_TIMESTAMP in milliseconds

The correct way of extracting miliseconds from a timestamp value on PostgreSQL accordingly to current documentation is:

SELECT date_part('milliseconds', current_timestamp);

--OR

SELECT EXTRACT(MILLISECONDS FROM current_timestamp);

with returns: The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

I had the same problem once. Calling invalidate after changing visibility almost always works, but in some cases it doesn't. I had to cheat and set the background to a transparent image and set the text to "".

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How to use the PRINT statement to track execution as stored procedure is running?

Can I just ask about the long term need for this facility - is it for debuging purposes?

If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.

Just my opinion, but I prefer the debugger approach - for code and databases.

Toolbar navigation icon never set

(The answer to user802421)

private void setToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
}

toolbar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/toolbar_height"
    android:background="?attr/colorPrimaryDark" />

Saving awk output to variable

#!/bin/bash

variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable

Notice that there's no space after the equal sign.

You can also use $() which allows nesting and is readable.

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

Prevent Android activity dialog from closing on outside touch

Alert Dialog is deprecated so use Dialog dialog = new Dialog(this);

For prevent close on outside touch

dialog.setCanceledOnTouchOutside(false);

What is the difference between a Docker image and a container?

Maybe explaining the whole workflow can help.

Everything starts with the Dockerfile. The Dockerfile is the source code of the image.

Once the Dockerfile is created, you build it to create the image of the container. The image is just the "compiled version" of the "source code" which is the Dockerfile.

Once you have the image of the container, you should redistribute it using the registry. The registry is like a Git repository -- you can push and pull images.

Next, you can use the image to run containers. A running container is very similar, in many aspects, to a virtual machine (but without the hypervisor).

Converting an object to a string

If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.

Change route params without reloading in Angular 2

For anyone like me finding this question the following might be useful.

I had a similar problem and initially tried using location.go and location.replaceState as suggested in other answers here. However I ran into problems when I had to navigate to another page on the app because the navigation was relative to the current route and the current route wasn't being updated by location.go or location.replaceState (the router doesn't know anything about what these do to the URL)

In essence I needed a solution that DIDN'T reload the page/component when the route parameter changed but DID update the route state internally.

I ended up using query parameters. You can find more about it here: https://angular-2-training-book.rangle.io/handout/routing/query_params.html

So if you need to do something like save an order and get an order ID you can update your page URL like shown below. Updating a centre location and related data on a map would be similar

// let's say we're saving an order. Initally the URL is just blah/orders
save(orderId) {
    // [Here we would call back-end to save the order in the database]

    this.router.navigate(['orders'], { queryParams: { id: orderId } });
    // now the URL is blah/orders?id:1234. We don't reload the orders
    // page or component so get desired behaviour of not seeing any 
    // flickers or resetting the page.
}

and you keep track of it within the ngOnInit method like:

ngOnInit() {
    this.orderId = this.route
        .queryParamMap
        .map(params => params.get('id') || null);
    // orderID is up-to-date with what is saved in database now, or if
    // nothing is saved and hence no id query paramter the orderId variable
    // is simply null.
    // [You can load the order here from its ID if this suits your design]
}

If you need to go direct to the order page with a new (unsaved) order you can do:

this.router.navigate(['orders']);

Or if you need to go direct to the order page for an existing (saved) order you can do:

this.router.navigate(['orders'], { queryParams: { id: '1234' } });

How to unpack and pack pkg file?

You might want to look into my fork of pbzx here: https://github.com/NiklasRosenstein/pbzx

It allows you to stream pbzx files that are not wrapped in a XAR archive. I've experienced this with recent XCode Command-Line Tools Disk Images (eg. 10.12 XCode 8).

pbzx -n Payload | cpio -i

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

How to change the background color of Action Bar's Option Menu in Android 4.2?

In case you are working in the latest toolbar in android studio then here is the smallest solution To change the toolbar options menu color, add this to your toolbar element

 app:popupTheme="@style/MyDarkToolbarStyle"

Then in your styles.xml define the popup menu style

<style name="MyDarkToolbarStyle" parent="ThemeOverlay.AppCompat.Light"> <item name="android:colorBackground">@color/mtrl_white_100</item> <item name="android:textColor">@color/mtrl_light_blue_900</item> </style>

Note that you need to use colorBackground not background. The latter would be applied to everything (the menu itself and each menu item), the former applies only to the popup menu.

insert datetime value in sql database with c#

you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"

Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.

DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";

sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

An easy way to fix this issue is to do the following (click on images to zoom):

Make sure to close Visual Studio, then go to your Windows Start -> Control Panel -> Programs and Features. Now do this:

enter image description here

A Visual Studio window will open up. Here go on doing this:

Select the checkbox for Common Tools for Visual C++ 2015 and install the update.

enter image description here

The update may takes some time (~5-10 minutes). After Visual Studio was successfully updated, reopen your project and hit Ctrl + F5. Your project should now compile and run without any problems.

Fragments onResume from back stack

A little improved and wrapped into a manager solution.

Things to keep in mind. FragmentManager is not a singleton, it manages only Fragments within Activity, so in every activity it will be new. Also, this solution so far doesn't take ViewPager into account that calls setUserVisibleHint() method helping to control visiblity of Fragments.

Feel free to use following classes when dealing with this issue (uses Dagger2 injection). Call in Activity:

//inject FragmentBackstackStateManager instance to myFragmentBackstackStateManager
FragmentManager fragmentManager = getSupportFragmentManager(); 
myFragmentBackstackStateManager.apply(fragmentManager);

FragmentBackstackStateManager.java:

@Singleton
public class FragmentBackstackStateManager {

    private FragmentManager fragmentManager;

    @Inject
    public FragmentBackstackStateManager() {
    }

    private BackstackCallback backstackCallbackImpl = new BackstackCallback() {
        @Override
        public void onFragmentPushed(Fragment parentFragment) {
            parentFragment.onPause();
        }

        @Override
        public void onFragmentPopped(Fragment parentFragment) {
            parentFragment.onResume();
        }
    };

    public FragmentBackstackChangeListenerImpl getListener() {
        return new FragmentBackstackChangeListenerImpl(fragmentManager, backstackCallbackImpl);
    }

    public void apply(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
        fragmentManager.addOnBackStackChangedListener(getListener());
    }
}

FragmentBackstackChangeListenerImpl.java:

public class FragmentBackstackChangeListenerImpl implements FragmentManager.OnBackStackChangedListener {

    private int lastBackStackEntryCount = 0;
    private final FragmentManager fragmentManager;
    private final BackstackCallback backstackChangeListener;

    public FragmentBackstackChangeListenerImpl(FragmentManager fragmentManager, BackstackCallback backstackChangeListener) {
        this.fragmentManager = fragmentManager;
        this.backstackChangeListener = backstackChangeListener;
        lastBackStackEntryCount = fragmentManager.getBackStackEntryCount();
    }

    private boolean wasPushed(int backStackEntryCount) {
        return lastBackStackEntryCount < backStackEntryCount;
    }

    private boolean wasPopped(int backStackEntryCount) {
        return lastBackStackEntryCount > backStackEntryCount;
    }

    private boolean haveFragments() {
        List<Fragment> fragmentList = fragmentManager.getFragments();
        return fragmentList != null && !fragmentList.isEmpty();
    }


    /**
     * If we push a fragment to backstack then parent would be the one before => size - 2
     * If we pop a fragment from backstack logically it should be the last fragment in the list, but in Android popping a fragment just makes list entry null keeping list size intact, thus it's also size - 2
     *
     * @return fragment that is parent to the one that is pushed to or popped from back stack
     */
    private Fragment getParentFragment() {
        List<Fragment> fragmentList = fragmentManager.getFragments();
        return fragmentList.get(Math.max(0, fragmentList.size() - 2));
    }

    @Override
    public void onBackStackChanged() {
        int currentBackStackEntryCount = fragmentManager.getBackStackEntryCount();
        if (haveFragments()) {
            Fragment parentFragment = getParentFragment();

            //will be null if was just popped and was last in the stack
            if (parentFragment != null) {
                if (wasPushed(currentBackStackEntryCount)) {
                    backstackChangeListener.onFragmentPushed(parentFragment);
                } else if (wasPopped(currentBackStackEntryCount)) {
                    backstackChangeListener.onFragmentPopped(parentFragment);
                }
            }
        }

        lastBackStackEntryCount = currentBackStackEntryCount;
    }
}

BackstackCallback.java:

public interface BackstackCallback {
    void onFragmentPushed(Fragment parentFragment);

    void onFragmentPopped(Fragment parentFragment);
}

jQuery - Detect value change on hidden input field

Although this thread is 3 years old, here is my solution:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}

How to check if an NSDictionary or NSMutableDictionary contains a key?

Solution for swift 4.2

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

What is the difference between "INNER JOIN" and "OUTER JOIN"?

There are major mainly 2 types of JOINs in SQL: [INNER and OUTER]


Examples

Suppose you have two tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6
7
8

Note that (1,2,7,8) are unique to A, (3,4) are common, and (5,6) are unique to B.



  • (INNER) JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same.

INNER JOIN

select * from a INNER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b;

Result:

a | b
--+--
3 | 3
4 | 4


  • LEFT (OUTER) JOIN:

This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

LEFT JOIN / LEFT OUTER JOIN

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b(+);

Result:

a |  b
--+-----
1 | null
2 | null
3 |    3
4 |    4
7 | null
8 | null


  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table

RIGHT JOIN / RIGHT OUTER JOIN

select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a(+) = b.b;

Result:

a    |  b
-----+----
3    |  3
4    |  4
null |  5
null |  6


  • FULL (OUTER) JOIN:

    FULL JOIN creates the result-set by combining the result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.

FULL JOIN / FULL OUTER JOIN

select * from a FULL OUTER JOIN b on a.a = b.b;

Result:

 a   |  b
-----+-----
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5
   7 | null
   8 | null

Set height 100% on absolute div

http://jsbin.com/ubalax/1/edit .You can see the results here

body {
    position: relative;
    float: left;
    height: 3000px;
    width: 100%;
}
body div {
    position: absolute;
    height: 100%;
    width: 100%;
    top:0;
    left:0;
    background-color: yellow;
}

Django set default form values

I hope this can help you:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id

open resource with relative path in Java

I had problems with using the getClass().getResource("filename.txt") method. Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:

src/main/com/mycompany/myapp

then you can add a resources folder as recommended by maven in:

src/main/resources

furthermore you can add subfolders in the resources folder

src/main/resources/textfiles

and say that your file is called myfile.txt so you have

src/main/resources/textfiles/myfile.txt

Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:

"/main/resources/textfiles/myfile.txt" path

or

"/resources/textfiles/myfile.txt"

both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:

myapp/target/classes 

folder. But the resources folder is not there, just the folders in the resources folder. So you have:

myapp/target/classes/textfiles/myfile.txt

myapp/target/classes/com/mycompany/myapp/*

so the correct path to give to the getClass().getResource("") method is:

"/textfiles/myfile.txt"

here it is:

getClass().getResource("/textfiles/myfile.txt")

This will no longer return null, but will return your class. I hope this helps somebody. It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under "myapp/target/classes"

Parse large JSON file in Nodejs

I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".

Sample code:

var fs = require('fs')
  , split = require('split')
  ;

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
    var json = JSON.parse(chunk);           
    // ...
});

<Django object > is not JSON serializable

simplejson and json don't work with django objects well.

Django's built-in serializers can only serialize querysets filled with django objects:

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

In your case, self.get_queryset() contains a mix of django objects and dicts inside.

One option is to get rid of model instances in the self.get_queryset() and replace them with dicts using model_to_dict:

from django.forms.models import model_to_dict

data = self.get_queryset()

for item in data:
   item['product'] = model_to_dict(item['product'])

return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")

Hope that helps.

How do I convert a number to a letter in Java?

public static void main(String[] args)
 {
     int rem,n=702,quo;
     String s=" ";
     while(n>0)
     {
         rem=(n-1)%26;
         quo=(n-1)/26;
         s=(char)(rem+97)+s;
         if(quo==1)
         {
            s=(char)(97)+s;
            break;
         }
         else
         n=(n-1)/26;
     }
     System.out.print(s);
 }
}
////We can also write the code like the below one. There is no much difference but it may help to understand the concept for some people.


public static void main(String[] args)
 {
     int rem,n=52,quo;
     String s=" ";
     while(n>0)
     {
         rem=n%26;
         quo=n/26;
         if(rem==0)
             rem=26;
         s=(char)(rem+96)+s;
         if((quo==1 || quo==0) && n>26)
         {
             n=n/26;
            s=(char)(n+96)+s;
            break;
         }
         else
             n=n/26-1; 
     }
     System.out.print(s);
 }

Find and replace entire mysql database

Another option (depending on the use case) would be to use DataMystic's TextPipe and DataPipe products. I've used them in the past, and they've worked great in the complex replacement scenarios, and without having to export data out of the database for find-and-replace.

Angular ng-if not true

Use like this

<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>

Find empty or NaN entry in Pandas Dataframe

Try this:

df[df['column_name'] == ''].index

and for NaNs you can try:

pd.isna(df['column_name'])

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using the AWS Management Console

  • Go to "Volumes" and create a Snapshot of your instance's volume.
  • Go to "Snapshots" and select "Create Image from Snapshot".
  • Go to "AMIs" and select "Launch Instance" and choose your "Instance Type" etc.

Jackson Vs. Gson

Gson 1.6 now includes a low-level streaming API and a new parser which is actually faster than Jackson.

Converting Select results into Insert script - SQL Server

You can Choose 'Result to File' option in SSMS and export your select result to file and make your changes in result file and finally using BCP - Bulk copy you can insert in table 1 in database 2.

I think for bulk insert you have to convert .rpt file to .csv file

Hope it will help.

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

How to prevent line-break in a column of a table cell (not a single cell)?

Use the nowrap style:

<td style="white-space:nowrap;">...</td>

It's CSS!

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

How do I run a program with commandline arguments using GDB within a Bash script?

Much too late, but here is a method that works during gdb session.

gdb <executable>

then

(gdb) apropos argument

This will return lots of matches, the useful one is set args.

set args -- Set argument list to give program being debugged when it is started.

set args arg1 arg2 ...

then

r

This will run the program, passing to main(argc, argv) the arguments and the argument count.

How to rename a file using Python

One important point to note here, we should check if any files exists with the new filename.

suppose if b.kml file exists then renaming other file with the same filename leads to deletion of existing b.kml.

import os

if not os.path.exists('b.kml')
    os.rename('a.txt','b.kml')

Vue.js img src concatenate variable and text

In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:

<img v-bind:src="`${imgPreUrl()}img/logo.png`">

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

Limit the output of the TOP command to a specific process name

The following code updates a list of processes every 5 seconds via the watch command:

watch -n 5 -t top -b -n 1 -p$(pgrep java | head -20 | tr "\\n" "," | sed 's/,$//')

Which one is the best PDF-API for PHP?

I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.