Programs & Examples On #Expandoobject

ExpandoObject is a .NET type whose members can be added and removed at runtime.

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

What does localhost:8080 mean?

the localhost:8080 means your explicitly targeting port 8080.

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Removing the password from a VBA project

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps! JFV

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

Convert string to title case with JavaScript

Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

For example:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How to make a div have a fixed size?

Use this style

<div class="form-control"
     style="height:100px;
     width:55%;
     overflow:hidden;
     cursor:pointer">
</div>

Access denied for user 'test'@'localhost' (using password: YES) except root user

In my case the same error happen because I was trying to use mysql by just typing "mysql" instead of "mysql -u root -p"

How to Delete node_modules - Deep Nested Folder in Windows

Just use powershell..

Run powershell and cd to the parent folder and then:

rm [yourfolder]

as in:

rm node_modules

Benefits of inline functions in C++?

In archaic C and C++, inline is like register: a suggestion (nothing more than a suggestion) to the compiler about a possible optimization.

In modern C++, inline tells the linker that, if multiple definitions (not declarations) are found in different translation units, they are all the same, and the linker can freely keep one and discard all the other ones.

inline is mandatory if a function (no matter how complex or "linear") is defined in a header file, to allow multiple sources to include it without getting a "multiple definition" error by the linker.

Member functions defined inside a class are "inline" by default, as are template functions (in contrast to global functions).

//fileA.h
inline void afunc()
{ std::cout << "this is afunc" << std::endl; }

//file1.cpp
#include "fileA.h"
void acall()
{ afunc(); }

//main.cpp
#include "fileA.h"
void acall();

int main()
{ 
   afunc(); 
   acall();
}

//output
this is afunc
this is afunc

Note the inclusion of fileA.h into two .cpp files, resulting in two instances of afunc(). The linker will discard one of them. If no inline is specified, the linker will complain.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

As you probably figured out, the issue is that you are trying to allocate one large contiguous block of memory, which does not work due to memory fragmentation. If I needed to do what you are doing I would do the following:

int sizeA = 10000,
    sizeB = 10000;
double sizeInMegabytes = (sizeA * sizeB * 8.0) / 1024.0 / 1024.0; //762 mb
double[][] randomNumbers = new double[sizeA][];
for (int i = 0; i < randomNumbers.Length; i++)
{
    randomNumbers[i] = new double[sizeB];
}

Then, to get a particular index you would use randomNumbers[i / sizeB][i % sizeB].

Another option if you always access the values in order might be to use the overloaded constructor to specify the seed. This way you would get a semi random number (like the DateTime.Now.Ticks) store it in a variable, then when ever you start going through the list you would create a new Random instance using the original seed:

private static int randSeed = (int)DateTime.Now.Ticks;  //Must stay the same unless you want to get different random numbers.
private static Random GetNewRandomIterator()
{
    return new Random(randSeed);
}

It is important to note that while the blog linked in Fredrik Mörk's answer indicates that the issue is usually due to a lack of address space it does not list a number of other issues, like the 2GB CLR object size limitation (mentioned in a comment from ShuggyCoUk on the same blog), glosses over memory fragmentation, and fails to mention the impact of page file size (and how it can be addressed with the use of the CreateFileMapping function).

The 2GB limitation means that randomNumbers must be less than 2GB. Since arrays are classes and have some overhead them selves this means an array of double will need to be smaller then 2^31. I am not sure how much smaller then 2^31 the Length would have to be, but Overhead of a .NET array? indicates 12 - 16 bytes.

Memory fragmentation is very similar to HDD fragmentation. You might have 2GB of address space, but as you create and destroy objects there will be gaps between the values. If these gaps are too small for your large object, and additional space can not be requested, then you will get the System.OutOfMemoryException. For example, if you create 2 million, 1024 byte objects, then you are using 1.9GB. If you delete every object where the address is not a multiple of 3 then you will be using .6GB of memory, but it will be spread out across the address space with 2024 byte open blocks in between. If you need to create an object which was .2GB you would not be able to do it because there is not a block large enough to fit it in and additional space cannot be obtained (assuming a 32 bit environment). Possible solutions to this issue are things like using smaller objects, reducing the amount of data you store in memory, or using a memory management algorithm to limit/prevent memory fragmentation. It should be noted that unless you are developing a large program which uses a large amount of memory this will not be an issue. Also, this issue can arise on 64 bit systems as windows is limited mostly by the page file size and the amount of RAM on the system.

Since most programs request working memory from the OS and do not request a file mapping, they will be limited by the system's RAM and page file size. As noted in the comment by Néstor Sánchez (Néstor Sánchez) on the blog, with managed code like C# you are stuck to the RAM/page file limitation and the address space of the operating system.


That was way longer then expected. Hopefully it helps someone. I posted it because I ran into the System.OutOfMemoryException running a x64 program on a system with 24GB of RAM even though my array was only holding 2GB of stuff.

How do I put two increment statements in a C++ 'for' loop?

I agree with squelart. Incrementing two variables is bug prone, especially if you only test for one of them.

This is the readable way to do this:

int j = 0;
for(int i = 0; i < 5; ++i) {
    do_something(i, j);
    ++j;
}

For loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.

If you need j to be tied to i, why not leave the original variable as is and add i?

for(int i = 0; i < 5; ++i) {
    do_something(i,a+i);
}

If your logic is more complex (for example, you need to actually monitor more than one variable), I'd use a while loop.

git replace local version with remote version

Use the -s or --strategy option combined with the -X option. In your specific question, you want to keep all of the remote files and replace the local files of the same name.

Replace conflicts with the remote version

git merge -s recursive -Xtheirs upstream/master  

will use the remote repo version of all conflicting files.

Replace conflicts with the local version

git merge -s recursive -Xours upstream/master

will use the local repo version of all conflicting files.

Check if a row exists, otherwise insert

Take a look at MERGE command. You can do UPDATE, INSERT & DELETE in one statement.

Here is a working implementation on using MERGE
- It checks whether flight is full before doing an update, else does an insert.

if exists(select 1 from INFORMATION_SCHEMA.TABLES T 
              where T.TABLE_NAME = 'Bookings') 
begin
    drop table Bookings
end
GO

create table Bookings(
  FlightID    int identity(1, 1) primary key,
  TicketsMax    int not null,
  TicketsBooked int not null
)
GO

insert  Bookings(TicketsMax, TicketsBooked) select 1, 0
insert  Bookings(TicketsMax, TicketsBooked) select 2, 2
insert  Bookings(TicketsMax, TicketsBooked) select 3, 1
GO

select * from Bookings

And then ...

declare @FlightID int = 1
declare @TicketsToBook int = 2

--; This should add a new record
merge Bookings as T
using (select @FlightID as FlightID, @TicketsToBook as TicketsToBook) as S
    on  T.FlightID = S.FlightID
      and T.TicketsMax > (T.TicketsBooked + S.TicketsToBook)
  when matched then
    update set T.TicketsBooked = T.TicketsBooked + S.TicketsToBook
  when not matched then
    insert (TicketsMax, TicketsBooked) 
    values(S.TicketsToBook, S.TicketsToBook);

select * from Bookings

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

Maybe an old version of the service was not uninstalled from windows

  1. uninstall the old version running this command line

    sc delete wampapache

  2. Reinstall the service from wamp:

    Wamp Tray Icon -> Apache -> Service -> Install Service

It works for me, enjoy!

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Turns out that the culprit was the IIS Url Rewrite module. I had defined a rule that redirected calls to Default.aspx (which was set as the start page of the web site) to the root of the site so that I could have a canonical home URL. However, apparently VS had a problem with this and got confused. This problem did not happen when I was using Helicon ISAPI_Rewrite so it didn't even occur to me to check.

I ended up creating a whole new web site from scratch and porting projects/files over little by little into my solution and rebuilding my web.config until I found this out! Well, at least now I have a slightly cleaner site using .NET 4.0 (so far, hopefully I won't run into any walls)--but what a pain!

Get random sample from list while maintaining ordering of items?

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size)

generates a random sample of the indices of the original list.

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

OOP vs Functional Programming vs Procedural

All of them are good in their own ways - They're simply different approaches to the same problems.

In a purely procedural style, data tends to be highly decoupled from the functions that operate on it.

In an object oriented style, data tends to carry with it a collection of functions.

In a functional style, data and functions tend toward having more in common with each other (as in Lisp and Scheme) while offering more flexibility in terms of how functions are actually used. Algorithms tend also to be defined in terms of recursion and composition rather than loops and iteration.

Of course, the language itself only influences which style is preferred. Even in a pure-functional language like Haskell, you can write in a procedural style (though that is highly discouraged), and even in a procedural language like C, you can program in an object-oriented style (such as in the GTK+ and EFL APIs).

To be clear, the "advantage" of each paradigm is simply in the modeling of your algorithms and data structures. If, for example, your algorithm involves lists and trees, a functional algorithm may be the most sensible. Or, if, for example, your data is highly structured, it may make more sense to compose it as objects if that is the native paradigm of your language - or, it could just as easily be written as a functional abstraction of monads, which is the native paradigm of languages like Haskell or ML.

The choice of which you use is simply what makes more sense for your project and the abstractions your language supports.

Two way sync with rsync

Try Unison: http://www.cis.upenn.edu/~bcpierce/unison/

Syntax: unison dirA/ dirB/

Unison asks what to do when files are different, but you can automate the process by using the following which accepts default (nonconflicting) options:

unison -auto dirA/ dirB/

unison -batch dirA/ dirB/ asks no questions at all, and writes to output how many files were ignored (because they conflicted).

Global constants file in Swift

Consider enumerations. These can be logically broken up for separate use cases.

enum UserDefaultsKeys: String {
    case SomeNotification = "aaaaNotification"
    case DeviceToken = "deviceToken"
}

enum PhotoMetaKeys: String {
    case Orientation = "orientation_hv"
    case Size = "size"
    case DateTaken = "date_taken"
}

One unique benefit happens when you have a situation of mutually exclusive options, such as:

for (key, value) in photoConfigurationFile {
    guard let key = PhotoMetaKeys(rawvalue: key) else {
        continue // invalid key, ignore it
    }
    switch (key) {
    case.Orientation: {
        photo.orientation = value
    }
    case.Size: {
        photo.size = value
    }
    }
}

In this example, you will receive a compile error because you have not handled the case of PhotoMetaKeys.DateTaken.

How to catch integer(0)?

Maybe off-topic, but R features two nice, fast and empty-aware functions for reducing logical vectors -- any and all:

if(any(x=='dolphin')) stop("Told you, no mammals!")

How to return a file (FileContentResult) in ASP.NET WebAPI

I am not exactly sure which part to blame, but here's why MemoryStream doesn't work for you:

As you write to MemoryStream, it increments it's Position property. The constructor of StreamContent takes into account the stream's current Position. So if you write to the stream, then pass it to StreamContent, the response will start from the nothingness at the end of the stream.

There's two ways to properly fix this:

1) construct content, write to stream

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    // ...
    // stream.Write(...);
    // ...
    return response;
}

2) write to stream, reset position, construct content

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    // ...
    // stream.Write(...);
    // ...
    stream.Position = 0;

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return response;
}

2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

How do I do a HTTP GET in Java?

If you want to stream any webpage, you can use the method below.

import java.io.*;
import java.net.*;

public class c {

   public static String getHTML(String urlToRead) throws Exception {
      StringBuilder result = new StringBuilder();
      URL url = new URL(urlToRead);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      try (var reader = new BufferedReader(
                  new InputStreamReader(conn.getInputStream()))) {
          for (String line; (line = reader.readLine()) != null; ) {
              result.append(line);
          }
      }
      return result.toString();
   }

   public static void main(String[] args) throws Exception
   {
     System.out.println(getHTML(args[0]));
   }
}

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Does the class org.apache.maven.shared.filtering.MavenFilteringException exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar?

The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.

I'm also wondering where the version 1.0-beta-2 comes from; I have 1.0 on my disk. Try version 2.3 of the WAR plugin.

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

This happens because of your application does not allow to append iframe from origin other than your application domain.

If your application have web.config then add the following tag in web.config

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="X-Frame-Options" value="ALLOW" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option

X-FRAME-OPTIONS: ALLOW-FROM https://example.com/ 

Error 1022 - Can't write; duplicate key in table

The most likely you already have a constraint with the name iduser or idcategory in your database. Just rename the constraints if so.

Constraints must be unique for the entire database, not just for the specific table you are creating/altering.

To find out where the constraints are currently in use you can use the following query:

SELECT `TABLE_SCHEMA`, `TABLE_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_NAME` IN ('iduser', 'idcategory');

Javascript ES6/ES5 find in array and change

worked for me

let returnPayments = [ ...this.payments ];

returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;

How do you set the title color for the new Toolbar?

Create a toolbar in your xml...toolbar.xml:

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"

    </android.support.v7.widget.Toolbar>

Then add the following in your toolbar.xml:

app:titleTextColor="@color/colorText"
app:title="@string/app_name">

Remeber @color/colorText is simply your color.xml file with the color attribute named colorText and your color.This is the best way to calll your strings rather than hardcoding your color inside your toolbar.xml. You also have other options to modify your text,such as:textAppearance...etc...just type app:text...and intelisense will give you options in android studio.

your final toolbar should look like this:

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_weight="1"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/Theme.AppCompat"
       app:subtitleTextAppearance="@drawable/icon"
        app:title="@string/app_name">
    </android.support.v7.widget.Toolbar>

NB:This toolbar should be inside your activity_main.xml.Easy Peasie

Another option is to do it all in your class:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);

Good Luck

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How do I make the method return type generic?

I did the following in my lib kontraktor:

public class Actor<SELF extends Actor> {
    public SELF self() { return (SELF)_self; }
}

subclassing:

public class MyHttpAppSession extends Actor<MyHttpAppSession> {
   ...
}

at least this works inside the current class and when having a strong typed reference. Multiple inheritance works, but gets really tricky then :)

Android - Activity vs FragmentActivity?

FragmentActivity gives you all of the functionality of Activity plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.

If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity and use the native Fragments introduced in v11 without issue. FragmentActivity was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.

I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.

JavaScript equivalent of PHP's in_array()

haystack.find(value => value == needle)

where haystack is an array and needle is an element in array. If element not found will be returned undefined else the same element.

clear table jquery

Slightly quicker than removing each one individually:

$('#myTable').empty()

Technically, this will remove thead, tfoot and tbody elements too.

How to serialize object to CSV file?

Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.

I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.

Link: https://github.com/abhisoni96/dev-tools

Difference between Hive internal tables and external tables?

Hive tables can be created as EXTERNAL or INTERNAL. This is a choice that affects how data is loaded, controlled, and managed.

Use EXTERNAL tables when:

  1. The data is also used outside of Hive. For example, the data files are read and processed by an existing program that doesn't lock the files.
  2. Data needs to remain in the underlying location even after a DROP TABLE. This can apply if you are pointing multiple schemas (tables or views) at a single data set or if you are iterating through various possible schemas.
  3. You want to use a custom location such as ASV.
  4. Hive should not own data and control settings, dirs, etc., you have another program or process that will do those things.
  5. You are not creating table based on existing table (AS SELECT).

Use INTERNAL tables when:

The data is temporary.

You want Hive to completely manage the lifecycle of the table and data.

get an element's id

Yes you can simply say:


function getID(oObject) 
{
    var id = oObject.id;
    alert("This object's ID attribute is set to \"" + id + "\"."); 
}

Check this out: ID Attribute | id Property

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

How can I check if an InputStream is empty without reading from it?

If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
    //stream not empty
} else {
    //stream empty
} 

If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

php: check if an array has duplicates

Keep it simple, silly! ;)

Simple OR logic...

function checkDuplicatesInArray($array){
    $duplicates=FALSE;
    foreach($array as $k=>$i){
        if(!isset($value_{$i})){
            $value_{$i}=TRUE;
        }
        else{
            $duplicates|=TRUE;          
        }
    }
    return ($duplicates);
}

Regards!

filedialog, tkinter and opening files

The exception you get is telling you filedialog is not in your namespace. filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *

>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>> 

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

enter image description here

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

How to change color of ListView items on focus and on click

Declare list item components as final outside your setOnClickListener or whatever you want to apply on your list item like this:

final View yourView;
final TextView yourTextView;

And in overriding onClick or whatever method you use, just set colors as needed like this:

yourView.setBackgroundColor(Color.WHITE/*or whatever RGB suites good contrast*/);
yourTextView.setTextColor(Color.BLACK/*or whatever RGB suites good contrast*/);

Or without the final declaration, if let's say you implement an onClick() for a custom adapter to populate a list, this is what I used in getView() for my setOnClickListener/onClick():

//reset color for all list items in case any item was previously selected
for(int i = 0; i < parent.getChildCount(); i++)
{
  parent.getChildAt(i).setBackgroundColor(Color.BLACK);
  TextView text=(TextView) parent.getChildAt(i).findViewById(R.id.item);
  text.setTextColor(Color.rgb(0,178,178));
}
//highlight currently selected item
 parent.getChildAt(position).setBackgroundColor(Color.rgb(0,178,178));
 TextView text=(TextView) parent.getChildAt(position).findViewById(R.id.item);
 text.setTextColor(Color.rgb(0,178,178));

I get Access Forbidden (Error 403) when setting up new alias

I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...

The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf file is below...

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#

##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
    ##ServerName dummy-host.example.com
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs"
    ServerName localhost
</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
    </Directory>
</VirtualHost>

I then updated my C:\windows\System32\drivers\etc\hosts file like this...

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1   dev.middleweek.co.uk
127.0.0.1       localhost

Restart your machine for good measure, open the XAMPP Control Panel and start Apache.

Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk

Hope that helps someone!

And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf to include "Options Indexes" like this...

<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
        Options Indexes
    </Directory>
</VirtualHost>

Cheers, Nick

Detect if the app was launched/opened from a push notification

Swift 2.0 For 'Not Running' State (Local & Remote Notification)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


// Handle notification
if (launchOptions != nil) {

    // For local Notification
    if let localNotificationInfo = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {

        if let something = localNotificationInfo.userInfo!["yourKey"] as? String {
            self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
        }


    } else

    // For remote Notification
    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject]? {

        if let something = remoteNotification["yourKey"] as? String {
            self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
        }
    }

}


return true
}

Initializing an Array of Structs in C#

I'd use a static constructor on the class that sets the value of a static readonly array.

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}

Why does my 'git branch' have no master?

I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add . and then git commit and the master branch will be created.

Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.

Printing everything except the first field with awk

Yet another way...

...this rejoins the fields 2 thru NF with the FS and outputs one line per line of input

awk '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'

I use this with git to see what files have been modified in my working dir:

git diff| \
    grep '\-\-git'| \
    awk '{print$NF}'| \
    awk -F"/" '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'

How to get bitmap from a url in android?

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

In C# it also works with a null as the 4th parameter.

@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })

Encode a FileStream to base64 with c#

You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?

Or I think it should be also possible to use the .ToString() method and encode this.

Store mysql query output into a shell variable

Another example when the table name or database contains unsupported characters such as a space, or '-'

db='data-base'

db_d=''
db_d+='`'
db_d+=$db
db_d+='`'

myvariable=`mysql --user=$user --password=$password -e "SELECT A, B, C FROM $db_d.table_a;"`

No mapping found for HTTP request with URI.... in DispatcherServlet with name

What is /Elso?

You try:

@RequestMapping("/Elso")
public class myController {

    @RequestMapping("/hello")
    public ModelAndView helloWorld() {

        String message = "Hello World, Spring 3.0!";
        return new ModelAndView("hello", "message", message); 
    }
}

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

C++ correct way to return pointer to array from function

Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:

  • When you create an array with syntax int arr[5];, it's allocated on the stack and is local to the function.
  • C++ allows you to return a pointer to this array, but it is undefined behavior to use the memory pointed to by this pointer outside of its local scope. Read this great answer using a real world analogy to get a much clear understanding than what I could ever explain.
  • You can still use the array outside the scope if you can guarantee that memory of the array has not be purged. In your case this is true when you pass arr to test().
  • If you want to pass around pointers to a dynamically allocated array without worrying about memory leaks, you should do some reading on std::unique_ptr/std::shared_ptr<>.

Edit - to answer the use-case of matrix multiplication

You have two options. The naive way is to use std::unique_ptr/std::shared_ptr<>. The Modern C++ way is to have a Matrix class where you overload operator * and you absolutely must use the new rvalue references if you want to avoid copying the result of the multiplication to get it out of the function. In addition to having your copy constructor, operator = and destructor, you also need to have move constructor and move assignment operator. Go through the questions and answers of this search to gain more insight on how to achieve this.

Edit 2 - answer to appended question

int* test (int a[5], int b[5]) {
    int *c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

If you are using this as int *res = test(a,b);, then sometime later in your code, you should call delete []res to free the memory allocated in the test() function. You see now the problem is it is extremely hard to manually keep track of when to make the call to delete. Hence the approaches on how to deal with it where outlined in the answer.

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

Generating random number between 1 and 10 in Bash Shell Script

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.

 echo $RANDOM % 10 + 1 | bc

How to disable text selection using jQuery?

I think this code works on all browsers and requires the least overhead. It's really a hybrid of all the above answers. Let me know if you find a bug!

Add CSS:

.no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}

Add jQuery:

(function($){
    $.fn.disableSelection = function() 
    {       
        $(this).addClass('no_select');              
        if($.browser.msie)
        {
            $(this).attr('unselectable', 'on').on('selectstart', false);            
        }
    return this;            
};
})(jQuery);

Optional: To disable selection for all children elements as well, you can change the IE block to:

$(this).each(function() {
    $(this).attr('unselectable','on')
    .bind('selectstart',function(){ return false; });
});

Usage:

$('.someclasshere').disableSelection();

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

How to center-justify the last line of text in CSS?

For people looking for getting text that is both centered and justified, the following should work:

<div class="center-justified">...lots and lots of text...</div>

With the following CSS rule (adjust the width property as needed):

.center-justified {
  text-align: justify;
  margin: 0 auto;
  width: 30em;
}

Here's the live demo.

What's going on?

  1. text-align: justify; makes sure the text fills the full width of the div it is enclosed in.
  2. margin: 0 auto; is actually a shorthand for four rules:
    • The first value is used for the margin-top and margin-bottom rules. The whole thing therefore means margin-top: 0; margin-bottom: 0, i.e. no margins above or below the div.
    • The second value is used for the margin-left and margin-right rules. So this rule results in margin-left: auto; margin-right: auto. This is the clever bit: it tells the browser to take whatever space is available on the sides and distribute it evenly on left and right. The result is centered text.
      However, this would not work without
  3. width: 30em;, which limits the width of the div. Only when the width is restricted is there some whitespace left over for margin: auto to distribute. Without this rule the div would take up all available horizontal space, and you'd lose the centering effect.

Correct Way to Load Assembly, Find Class and Call Run() Method

I'm doing exactly what you're looking for in my rules engine, which uses CS-Script for dynamically compiling, loading, and running C#. It should be easily translatable into what you're looking for, and I'll give an example. First, the code (stripped-down):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CSScriptLibrary;

namespace RulesEngine
{
    /// <summary>
    /// Make sure <typeparamref name="T"/> is an interface, not just any type of class.
    /// 
    /// Should be enforced by the compiler, but just in case it's not, here's your warning.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RulesEngine<T> where T : class
    {
        public RulesEngine(string rulesScriptFileName, string classToInstantiate)
            : this()
        {
            if (rulesScriptFileName == null) throw new ArgumentNullException("rulesScriptFileName");
            if (classToInstantiate == null) throw new ArgumentNullException("classToInstantiate");

            if (!File.Exists(rulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", rulesScriptFileName);
            }

            RulesScriptFileName = rulesScriptFileName;
            ClassToInstantiate = classToInstantiate;

            LoadRules();
        }

        public T @Interface;

        public string RulesScriptFileName { get; private set; }
        public string ClassToInstantiate { get; private set; }
        public DateTime RulesLastModified { get; private set; }

        private RulesEngine()
        {
            @Interface = null;
        }

        private void LoadRules()
        {
            if (!File.Exists(RulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", RulesScriptFileName);
            }

            FileInfo file = new FileInfo(RulesScriptFileName);

            DateTime lastModified = file.LastWriteTime;

            if (lastModified == RulesLastModified)
            {
                // No need to load the same rules twice.
                return;
            }

            string rulesScript = File.ReadAllText(RulesScriptFileName);

            Assembly compiledAssembly = CSScript.LoadCode(rulesScript, null, true);

            @Interface = compiledAssembly.CreateInstance(ClassToInstantiate).AlignToInterface<T>();

            RulesLastModified = lastModified;
        }
    }
}

This will take an interface of type T, compile a .cs file into an assembly, instantiate a class of a given type, and align that instantiated class to the T interface. Basically, you just have to make sure the instantiated class implements that interface. I use properties to setup and access everything, like so:

private RulesEngine<IRulesEngine> rulesEngine;

public RulesEngine<IRulesEngine> RulesEngine
{
    get
    {
        if (null == rulesEngine)
        {
            string rulesPath = Path.Combine(Application.StartupPath, "Rules.cs");

            rulesEngine = new RulesEngine<IRulesEngine>(rulesPath, typeof(Rules).FullName);
        }

        return rulesEngine;
    }
}

public IRulesEngine RulesEngineInterface
{
    get { return RulesEngine.Interface; }
}

For your example, you want to call Run(), so I'd make an interface that defines the Run() method, like this:

public interface ITestRunner
{
    void Run();
}

Then make a class that implements it, like this:

public class TestRunner : ITestRunner
{
    public void Run()
    {
        // implementation goes here
    }
}

Change the name of RulesEngine to something like TestHarness, and set your properties:

private TestHarness<ITestRunner> testHarness;

public TestHarness<ITestRunner> TestHarness
{
    get
    {
        if (null == testHarness)
        {
            string sourcePath = Path.Combine(Application.StartupPath, "TestRunner.cs");

            testHarness = new TestHarness<ITestRunner>(sourcePath , typeof(TestRunner).FullName);
        }

        return testHarness;
    }
}

public ITestRunner TestHarnessInterface
{
    get { return TestHarness.Interface; }
}

Then, anywhere you want to call it, you can just run:

ITestRunner testRunner = TestHarnessInterface;

if (null != testRunner)
{
    testRunner.Run();
}

It would probably work great for a plugin system, but my code as-is is limited to loading and running one file, since all of our rules are in one C# source file. I would think it'd be pretty easy to modify it to just pass in the type/source file for each one you wanted to run, though. You'd just have to move the code from the getter into a method that took those two parameters.

Also, use your IRunnable in place of ITestRunner.

Why can't I see the "Report Data" window when creating reports?

please go to

View > Toolbars > Customize

then select "Data" categories then click "Show data source" in command panel

"Data" menu will be seen in menu panel. click to get the website data source

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

This could actually do it without having to write code:

In your catch block, add a break point at the following line of code:

catch (Exception exception)
{

}

Now if you hover on exception or add it to the Watch and then navigate into the exception details as shown below; you will see which particular column(s) is/ are causing the problem as this error usually occurs when a table-constraint is violated..

enter image description here

Large image

Inner join of DataTables in C#

this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.

public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
    var dt = new DataTable();
    var joinTable = from t1 in dataTable1.AsEnumerable()
                            join t2 in dataTable2.AsEnumerable()
                                on t1[joinField] equals t2[joinField]
                            select new { t1, t2 };

    foreach (DataColumn col in dataTable1.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    dt.Columns.Remove(joinField);

    foreach (DataColumn col in dataTable2.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    foreach (var row in joinTable)
    {
        var newRow = dt.NewRow();
        newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
        dt.Rows.Add(newRow);
    }
    return dt;
}

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

HTTP Error 500.30 - ANCM In-Process Start Failure

I had a similar issue when attempting to switch to from OutOfProcess hosting to InProcess hosting on a .Net Core project which I had recently upgraded from 2.0 to 3.0.

With no real helpful error to go on and after spending days trying to resolve this, I eventually found a fix for my case which I thought I'd share in case it is helpful to anyone else struggling with this.

For me, it was caused by a few Microsoft.AspNetCore packages.

After removing all of the referenced Microsoft.AspNetCore packages that had version less than 3.0.0 (there was no upgrade available >= 3.0.0 for these) this error no longer occurred.

These were the packages I removed;

<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.2.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />

All other Microsoft.AspNetCore packages with version greater than or equal to 3.0.0 worked fine.

Programmatically navigate to another view controller/scene

You can move from one scene to another programmatically using below code :

  let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

  let objSomeViewController = storyBoard.instantiateViewControllerWithIdentifier(“storyboardID”) as! SomeViewController

  // If you want to push to new ViewController then use this
  self.navigationController?.pushViewController(objSomeViewController, animated: true)

  // ---- OR ----

  // If you want to present the new ViewController then use this
  self.presentViewController(objSomeViewController, animated:true, completion:nil) 

Here storyBoardID is value that you set to scene using Interface Builder. This is shown below :

Screenshot for how to set storyboardID

How to stop/shut down an elasticsearch node?

Answer for Elasticsearch inside Docker:

Just stop the docker container. It seems to stop gracefully because it logs:

[INFO ][o.e.n.Node               ] [elastic] stopping ...

Ternary operator in PowerShell

Powershell 7 has it. https://toastit.dev/2019/09/25/ternary-operator-powershell-7/

PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes

Why do this() and super() have to be the first statement in a constructor?

So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.

Actually you can execute logic with several expessions, you just have to wrap your code in a static function and call it in the super statement.

Using your example:

public class MySubClassC extends MyClass {
    public MySubClassC(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(createList(item));  // OK
    }

    private static List createList(item) {
        List list = new ArrayList();
        list.add(item);
        return list;
    }
}

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

How do I quickly rename a MySQL database (change schema name)?

I posed a question on Server Fault trying to get around downtime when restoring very large databases by using MySQL Proxy. I didn't have any success, but I realized in the end what I wanted was RENAME DATABASE functionality because dump/import wasn't an option due to the size of our database.

There is a RENAME TABLE functionality built in to MySQL so I ended up writing a simple Python script to do the job for me. I've posted it on GitHub in case it could be of use to others.

JFrame: How to disable window resizing?

it's easy to use:

frame.setResizable(false);

How good is Java's UUID.randomUUID?

At a former employer we had a unique column that contained a random uuid. We got a collision the first week after it was deployed. Sure, the odds are low but they aren't zero. That is why Log4j 2 contains UuidUtil.getTimeBasedUuid. It will generate a UUID that is unique for 8,925 years so long as you don't generate more than 10,000 UUIDs/millisecond on a single server.

Finding CN of users in Active Directory

You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.

alt text

Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement namespace, you could also do it programmatically:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.

Or:

UserPrincipal myself = UserPrincipal.Current;

This will give you a UserPrincipal object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!

CSS Animation and Display None

How do I have a div not take up space until it is timed to come in (using CSS for the timing.)

Here is my solution to the same problem.

Moreover I have an onclick on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.

Basically my solution is to keep the div 1 pixel high using a scale(0.001), zooming it when I need it. If you don't like the zoom effect you can restore the opacity to 1 after zooming the slide.

#Slide_TheEnd {

    -webkit-animation-delay: 240s;
    animation-delay: 240s;

    -moz-animation-timing-function: linear;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;

    -moz-animation-duration: 20s;
    -webkit-animation-duration: 20s;
    animation-duration: 20s;

    -moz-animation-name: Slide_TheEnd;
    -webkit-animation-name: Slide_TheEnd;
    animation-name: Slide_TheEnd;

    -moz-animation-iteration-count: 1;
    -webkit-animation-iteration-count: 1;
    animation-iteration-count: 1;

    -moz-animation-direction: normal;
    -webkit-animation-direction: normal;
    animation-direction: normal;

    -moz-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;

    transform: scale(0.001);
    background: #cf0;
    text-align: center;
    font-size: 10vh;
    opacity: 0;
}

@-moz-keyframes Slide_TheEnd {
    0% { opacity: 0;  transform: scale(0.001); }
    10% { opacity: 1; transform: scale(1); }
    95% { opacity: 1; transform: scale(1); }
    100% { opacity: 0;  transform: scale(0.001); }
}

Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.

Copying PostgreSQL database to another server

Accepted answer is correct, but if you want to avoid entering the password interactively, you can use this:

PGPASSWORD={{export_db_password}} pg_dump --create -h {{export_db_host}} -U {{export_db_user}} {{export_db_name}} | PGPASSWORD={{import_db_password}} psql -h {{import_db_host}} -U {{import_db_user}} {{import_db_name}}

Delete default value of an input text on click

Here is an easy way.

#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.

$("#animal").on('click', function(){
    var userVal = $("#animal-value").val(); // storing that value
    console.log(userVal); // logging the stored value to the console
    $("#animal-value").val('') // reseting it to empty
});

IntelliJ IDEA generating serialVersionUID

With version v2018.2.1

Go to

Preference > Editor > Inspections > Java > Serialization issues > toggle "Serializable class without 'serialVersionUID'".

A warning should appear next to the class declaration.

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

how to deal with google map inside of a hidden div (Updated picture)

My solution was:

CSS:

.map {
   height: 400px;
   border: #ccc solid 1px;
}

jQuery:

$('.map').width(555); // width of map canvas

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

Java Pass Method as Parameter

Java do have a mechanism to pass name and call it. It is part of the reflection mechanism. Your function should take additional parameter of class Method.

public void YouMethod(..... Method methodToCall, Object objWithAllMethodsToBeCalled)
{
...
Object retobj = methodToCall.invoke(objWithAllMethodsToBeCalled, arglist);
...
}

How can you get the first digit in an int (C#)?

int myNumber = 8383;
char firstDigit = myNumber.ToString()[0];
// char = '8'

Scroll to bottom of div?

I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:

$("#html, body").stop().animate({
     scrollTop: $("#last-message").offset().top
}, 2000);

I hope this helps someone else.

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

Set default option in mat-select

I would like to add to Narm's answer here and have added the same as a comment under her answer.

Basically the datatype of the value assigned to [(value)] should match the datatype of the [value] attribute used for the mat-options. Especially if some one populates the options using an *ngFor as below

<mat-form-field fxHide.gt-sm='true'>
        <mat-select [(value)]="heroes[0].id">
          <mat-option *ngFor="let hero of heroes" [value]="hero.id">{{ hero.name }}</mat-option>
        </mat-select>
</mat-form-field>

Notice that, if you change the [(value)]="heroes[0].id" to [(value)]="heroes[0].name" it won't work as the data types don't match.

These are my findings, please feel free to correct me if needed.

check android application is in foreground or not?

I don't understand what you want, but You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses() call.

Something like,

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

Also let me know if I misunderstand..

UPDATE: Look at this SO question Determining the current foreground application from a background task or service fore more information..

Thanks..

Gradle, Android and the ANDROID_HOME SDK location

On my system (Ubuntu 20.04 after two version upgrades from 19.04) the symptoms were as if gradle (4.4.1 installed from APT repos) ignored ANDROID_HOME environment variable, while picking up the sdk.dir value from local.properties if I created one.

The reason appeared to have been that java command referred to openjdk version "11.0.7". After I installed openjdk-8-jdk package and did update-alternatives --config java to make the default java be version 8 ("1.8.0_252"), gradle started working as expected.

How do I find which process is leaking memory?

As suggeseted, the way to go is valgrind. It's a profiler that checks many aspects of the running performance of your application, including the usage of memory.

Running your application through Valgrind will allow you to verify if you forget to release memory allocated with malloc, if you free the same memory twice etc.

Where can I find error log files?

This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.


You can get the current log file assigned natively to php on any platform at runtime by using:

ini_get('error_log');

This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.

You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.

hibernate: LazyInitializationException: could not initialize proxy

If you are managing the Hibernate session manually, you may want to look into sessionFactory.getCurrentSession() and associated docs here:

http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html

CSS hide scroll bar, but have element scrollable

You can hide it :

html {
  overflow:   scroll;
}
::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* make scrollbar transparent */
}

For further information, see : Hide scroll bar, but while still being able to scroll

java.lang.Exception: No runnable methods exception in running JUnits

You can also get this if you mix org.junit and org.junit.jupiter annotations inadvertently.

Get current directory name (without full path) in a Bash script

Just use:

pwd | xargs basename

or

basename "`pwd`"

How can I print literal curly-brace characters in a string and also use .format on it?

Python 3.6+ (2017)

In the recent versions of Python one would use f-strings (see also PEP498).

With f-strings one should use double {{ or }}

n = 42  
print(f" {{Hello}} {n} ")

produces the desired

 {Hello} 42

If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

produces

{hello}

Converting ISO 8601-compliant String to java.util.Date

The Jackson-databind library also has ISO8601DateFormat class that does that (actual implementation in ISO8601Utils.

ISO8601DateFormat df = new ISO8601DateFormat();
Date d = df.parse("2010-07-28T22:25:51Z");

Connection pooling options with JDBC: DBCP vs C3P0

Another alternative, Proxool, is mentioned in this article.

You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?

Checking for duplicate strings in JavaScript array

You could take a Set and filter the values who are alreday seen.

_x000D_
_x000D_
var array = ["q", "w", "w", "e", "i", "u", "r"],_x000D_
    seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));_x000D_
_x000D_
console.log(seen);
_x000D_
_x000D_
_x000D_

Get the last item in an array

simple answer

const array = [1,2,3]
array[array.length - 1]

What is the difference between AF_INET and PF_INET in socket programming?

There are situations where it matters.

If you pass AF_INET to socket() in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.

Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.

Looping through the content of a file in Bash

Suppose you have this file:

$ cat /tmp/test.txt
Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR

There are four elements that will alter the meaning of the file output read by many Bash solutions:

  1. The blank line 4;
  2. Leading or trailing spaces on two lines;
  3. Maintaining the meaning of individual lines (i.e., each line is a record);
  4. The line 6 not terminated with a CR.

If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.

Here are the methods that may change the file (in comparison to what cat returns):

1) Lose the last line and leading and trailing spaces:

$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'

(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)

2) Using process substitution with cat will reads the entire file in one gulp and loses the meaning of individual lines:

$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR'

(If you remove the " from $(cat /tmp/test.txt) you read the file word by word rather than one gulp. Also probably not what is intended...)


The most robust and simplest way to read a file line-by-line and preserve all spacing is:

$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'    Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space    '
'Line 6 has no ending CR'

If you want to strip leading and trading spaces, remove the IFS= part:

$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'

(A text file without a terminating \n, while fairly common, is considered broken under POSIX. If you can count on the trailing \n you do not need || [[ -n $line ]] in the while loop.)

More at the BASH FAQ

position fixed header in html

I assume your header is fixed because you want it to stay at the top of the page even when the user scrolls down, but you dont want it covering the container. Setting position: fixed removes the element from the linear layout of the page however, so you would need to either set the top margin of the "next" element to be the same as the height of the header, or (if for whatever reason you don't want to do that), put a placeholder element which takes up space in the page flow, but would appear underneath where the header shows up.

Split list into smaller lists (split in half)

If you don't care about the order...

def split(list):  
    return list[::2], list[1::2]

list[::2] gets every second element in the list starting from the 0th element.
list[1::2] gets every second element in the list starting from the 1st element.

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

How to delete a file after checking whether it exists

  if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
    {
        // Use a try block to catch IOExceptions, to 
        // handle the case of the file already being 
        // opened by another process. 
        try
        {
            System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
            return;
        }
    }

How do I find a default constraint using INFORMATION_SCHEMA?

How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:

    select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name
          from information_schema.columns columns
             inner join information_schema.constraint_column_usage usage on 
                  columns.column_name = usage.column_name and columns.table_name = usage.table_name
             inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name
    where columns.column_default is not null

Using .htaccess to make all .html pages to run as .php files?

On Dreamhost Servers you can refer to this page that at time of writing indicates you may use the following for php 7.2 with FastCGI:

AddHandler fcgid-script .html
FcgidWrapper "/dh/cgi-system/php72.cgi" .html

Or if you are using php5 cgi (not FastCGI):

AddHandler php5-cgi .html

How can I disable selected attribute from select2() dropdown Jquery?

if you want to disable the values of the dropdown

$('select option:not(selected)').prop('disabled', true);

$('select').prop('disabled', true);

How do I get the Session Object in Spring?

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
attr.getSessionId();

Implement Stack using Two Queues

Here is very simple solution which uses one Queue and gives functionality like Stack.

public class CustomStack<T>
{
    Queue<T> que = new Queue<T>();

    public void push(T t) // STACK = LIFO / QUEUE = FIFO
    {

        if( que.Count == 0)
        {
            que.Enqueue(t);
        }
        else
        {
            que.Enqueue(t);
            for (int i = 0; i < que.Count-1; i++)
            {
                var data = que.Dequeue();

                que.Enqueue(data);
            }
        }

    }

    public void pop()
    {

        Console.WriteLine("\nStack Implementation:");
        foreach (var item in que)
        {
            Console.Write("\n" + item.ToString() + "\t");
        }

        var data = que.Dequeue();
        Console.Write("\n Dequeing :" + data);
    }

    public void top()
    {

        Console.Write("\n Top :" + que.Peek());
    }


}

So in the above class named "CustomStack" what I am doing is just checking the queue for empty , if empty then insert one and from then on wards insert and then remove insert. By this logic first will come last. Example : In queue I inserted 1 and now trying to insert 2. Second time remove 1 and again insert so it becomes in reverse order.

Thank you.

Remove old Fragment from fragment manager

I had the same issue. I came up with a simple solution. Use fragment .replace instead of fragment .add. Replacing fragment doing the same thing as adding fragment and then removing it manually.

getFragmentManager().beginTransaction().replace(fragment).commit();

instead of

getFragmentManager().beginTransaction().add(fragment).commit();

Class Not Found Exception when running JUnit test

For me I had to put the project x/src/test/java/ at the bottom of the "order and export" in the "java build path"

enter image description here

How to to send mail using gmail in Laravel?

This is working sample that i have tried :

Open your mail.php under config folder then fill with this option :

'driver'     => env('MAIL_DRIVER', 'smtp'),
'host'       => env('MAIL_HOST', 'smtp.gmail.com'),
'port'       => env('MAIL_PORT', 587),
'from'       => ['address' =>'[email protected]', 'name' => 'Email_Subject'],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username'   => env('MAIL_USERNAME','[email protected]'),
'password'   => env('MAIL_PASSWORD','youremailpassword'),
'sendmail'   => '/usr/sbin/sendmail -bs',

Open your .env file under root project. Also edit this file following above option such

MAIL_DRIVER=smtp    
MAIL_HOST=smtp.gmail.com   
MAIL_PORT=587      
MAIL_USERNAME=youremailusername
MAIL_PASSWORD=youremailpassword
MAIL_ENCRYPTION=tls

After that clear your config by running this command

php artisan config:cache

Restart your local server

Try visit your route with controller contains mail function at first time it still error Authentication Required. You need to login via your gmail account to authorize untrusted connection. Visit this link to authorize

Use of *args and **kwargs

Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:

mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))

I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!

How to use boolean 'and' in Python

The correct operator to be used are the keywords 'or' and 'and', which in your example, the correct way to express this would be:

if i == 5 and ii == 10:
    print "i is 5 and ii is 10"

You can refer the details in the "Boolean Operations" section in the language reference.

What does '<?=' mean in PHP?

As of PHP 5.4.0, <?= ?> are always available even without the short_open_tag set in php.ini.

Furthermore, as of PHP 7.0, The ASP tags: <%, %> and the script tag <script language="php"> are removed from PHP.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

Here is a part of code I use to direct my server.js file to angular dist folder, which was created after npm build

// Create link to Angular build directory
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));

I fixed it by changing "/dist/" to "./dist/"

Using Google Text-To-Speech in Javascript

You can use the SpeechSynthesisUtterance with a function like say:

function say(m) {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[10];
  msg.voiceURI = "native";
  msg.volume = 1;
  msg.rate = 1;
  msg.pitch = 0.8;
  msg.text = m;
  msg.lang = 'en-US';
  speechSynthesis.speak(msg);
}

Then you only need to call say(msg) when using it.

Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.

Why is Git better than Subversion?

Why I think Subversion is better than Git (at least for the projects I work on), mainly due to its usability, and simpler workflow:

http://www.databasesandlife.com/why-subversion-is-better-than-git/

When should I use a List vs a LinkedList

The primary advantage of linked lists over arrays is that the links provide us with the capability to rearrange the items efficiently. Sedgewick, p. 91

How to remove old Docker containers

So, personally I recommend doing this as part of your deploy script for both images and containers, keeping only the most recent n containers and images. I tag my Docker images with the same versioning schema I use with git tag as well as always tagging the latest Docker image with "latest." This means that without cleaning up anything, my Docker images wind up looking like:

REPOSITORY              TAG       IMAGE ID        CREATED         VIRTUAL SIZE
some_repo/some_image    0.0.5     8f1a7c7ba93c    23 hours ago    925.4 MB
some_repo/some_image    latest    8f1a7c7ba93c    23 hours ago    925.4 MB
some_repo/some_image    0.0.4     0beabfa514ea    45 hours ago    925.4 MB
some_repo/some_image    0.0.3     54302cd10bf2    6 days ago      978.5 MB
some_repo/some_image    0.0.2     0078b30f3d9a    7 days ago      978.5 MB
some_repo/some_image    0.0.1     sdfgdf0f3d9a    8 days ago      938.5 MB

Now, of course I don't want to keep all my images (or containers) going back to perpetuity on all my production boxes. I just want the last 3 or 4 for rollbacks and to get rid of everything else. Unix's tail is your best friend here. Since docker images and docker ps both order by date, we can just use tail to select all but the top three and remove them:

docker rmi $(docker images -q | tail -n +4)

Run that along with your deploy scripts (or locally) to always keep just enough images to comfortably roll back without taking up too much room or cluttering stuff up with old images.

Personally, I only keep one container on my production box at any time, but you can do the same sort of thing with containers if you want more:

docker rm $(docker ps -aq | tail -n +4)

Finally, in my simplified example we're only dealing with one repository at a time, but if you had more, you can just get a bit more sophisticated with the same idea. Say I just want to keep the last three images from some_repo/some_image. I can just mix in grep and awk and be on my way:

docker rmi $(docker images -a | grep 'some_repo/some_image' | awk '{print $3}' | tail -n +4)

Again, the same idea applies to containers, but you get it by this point so I'll stop giving examples.

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

why numpy.ndarray is object is not callable in my simple for python loop

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.

Use

Z=XY[0]+XY[1]

Instead of

Z=XY(i,0)+XY(i,1)

WCF gives an unsecured or incorrectly secured fault error

For what it's worth - I also had this error and found it was caused by the connection string in the web services web.config being set to connect to the wrong machine.

How to convert an ArrayList containing Integers to primitive int array?

   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }

Adding a newline into a string in C#

Then just modify the previous answers to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don't want the newlines in the text file, then don't preserve it.

pip installing in global site-packages instead of virtualenv

I hit into the same issue while installing a python package from within a virtualenv. The root cause in my case was different. From within the virtualenv, I was (out of habit on Ubuntu), doing:

sudo easy_install -Z <package>

This caused the bin/pip shebang to be ignored and it used the root's non virtualenv python to install it in the global site-packages. Since we have a virtual environment, we should install the package without "sudo"

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

How do I debug a stand-alone VBScript script?

Export this folder to a backup file and try remove this folder and all the content.

HKEY_CURRENT_USER\Software\Microsoft\Script Debugger

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

What's the difference between "static" and "static inline" function?

In C, static means the function or variable you define can be only used in this file(i.e. the compile unit)

So, static inline means the inline function which can be used in this file only.

EDIT:

The compile unit should be The Translation Unit

jquery: $(window).scrollTop() but no $(window).scrollBottom()

I would say that a scrollBottom as a direct opposite of scrollTop should be:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

Here is a small ugly test that works for me:

// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');

$(window).scroll(function () {
  var st = $(window).scrollTop();
  var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  $('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //

How to yum install Node.JS on Amazon Linux

I had Node.js 6.x installed and wanted to install Node.js 8.x.

Here's the commands I used (taken from Nodejs's site with a few extra steps to handle the yum cached data):

  1. sudo yum remove nodejs: Uninstall Node.js 6.x (I don't know if this was necessary or not)
  2. curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
  3. sudo yum clean all
  4. sudo yum makecache: Regenerate metadata cache (this wasn't in the docs, but yum kept trying to install Node.jx 6.x, unsuccessfully, until I issued these last two commands)
  5. sudo yum install nodejs: Install Node.js 8.x

can't start MySql in Mac OS 10.6 Snow Leopard

  1. Change the following to the file /usr/local/mysql/support-files/mysql.server the follow lines:

    basedir="/usr/local/mysql"
    
    datadir="/usr/local/mysql/data"
    

    and save it.

  2. In the file /etc/rc.common add the follow line at end: /usr/local/mysql/bin/mysqld_safe --user=mysql &

Configuring user and password with Git Bash

If your repo is of HTTPS repo, git config -e give this command in the git bash. Update the username and password by opening in insert mode, change the password or username give :x and Cntrl+z keys it will save and exit

So, From then while you pull / push the code to the repository it will not ask for password.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

How to pass parameters to ThreadStart method in Thread?

How about this: (or is it ok to use like this?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

Android Room - simple select query - Cannot access database on the main thread

For quick queries you can allow room to execute it on UI thread.

AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
        AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();

In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity

       @Override
        public void onClick(View view) {



            int position = getAdapterPosition();

            User user = new User();
            String name = getName(position);
            user.setName(name);

            AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
            UserDao userDao = appDatabase.getUserDao();
            ArrayList<User> users = new ArrayList<User>();
            users.add(user);
            List<Long> ids = userDao.insertAll(users);

            Long id = ids.get(0);
            if(id == -1)
            {
                user = userDao.getUser(name);
                user.setId(user.getId());
            }
            else
            {
                user.setId(id);
            }

            Intent intent = new Intent(mContext, ChatActivity.class);
            intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
            mContext.startActivity(intent);
        }
    }

Focus Input Box On Load

A portable way of doing this is using a custom function (to handle browser differences) like this one.

Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:

window.onload = function() {
  document.getElementById("myinputbox").focus();
}

How to make a div with a circular shape?

By using a border-radius of 50% you can make a circle. Here is an example:

CSS:

#exampleCircle{
    width: 500px;
    height: 500px;
    background: red;
    border-radius: 50%;
}

HTML:

<div id = "exampleCircle"></div>

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Why do we usually use || over |? What is the difference?

In Addition to the fact that | is a bitwise-operator: || is a short-circuit operator - when one element is false, it will not check the others.

 if(something || someotherthing)
 if(something | someotherthing)

if something is TRUE, || will not evaluate someotherthing, while | will do. If the variables in your if-statements are actually function calls, using || is possibly saving a lot of performance.

Is it possible to program iPhone in C++

First off, saying Objective-C is "insane" is humorous- I have the Bjarne Stroustrup C++ book sitting by my side which clocks in at 1020 pages. Apple's PDF on Objective-C is 141.

If you want to use UIKit it will be very, very difficult for you to do anything in C++. Any serious iPhone app that conforms to Apple's UI will need it's UI portions to be written in Objective-C. Only if you're writing an OpenGL game can you stick almost entirely to C/C++.

How to name Dockerfiles

dev.Dockerfile, test.Dockerfile, build.Dockerfile etc.

On VS Code I use <purpose>.Dockerfile and it gets recognized correctly.

How to Add Date Picker To VBA UserForm

Just throw some light in to some issues related to this control.

Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.

In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.

In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.

If you need the file, download MSCOMCT2.OCX from here.

How to determine the current shell I'm working on

Grepping PID from the output of "ps" is not needed, because you can read the respective command line for any PID from the /proc directory structure:

echo $(cat /proc/$$/cmdline)

However, that might not be any better than just simply:

echo $0

About running an actually different shell than the name indicates, one idea is to request the version from the shell using the name you got previously:

<some_shell> --version

sh seems to fail with exit code 2 while others give something useful (but I am not able to verify all since I don't have them):

$ sh --version
sh: 0: Illegal option --
echo $?
2

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Bootstrap.yml is the first file loaded when you start spring boot application and application.property is loaded when application starts. So, you keep, may be your config server's credentials etc., in bootstrap.yml which is required during loading application and then in application.properties you keep may be database URL etc.

How do I pass a unique_ptr argument to a constructor or a function?

tl;dr: Do not use unique_ptr's like that.

I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.

  1. Only take unique_ptr constructor parameters if you have publicly-exposed unique_ptr members.

unique_ptrs wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*> as suggested in the Core Guidelines.

Only if the purpose of your class is to hold unique_ptr's, and have others use those unique_ptr's as such - only then is it reasonable for your constructor or methods to take them.

  1. Don't expose the fact that you use unique_ptrs internally

Using unique_ptr for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.

Populate dropdown select with array using jQuery

Try for loops:

var numbers = [1, 2, 3, 4, 5];

for (var i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}

Much better approach:

var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
   option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

2D cross-platform game engine for Android and iOS?

I've worked with Marmalade and I found it satisfying. Although it's not free and the developer community is also not large enough, but still you can handle most of the task using it's tutorials. (I'll write my tutorials once I got some times too).
IwGame is a good engine, developed by one of the Marmalade user. It's good for a basic game, but if you are looking for some serious advanced gaming stuff, you can also use Cocos2D-x with Marmalade. I've never used Cocos2D-x, but there's an Extension on Marmalade's Github.
Another good thing about Marmalade is it's EDK (Extension Development Kit), which lets you make an extension for whatever functionality you need which is available in native code, but not in Marmalade. I've used it to develop my own Customized Admob extension and a Facebook extension too.

Edit:
Marmalade now has it's own RAD(Rapid Application Development) tool just for 2D development, named as Marmalade Quick. Although the coding will be in Lua not in C++, but since it's built on top of C++ Marmalade, you can easily include a C++ library, and all other EDK extensions. Also the Cocos-2Dx and Box2D extensions are preincluded in the Quick. They recently launched it's Release version (It was in beta for 3-4 months). I think we you're really looking for only 2D development, you should give it a try.

Update:
Unity3D recently launched support for 2D games, which seems better than any other 2D game engine, due to it's GUI and Editor. Physics, sprite etc support is inbuilt. You can have a look on it.

Update 2
Marmalade is going to discontinue their SDK in favor of their in-house game production soon. So it won't be a wise decision to rely on that.

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

Putting an if-elif-else statement on one line?

If you only need different expressions for different cases then this may work for you:

expr1 if condition1 else expr2 if condition2 else expr

For example:

a = "neg" if b<0 else "pos" if b>0 else "zero"

How to run a jar file in a linux commandline

sudo -sH
java -jar filename.jar

Keep in mind to never run executable file in as root.

Run a Command Prompt command from Desktop Shortcut

I tried this, all it did was open a cmd prompt with "cmd -c (my command)" and didn't actually run it. see below.

C:\windows\System32>cmd -c (powercfg /lastwake) Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\windows\System32>

***Update
I changed my .bat file to read "cmd /k (powercfg /lastwake)" and it worked. You can also leave out the () and it works too.

How to retrieve a file from a server via SFTP?

The best solution I've found is Paramiko. There's a Java version.

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Prevent text selection after double click

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}

Does hosts file exist on the iPhone? How to change it?

This doesn't directly answer your question, but it does solve your problem...

What make of router do you have? Your router firmware may allow you to set DNS records for your local network. This is what I do with the Tomato firmware

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

Open another application from your own (intent)

Firstly, the concept of "application" in Android is slightly an extended one.

An application - technically a process - can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running (the process).

So, what you have to identify is how do you want to "start the application".

Ok... here's what you can try out:

  1. Create an intent with action=MAIN and category=LAUNCHER
  2. Get the PackageManager from the current context using context.getPackageManager
  3. packageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcher
  4. Get theActivityInfo you're interested in
  5. From the ActivityInfo, get the packageName and name
  6. Finally, create another intent with with category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  7. Finally, context.startActivity(newIntent)

Error: 'int' object is not subscriptable - Python

When you type x = 0 that is creating a new int variable (name) and assigning a zero to it.

When you type x[age1] that is trying to access the age1'th entry, as if x were an array.

Sorting an array of objects by property values

For sorting a array you must define a comparator function. This function always be different on your desired sorting pattern or order(i.e. ascending or descending).

Let create some functions that sort an array ascending or descending and that contains object or string or numeric values.

function sorterAscending(a,b) {
    return a-b;
}

function sorterDescending(a,b) {
    return b-a;
}

function sorterPriceAsc(a,b) {
    return parseInt(a['price']) - parseInt(b['price']);
}

function sorterPriceDes(a,b) {
    return parseInt(b['price']) - parseInt(b['price']);
}

Sort numbers (alphabetically and ascending):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Sort numbers (alphabetically and descending):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

Sort numbers (numerically and ascending):

var points = [40,100,1,5,25,10];
points.sort(sorterAscending());

Sort numbers (numerically and descending):

var points = [40,100,1,5,25,10];
points.sort(sorterDescending());

As above use sorterPriceAsc and sorterPriceDes method with your array with desired key.

homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())

Wait for a process to finish

There is no builtin feature to wait for any process to finish.

You could send kill -0 to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps (while still retrieving the PID list using ps).

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Disclaimer- The main source of some definitions are wikipedia, any suggestion to improve my answer is welcome.

Although this post has an accepted answer and is a good one I was still in confusion and would like to add some more clarification regarding the difference between these terms.

(1)FULL BINARY TREE- A full binary tree is a binary tree in which every node other than the leaves has two children.This is also called strictly binary tree.

enter image description here enter image description here

The above two are the examples of full or strictly binary tree.

(2)COMPLETE BINARY TREE- Now, the definition of complete binary tree is quite ambiguous, it states :- A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. It can have between 1 and 2h nodes, as far left as possible, at the last level h

Notice the lines in italic.

The ambiguity lies in the lines in italics , "except possibly the last" which means that the last level may also be completely filled , i.e this exception need not always be satisfied. If the exception doesn't hold then it is exactly like the second image I posted, which can also be called as perfect binary tree. So, a perfect binary tree is also full and complete but not vice-versa which will be clear by one more definition I need to state:

ALMOST COMPLETE BINARY TREE- When the exception in the definition of complete binary tree holds then it is called almost complete binary tree or nearly complete binary tree . It is just a type of complete binary tree itself , but a separate definition is necessary to make it more unambiguous.

So an almost complete binary tree will look like this, you can see in the image the nodes are as far left as possible so it is more like a subset of complete binary tree , to say more rigorously every almost complete binary tree is a complete binary tree but not vice versa . :

enter image description here

Proper way of checking if row exists in table in PL/SQL block

Many ways to skin this cat. I put a simple function in each table's package...

function exists( id_in in yourTable.id%type ) return boolean is
  res boolean := false;
begin
  for c1 in ( select 1 from yourTable where id = id_in and rownum = 1 ) loop
    res := true;
    exit; -- only care about one record, so exit.
  end loop;
  return( res );
end exists;

Makes your checks really clean...

IF pkg.exists(someId) THEN
...
ELSE
...
END IF;

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How do I record audio on iPhone with AVAudioRecorder?

I have uploaded a sample project. You can take a look.

VoiceRecorder

How to convert FileInputStream to InputStream?

InputStream is = new FileInputStream("c://filename");
return is;

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Use dynamic linq

just add using System.Linq.Dynamic;

And use it like this to order all your columns:

string sortTypeStr = "ASC"; // or DESC
string SortColumnName = "Age"; // Your column name
query = query.OrderBy($"{SortColumnName} {sortTypeStr}");

Exit a while loop in VBS/VBA

Use Do...Loop with Until keyword

num=0
Do Until //certain_condition_to_break_loop
 num=num+1
Loop

This loop will continue to execute, Until the condition becomes true

While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops

Ping with timestamp on Windows CLI

I also need this to monitor the network issue for my database mirroring time out issue. I use the command code as below:

ping -t Google.com|cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 Google.com>nul" >C:\pingtest.txt

You just need to modify Google.com to your server name. It works perfectly for me. and remember to stop this when you finished. The pingtest.txt file will increase by 4.5 KB per min (around).

Thank for raymond.cc. https://www.raymond.cc/blog/timestamp-ping-with-hrping/

Truncate a string straight JavaScript

Use the substring method:

var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
// The value of myTruncatedString is "ABC"

So in your case:

var length = 3;  // set to the number of characters you want to keep
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));

document.getElementById("foo").innerHTML =
     "<a href='" + pathname +"'>" + trimmedPathname + "</a>"

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

How to determine if binary tree is balanced?

What kind of tree are you talking about? There are self-balancing trees out there. Check their algorithms where they determine if they need to reorder the tree in order to maintain balance.

How can I retrieve Id of inserted entity using Entity framework?

You can get ID only after saving, instead you can create a new Guid and assign before saving.

Fixed size div?

.myDiv { height: 150px; width 150px; }

<div class="mainDiv">
   <div class="myDiv"></div>
   <div class="myDiv"></div>
   <div class="myDiv"></div>
</div>

Click a button programmatically

The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.

Parsing boolean values with argparse

I think the most canonical way will be:

parser.add_argument('--ensure', nargs='*', default=None)

ENSURE = config.ensure is None

Efficient way to insert a number into a sorted array of numbers?

TypeScript version with custom compare method:

const { compare } = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: "base"
});

const insert = (items: string[], item: string) => {
    let low = 0;
    let high = items.length;

    while (low < high) {
        const mid = (low + high) >> 1;
        compare(items[mid], item) > 0
            ? (high = mid)
            : (low = mid + 1);
    }

    items.splice(low, 0, item);
};

Use:

const items = [];

insert(items, "item 12");
insert(items, "item 1");
insert(items, "item 2");
insert(items, "item 22");

console.log(items);

// ["item 1", "item 2", "item 12", "item 22"]

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

How to get first character of a string in SQL?

Select First two Character in selected Field with Left(string,Number of Char in int)

SELECT LEFT(FName, 2) AS FirstName FROM dbo.NameMaster

Run Python script at startup in Ubuntu

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!

How to insert a string which contains an "&"

An alternate solution, use concatenation and the chr function:

select 'J' || chr(38) || 'J Construction' from dual;

How to write lists inside a markdown table?

If you want a no-bullet list (or any other non-standard usage) or more lines in a cell use <br />

| Event         | Platform      | Description |
| ------------- |-----------| -----:|
| `message_received`| `facebook-messenger`<br/>`skype`|