Programs & Examples On #Machg

MacHg is a free open source OS X GUI for the distributed revision control system Mercurial.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
   return{
      exampleProperty: exampleValue 
   }
}

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

Fatal error: "No Target Architecture" in Visual Studio

At the beginning of the file you are compiling, before any include, try to put ONE of these lines

#define _X86_
#define _AMD64_
#define _ARM_

Choose the appropriate, only one, depending on your architecture.

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

Split Java String by New Line

In JDK11 the String class has a lines() method:

Returning a stream of lines extracted from this string, separated by line terminators.

Further, the documentation goes on to say:

A line terminator is one of the following: a line feed character "\n" (U+000A), a carriage return character "\r" (U+000D), or a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A). A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

With this one can simply do:

Stream<String> stream = str.lines();

then if you want an array:

String[] array = str.lines().toArray(String[]::new);

Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.

Create a SQL query to retrieve most recent records

another way, this will scan the table only once instead of twice if you use a subquery

only sql server 2005 and up

select Date, User, Status, Notes 
from (
       select m.*, row_number() over (partition by user order by Date desc) as rn
       from [SOMETABLE] m
     ) m2
where m2.rn = 1;

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

How do I read any request header in PHP

This small PHP snippet can be helpful to you:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

import operator, functools
def product(xs):
    return functools.reduce(operator.mul, xs, 1)

On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

def product(xs):
    result = 1
    for i in xs:
        result *= i
    return result

Nginx location priority

Locations are evaluated in this order:

  1. location = /path/file.ext {} Exact match
  2. location ^~ /path/ {} Priority prefix match -> longest first
  3. location ~ /Paths?/ {} (case-sensitive regexp) and location ~* /paths?/ {} (case-insensitive regexp) -> first match
  4. location /path/ {} Prefix match -> longest first

The priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.

For both prefix matche types the longest match wins.

Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.

Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.

Is Unit Testing worth the effort?

I didn't see this in any of the other answers, but one thing I noticed is that I could debug so much faster. You don't need to drill down through your app with just the right sequence of steps to get to the code your fixing, only to find you've made a boolean error and need to do it all again. With a unit test, you can just step directly into the code you're debugging.

EF Core add-migration Build Failed

I had the same problem when running: dotnet ef migrations add InitialCreate so what I did is tried to build the project using: dotnet build command.

It throws an error : Startup.cs(20,27): error CS0103: bla bla for example. which you can trace to find the error in your code.

Then i refactored the code and ran: dotnet build again to check any errors until there is no errors and build is succeded. Then ran: dotnet ef migrations add InitialCreate then the build succeded.

single line comment in HTML

No, <!-- ... --> is the only comment syntax in HTML.

Android set bitmap to Imageview

    //decode base64 string to image
    imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    image.setImageBitmap(decodedImage);

  //setImageBitmap is imp

Swipe ListView item From right to left show delete button

see there link was very nice and simple. its working fine... u don't want any library its working fine. click here

OnTouchListener gestureListener = new View.OnTouchListener() {
    private int padding = 0;
    private int initialx = 0;
    private int currentx = 0;
    private  ViewHolder viewHolder;

    public boolean onTouch(View v, MotionEvent event) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN) {
            padding = 0;
            initialx = (int) event.getX();
            currentx = (int) event.getX();
            viewHolder = ((ViewHolder) v.getTag());
        }
        if ( event.getAction() == MotionEvent.ACTION_MOVE) {
            currentx = (int) event.getX();
            padding = currentx - initialx;
        }       
        if ( event.getAction() == MotionEvent.ACTION_UP || 
                     event.getAction() == MotionEvent.ACTION_CANCEL) {
            padding = 0;
            initialx = 0;
            currentx = 0;
        }
        if(viewHolder != null) {
            if(padding == 0) {
                v.setBackgroundColor(0xFF000000 );  
                if(viewHolder.running)
                    v.setBackgroundColor(0xFF058805);
            }
            if(padding > 75) {
                viewHolder.running = true;
                v.setBackgroundColor(0xFF00FF00 );  
                viewHolder.icon.setImageResource(R.drawable.clock_running);
            }
            if(padding < -75) {
                viewHolder.running = false;
                v.setBackgroundColor(0xFFFF0000 );  
            }

            v.setPadding(padding, 0,0, 0);
        }

        return true;
    }
};

Removing array item by value

w/o flip:

<?php
foreach ($items as $key => $value) {
    if ($id === $value) {
        unset($items[$key]);
    }
}

Better way to find control in ASP.NET

All the highlighted solutions are using recursion (which is performance costly). Here is cleaner way without recursion:

public T GetControlByType<T>(Control root, Func<T, bool> predicate = null) where T : Control 
{
    if (root == null) {
        throw new ArgumentNullException("root");
    }

    var stack = new Stack<Control>(new Control[] { root });

    while (stack.Count > 0) {
        var control = stack.Pop();
        T match = control as T;

        if (match != null && (predicate == null || predicate(match))) {
            return match;
        }

        foreach (Control childControl in control.Controls) {
           stack.Push(childControl);
        }
    }

    return default(T);
}

How can I add a custom HTTP header to ajax request with js or jQuery?

Here's an example using XHR2:

function xhrToSend(){
    // Attempt to creat the XHR2 object
    var xhr;
    try{
        xhr = new XMLHttpRequest();
    }catch (e){
        try{
            xhr = new XDomainRequest();
        } catch (e){
            try{
                xhr = new ActiveXObject('Msxml2.XMLHTTP');
            }catch (e){
                try{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }catch (e){
                    statusField('\nYour browser is not' + 
                        ' compatible with XHR2');                           
                }
            }
        }
    }
    xhr.open('POST', 'startStopResume.aspx', true);
    xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            receivedChunks++;
        }
    };
    xhr.send(chunk);
    numberOfBLObsSent++;
}; 

Hope that helps.

If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How can building a heap be O(n) time complexity?

Lets suppose you have N elements in a heap. Then its height would be Log(N)

Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.

Now you are having N+1 elements & height = Log(N+1)

Using induction technique it can be proved that the complexity of insertion would be ?logi.

Now using

log a + log b = log ab

This simplifies to : ?logi=log(n!)

which is actually O(NlogN)

But

we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.

This realization came to me after a detail though & experimentation on Heaps.

Passing data between controllers in Angular JS?

There are three ways to do it,

a) using a service

b) Exploiting depending parent/child relation between controller scopes.

c) In Angular 2.0 "As" keyword will be pass the data from one controller to another.

For more information with example, Please check the below link:

http://www.tutorial-points.com/2016/03/angular-js.html

How do I store an array in localStorage?

The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.

at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).

Base64: java.lang.IllegalArgumentException: Illegal character

I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....

This answer led me to the solution:

String partSeparator = ",";
if (data.contains(partSeparator)) {
  String encodedImg = data.split(partSeparator)[1];
  byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
  Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
  Files.write(destinationFile, decodedImg);
}

How to get the month name in C#?

Use the "MMMM" format specifier:

string month = dateTime.ToString("MMMM");

Change URL and redirect using jQuery

Try this...

$("#abc").attr("action", "/yourapp/" + temp).submit();

What it means:

Find a form with id "abc", change it's attribute named "action" and then submit it...

This works for me... !!!

Using the slash character in Git branch name

Sometimes that problem occurs if you already have a branch with the base name.

I tried this:

git checkout -b features/aName origin/features/aName

Unfortunately, I already had a branch named features, and I got the exception of the question asker.

Removing the branch features resolved the problem, the above command worked.

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

How do I get the current date and time in PHP?

its very simple

echo $date = date('Y-m-d H:i:s');

Gson: Directly convert String to JsonObject (no POJO)

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

How to comment/uncomment in HTML code

My view templates are generally .php files. This is what I would be using for now.

<?php // Some comment here ?>

The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.

Xcode 6 Bug: Unknown class in Interface Builder file

Check if your class has right Target Membership.

Replacing column values in a pandas DataFrame

You can edit a subset of a dataframe by using loc:

df.loc[<row selection>, <column selection>]

In this case:

w.loc[w.female != 'female', 'female'] = 0
w.loc[w.female == 'female', 'female'] = 1

Batch file to copy files from one folder to another folder

If you want to copy file not using absolute path, relative path in other words:

Don't forget to write backslash in the path AND NOT slash

Example:

copy children-folder\file.something .\other-children-folder

PS: absolute path can be retrieved using these wildcards called "batch parameters"

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

Check documentation here about copy: https://technet.microsoft.com/en-us/library/bb490886.aspx

And also here for batch parameters documentation: https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

Convert numpy array to tuple

Another option

tuple([tuple(row) for row in myarray])

If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.

C++, What does the colon after a constructor mean?

This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++

What uses are there for "placement new"?

Here is the killer use for the C++ in-place constructor: aligning to a cache line, as well as other powers of 2 boundaries. Here is my ultra-fast pointer alignment algorithm to any power of 2 boundaries with 5 or less single-cycle instructions:

/* Quickly aligns the given pointer to a power of two boundary IN BYTES.
@return An aligned pointer of typename T.
@brief Algorithm is a 2's compliment trick that works by masking off
the desired number in 2's compliment and adding them to the
pointer.
@param pointer The pointer to align.
@param boundary_byte_count The boundary byte count that must be an even
power of 2.
@warning Function does not check if the boundary is a power of 2! */
template <typename T = char>
inline T* AlignUp(void* pointer, uintptr_t boundary_byte_count) {
  uintptr_t value = reinterpret_cast<uintptr_t>(pointer);
  value += (((~value) + 1) & (boundary_byte_count - 1));
  return reinterpret_cast<T*>(value);
}

struct Foo { Foo () {} };
char buffer[sizeof (Foo) + 64];
Foo* foo = new (AlignUp<Foo> (buffer, 64)) Foo ();

Now doesn't that just put a smile on your face (:-). I ??? C++1x

How to 'update' or 'overwrite' a python list

I think it is more pythonic:

aList.remove(123)
aList.insert(0, 2014)

more useful:

def shuffle(list, to_delete, to_shuffle, index):
    list.remove(to_delete)
    list.insert(index, to_shuffle)
    return

list = ['a', 'b']
shuffle(list, 'a', 'c', 0)
print list
>> ['c', 'b']

How to find the statistical mode?

I would use the density() function to identify a smoothed maximum of a (possibly continuous) distribution :

function(x) density(x, 2)$x[density(x, 2)$y == max(density(x, 2)$y)]

where x is the data collection. Pay attention to the adjust paremeter of the density function which regulate the smoothing.

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

error: RPC failed; curl transfer closed with outstanding read data remaining

This problem usually occurs while cloning large repos. If git clone http://github.com/large-repository --depth 1 does not work on windows cmd. Try running the command in windows powershell.

Is Secure.ANDROID_ID unique for each device?

There are multiple solution exist but none of them perfect. let's go one by one.

1. Unique Telephony Number (IMEI, MEID, ESN, IMSI)

  • This solution needs to request for android.permission.READ_PHONE_STATE to your user which can be hard to justify following the type of application you have made.

  • Furthermore, this solution is limited to smartphones because tablets don’t have telephony services. One advantage is that the value survives to factory resets on devices.

2. MAC Address

  • You can also try to get a MAC Address from a device having a Wi-Fi or Bluetooth hardware. But, this solution is not recommended because not all of the device have Wi-Fi connection. Even if the user have a Wi-Fi connection, it must be turned on to retrieve the data. Otherwise, the call doesn’t report the MAC Address.

3. Serial Number

  • Devices without telephony services like tablets must report a unique device ID that is available via android.os.Build.SERIAL since Android 2.3 Gingerbread. Some phones having telephony services can also define a serial number. Like not all Android devices have a Serial Number, this solution is not reliable.

4. Secure Android ID

  • On a device first boot, a randomly value is generated and stored. This value is available via Settings.Secure.ANDROID_ID . It’s a 64-bit number that should remain constant for the lifetime of a device. ANDROID_ID seems a good choice for a unique device identifier because it’s available for smartphones and tablets.

    String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
    
  • However, the value may change if a factory reset is performed on the device. There is also a known bug with a popular handset from a manufacturer where every instance have the same ANDROID_ID. Clearly, the solution is not 100% reliable.

5. Use UUID

  • As the requirement for most of applications is to identify a particular installation and not a physical device, a good solution to get unique id for an user if to use UUID class. The following solution has been presented by Reto Meier from Google in a Google I/O presentation :

    private static String uniqueID = null;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
    public synchronized static String id(Context context) {
       if (uniqueID == null) {
           SharedPreferences sharedPrefs = context.getSharedPreferences(
                   PREF_UNIQUE_ID, Context.MODE_PRIVATE);
           uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
           if (uniqueID == null) {
               uniqueID = UUID.randomUUID().toString();
               Editor editor = sharedPrefs.edit();
               editor.putString(PREF_UNIQUE_ID, uniqueID);
               editor.commit();
           }
       }    return uniqueID;
    }
    

Identify a particular device on Android is not an easy thing. There are many good reasons to avoid that. Best solution is probably to identify a particular installation by using UUID solution. credit : blog

What is the difference between DAO and Repository patterns?

Repository are nothing but well-designed DAO.

ORM are table centric but not DAO.

There's no need to use several DAO in repository since DAO itself can do exactly the same with ORM repositories/entities or any DAL provider, no matter where and how a car is persisted 1 table, 2 tables, n tables, half a table, a web service, a table and a web service etc. Services uses several DAO/repositories.

My own DAO, let's say CarDao only deal with Car DTO,I mean, only take Car DTO in input and only return car DTO or car DTO collections in output.

So just like Repository, DAO actually is an IoC, for the business logic, allowing persitence interfaces not be be intimidated by persitence strategies or legacies. DAO both encapsulates the persistence strategy and does provide the domaine-related persitence interface. Repository is just an another word for those who had not understood what a well-defined DAO actualy was.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

The

(condition) ? /* value to return if condition is true */ 
            : /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

Reading a huge .csv file

If you are using pandas and have lots of RAM (enough to read the whole file into memory) try using pd.read_csv with low_memory=False, e.g.:

import pandas as pd
data = pd.read_csv('file.csv', low_memory=False)

How to escape a JSON string to have it in a URL?

I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.

Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing ='s. Example:

JSON array-of-strings:

["option", "Fred's dog", "Bill & Trudy", "param=3"]

That data, URL-encoded as the data param:

"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"

Same, base64-encoded:

"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"

The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded % signs and so on. Base64 is very neutral because it doesn't use special characters.

Android webview & localStorage

setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

Change a web.config programmatically with C# (.NET)

This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"]; and then set a new value with config.ConnectionString = "your connection string";. Note that if you have any comments in the connectionStrings section in Web.Config these will be removed.

private void UpdateAppSettings(string key, string value)
{
    System.Configuration.Configuration configFile = null;
    if (System.Web.HttpContext.Current != null)
    {
        configFile =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    }
    else
    {
        configFile =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }
    var settings = configFile.AppSettings.Settings;
    if (settings[key] == null)
    {
        settings.Add(key, value);
    }
    else
    {
        settings[key].Value = value;
    }
    configFile.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}

Running npm command within Visual Studio Code

On Win10 I had to run VSCode as administrator to npm commands work.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

How can I get the nth character of a string?

Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];

...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

str = str + 1; // makes it point to 'E' now
char myChar =  *str;

I hope this helps.

How to zip a file using cmd line?

Yes, we can zip and unzip the file/folder using cmd. See the below command and simply you can copy past in cmd and change the directory and file name

To Zip/Compress File
powershell Compress-Archive D:\Build\FolderName D:\Build\FolderName.zip

To Unzip/Expand File
powershell expand-archive D:\Build\FileName.zip D:\deployments\FileName

ORA-30926: unable to get a stable set of rows in the source tables

SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 -  "unable to get a stable set of rows in the source tables"
*Cause:    A stable set of rows could not be got because of large dml
           activity or a non-deterministic where clause.
*Action:   Remove any non-deterministic where clauses and reissue the dml.

This Error occurred for me because of duplicate records(16K)

I tried with unique it worked .

but again when I tried merge without unique same proble occurred Second time it was due to commit

after merge if commit is not done same Error will be shown.

Without unique, Query will work if commit is given after each merge operation.

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

MongoDB vs. Cassandra

Lots of reads in every query, fewer regular writes

Both databases perform well on reads where the hot data set fits in memory. Both also emphasize join-less data models (and encourage denormalization instead), and both provide indexes on documents or rows, although MongoDB's indexes are currently more flexible.

Cassandra's storage engine provides constant-time writes no matter how big your data set grows. Writes are more problematic in MongoDB, partly because of the b-tree based storage engine, but more because of the multi-granularity locking it does.

For analytics, MongoDB provides a custom map/reduce implementation; Cassandra provides native Hadoop support, including for Hive (a SQL data warehouse built on Hadoop map/reduce) and Pig (a Hadoop-specific analysis language that many think is a better fit for map/reduce workloads than SQL). Cassandra also supports use of Spark.

Not worried about "massive" scalability

If you're looking at a single server, MongoDB is probably a better fit. For those more concerned about scaling, Cassandra's no-single-point-of-failure architecture will be easier to set up and more reliable. (MongoDB's global write lock tends to become more painful, too.) Cassandra also gives a lot more control over how your replication works, including support for multiple data centers.

More concerned about simple setup, maintenance and code

Both are trivial to set up, with reasonable out-of-the-box defaults for a single server. Cassandra is simpler to set up in a multi-server configuration since there are no special-role nodes to worry about.

If you're presently using JSON blobs, MongoDB is an insanely good match for your use case, given that it uses BSON to store the data. You'll be able to have richer and more queryable data than you would in your present database. This would be the most significant win for Mongo.

How to query MongoDB with "like"?

Use regular expressions matching as below. The 'i' shows case insensitivity.

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);

Align button at the bottom of div using CSS

CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>

Necessary CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}

Screenshot:

Output Image

Useful Resources:

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
body {_x000D_
  background: linear-gradient(orange, yellow);_x000D_
  font: 14px/18px Arial, sans-serif;_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  display: flex;_x000D_
  padding: 10px;_x000D_
}_x000D_
.container .btn-holder {_x000D_
  justify-content: flex-end;_x000D_
  display: flex;_x000D_
}_x000D_
.container .btn-holder button {_x000D_
  padding: 10px 25px;_x000D_
  background: blue;_x000D_
  font-size: 16px;_x000D_
  border: none;_x000D_
  color: #fff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
  <div class="btn-holder">_x000D_
    <button type="button">Click</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to save a list as numpy array in python?

First of all, I'd recommend you to go through NumPy's Quickstart tutorial, which will probably help with these basic questions.

You can directly create an array from a list as:

import numpy as np
a = np.array( [2,3,4] )

Or from a from a nested list in the same way:

import numpy as np
a = np.array( [[2,3,4], [3,4,5]] )

Batch file. Delete all files and folders in a directory

Use:

  • Create a batch file

  • Copy the below text into the batch file

    set folder="C:\test"
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
    

It will delete all files and folders.

How to remove extension from string (only real extension!)

As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me...

function string_pop($string, $delimiter){
    $a = explode($delimiter, $string);
    array_pop($a);
    return implode($delimiter, $a);
}

Usage:

$filename = "pic.of.my.house.jpeg";
$name = string_pop($filename, '.');
echo $name;

Outputs:

pic.of.my.house  (note it leaves valid, non-extension "." characters alone)

In action:

http://sandbox.onlinephpfunctions.com/code/5d12a96ea548f696bd097e2986b22de7628314a0

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

string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York

How to find where gem files are installed

if you are using rvm tool you can run this command to print gem path:

rvm gemdir

OR

echo $GEM_HOME

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Removing first x characters from string?

>>> text = 'lipsum'
>>> text[3:]
'sum'

See the official documentation on strings for more information and this SO answer for a concise summary of the notation.

Java check if boolean is null

A boolean cannot be null in java.

A Boolean, however, can be null.

If a boolean is not assigned a value (say a member of a class) then it will be false by default.

How to get the first word of a sentence in PHP?

Just in case you are not sure the string starts with a word...

$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test

C++, How to determine if a Windows Process is running?

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

/*!
\brief Check if a process is running
\param [in] processName Name of process to check if is running
\returns \c True if the process is running, or \c False if the process is not running
*/
bool IsProcessRunning(const wchar_t *processName)
{
    bool exists = false;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry))
        while (Process32Next(snapshot, &entry))
            if (!wcsicmp(entry.szExeFile, processName))
                exists = true;

    CloseHandle(snapshot);
    return exists;
}

How do I test which class an object is in Objective-C?

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

or

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

Arduino error: does not name a type?

Usually Header file syntax start with capital letter.I found that code written all in smaller letter

#ifndef DIAG_H
#define DIAG_H

#endif

Make anchor link go some pixels above where it's linked to

Using only css and having no problems with covered and unclickable content before (the point of this is the pointer-events:none):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

It seems that the queries are not exactly the same. At least for MySQL.

Compare:

  1. describe select distinct productname from northwind.products
  2. describe select productname from northwind.products group by productname

The second query gives additionally "Using filesort" in Extra.

HTML - how can I show tooltip ONLY when ellipsis is activated

I created a jQuery plugin that uses Bootstrap's tooltip instead of the browser's build-in tooltip. Please note that this has not been tested with older browser.

JSFiddle: https://jsfiddle.net/0bhsoavy/4/

$.fn.tooltipOnOverflow = function(options) {
    $(this).on("mouseenter", function() {
    if (this.offsetWidth < this.scrollWidth) {
        options = options || { placement: "auto"}
        options.title = $(this).text();
      $(this).tooltip(options);
      $(this).tooltip("show");
    } else {
      if ($(this).data("bs.tooltip")) {
        $tooltip.tooltip("hide");
        $tooltip.removeData("bs.tooltip");
      }
    }
  });
};

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue and did all the tips including Gmail setting (e.g. less secure apps access) with no luck. But finally when I changed password to something different, for some reason it worked! FYI, the initial password did not have any special characters.

Copy file or directories recursively in Python

shutil.copy and shutil.copy2 are copying files.

shutil.copytree copies a folder with all the files and all subfolders. shutil.copytree is using shutil.copy2 to copy the files.

So the analog to cp -r you are saying is the shutil.copytree because cp -r targets and copies a folder and its files/subfolders like shutil.copytree. Without the -r cp copies files like shutil.copy and shutil.copy2 do.

Bootstrap datepicker disabling past dates without current date

<script type="text/javascript">
$('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    todayHighlight:'TRUE',
    startDate: '-0d',
    autoclose: true,
})

Android: Clear Activity Stack

I noted that you asked for a solution that does not rely on finish(), but I wonder if this may help nonetheless.

I tracked whether an exit flag is raised with a static class variable, which survives the entire app lifespan. In each relevant activity's onResume(), use

@Override
public void onResume() {
    super.onResume();
    if (ExitHelper.isExitFlagRaised) {
        this.finish();
    }
}

The ExitHelper class

public class ExitHelper {
    public static boolean isExitFlagRaised = false;
}

Let's say in mainActivity, a user presses a button to exit - you can set ExitHelper.isExitFlagRaised = true; and then finish(). Thereafter, other relevant activities that are resumed automatically will be finished as well.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

So, we have a project with one solution that contains several projects that have assemblies with different version numbers.

After investigating several of the above methods, I just implemented a build step to run a Powershell script that does a find-and-replace on the AssemblyInfo.cs file. I still use the 1.0.* version number in source control, and Jenkins just manually updates the version number before msbuild runs.

dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }
dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyFileVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyFileVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }

I added the -Encoding "UTF8" option because git started treating the .cs file as binary files if I didn't. Granted, this didn't matter, since I never actually commit the result; it just came up as I was testing.

Our CI environment already has a facility to associate the Jenkins build with the particular git commit (thanks Stash plugin!), so I don't worry that there's no git commit with the version number attached to it.

Purpose of a constructor in Java?

A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor.

Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable?

public class C {
     private int number;

     public C(int number) {
        setNumber(number);
     }

     public void setNumber(int number) {
        if (number < 1) {
            throws IllegalArgumentException("C cannot store anything smaller than 1");
        }
        this.number = number;
     }
}

In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what.

"initialize the instances of a class" is what a constructor does, but not the reason why we have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10) in the example above. So a constructor is not the only way to initialize instances.

The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design.

Here is another example:

public class Interval {
    private long start;
    private long end;

    public Interval(long start, long end) {
        changeInterval(start, end);
    }

    public void changeInterval(long start, long end) {
        if (start >= end) {
            throw new IllegalArgumentException("Invalid interval.");
        }
        this.start = start;
        this.end = end;
    }
    public long duration() {
        return end - start;
    }
}

The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense.

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

How to use '-prune' option of 'find' in sh?

find builds a list of files. It applies the predicate you supplied to each one and returns those that pass.

This idea that -prune means exclude from results was really confusing for me. You can exclude a file without prune:

find -name 'bad_guy' -o -name 'good_guy' -print  // good_guy

All -prune does is alter the behavior of the search. If the current match is a directory, it says "hey find, that file you just matched, dont descend into it". It just removes that tree (but not the file itself) from the list of files to search.

It should be named -dont-descend.

How to raise a ValueError?

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

def contains(char_string, char):
    largest_index = -1
    for i, ch in enumerate(char_string):
        if ch == char:
            largest_index = i
    if largest_index > -1:  # any found?
        return largest_index  # return index of last one
    else:
        raise ValueError('could not find {!r} in {!r}'.format(char, char_string))

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "how-to-raise-a-valueerror.py", line 15, in <module>
    print(contains('bababa', 'k'))
  File "how-to-raise-a-valueerror.py", line 12, in contains
    raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with a quick unit test:

def contains(char_string, char):
    #  Ending - 1 adjusts returned index to account for searching in reverse.
    return len(char_string) - char_string[::-1].index(char) - 1

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "better-way-to-raise-a-valueerror.py", line 9, in <module>
    print(contains('bababa', 'k'))
  File "better-way-to-raise-a-valueerror", line 6, in contains
    return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found

What is SaaS, PaaS and IaaS? With examples

Here is another take with AWS Example of each service:

IaaS (Infrastructure as a Service): You get the whole infrastructure with hardware. You chose the type of OS that needs to be installed. You will have to install the necessary software.

AWS Example: EC2 which has only the hardware and you select the base OS to be installed. If you want to install Hadoop on that you have to do it yourself, it's just the base infrastructure AWS has provided.

PaaS (Platform as a Service): Provides you the infrastructure with OS and necessary base software. You will have to run your scripts to get the desired output.

AWS Example: EMR Which has the hardware (EC2) + Base OS + Hadoop software already installed. You will have to run hive/spark scripts to query tables and get results. You will need to invoke the instance and wait for 10 min for the setup to be ready. You have to take care of how many clusters you need based on the jobs you are running, but not worry about the cluster configuration.

SaaS (Software as a Service): You don't have to worry about Hardware or even Software. Everything will be installed and available for you to use instantly.

AWS Example: Athena, which is just a UI for you to query tables in S3 (with metadata stored in Glu). Just open the browser login to AWS and start running your queries, no worry about RAM/Storage/CPU/number of clusters, everything the cloud takes care of.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END

SQL - select distinct only on one column

Since you don't care, I chose the max ID for each number.

select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id

Query Explanation

 select 
    tbl.*  -- give me all the data from the base table (tbl) 
 from 
    tbl    
    inner join (  -- only return rows in tbl which match this subquery
        select 
            max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
        from 
            tbl 
        group by 
            NUMBER            -- how to group rows for the MAX aggregation
    ) maxID
        on maxID.maxID = tbl.id -- join condition ie only return rows in tbl 
                                -- whose ID is also a MAX ID for a given NUMBER

How can I save a base64-encoded image to disk?

I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.

Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the data: scheme prefix.

Here's an example:

var ba64 = require("ba64"),
    data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";

// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.

// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
    if (err) throw err;

    console.log("Image saved successfully");

    // do stuff
});

Install it: npm i ba64 -S. Repo is on GitHub: https://github.com/HarryStevens/ba64.

P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.

Detect changed input text box

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});

Set Content-Type to application/json in jsp file

@Petr Mensik & kensen john

Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

    <%
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("UTF-8");
        if (callback != null) {
            // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
            response.setContentType("text/javascript");
        } else {
            // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
            response.setContentType("application/json");
        }

        [...]

        String output = "";

        if (callback != null) {
            output += callback + "(";
        }

        output += jsonObj.toString();

        if (callback != null) {
            output += ");";
        }
    %>
    <%=output %>

When callback is supplied, returns:

    callback({...JSON stuff...});

with content-type "text/javascript"

When callback is NOT supplied, returns:

    {...JSON stuff...}

with content-type "application/json"

Inserting a PDF file in LaTeX

Use the pdfpages package.

\usepackage{pdfpages}

To include all the pages in the PDF file:

\includepdf[pages=-]{myfile.pdf}

To include just the first page of a PDF:

\includepdf[pages={1}]{myfile.pdf}

Run texdoc pdfpages in a shell to see the complete manual for pdfpages.

How might I schedule a C# Windows Service to perform a task daily?

For those that found the above solutions not working, it's because you may have a this inside your class, which implies an extension method which, as the error message says, only makes sense on a non-generic static class. Your class isn't static. This doesn't seem to be something that makes sense as an extension method, since it's acting on the instance in question, so remove the this.

Can you call ko.applyBindings to bind a partial view?

ko.applyBindings accepts a second parameter that is a DOM element to use as the root.

This would let you do something like:

<div id="one">
  <input data-bind="value: name" />
</div>

<div id="two">
  <input data-bind="value: name" />
</div>

<script type="text/javascript">
  var viewModelA = {
     name: ko.observable("Bob")
  };

  var viewModelB = {
     name: ko.observable("Ted")
  };

  ko.applyBindings(viewModelA, document.getElementById("one"));
  ko.applyBindings(viewModelB, document.getElementById("two"));
</script>

So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings multiple times on the same elements, as you will get multiple event handlers attached.

How to swap two variables in JavaScript

Here's a one-liner, assuming a and b exist already and have values needing to be swapped:

var c=a, a=b, b=c;

As @Kay mentioned, this actually performs better than the array way (almost 2x as fast).

Using "margin: 0 auto;" in Internet Explorer 8

  1. Assuming margin: 0 auto then the element should be centered, but the width is left as-is--whatever it is calculated to be, disregarding any margin settings.
  2. If you set the <INPUT> tag to display:block, then it should be centered with margin: 0 auto.

See Visual formatting model details - calculating widths and margins from the CSS 2.1 specs for more details. Relavent bits include:

In a block formatting context, each box's left outer edge touches the left edge of the containing block.

and

When the total width of the inline boxes on a line is less than the width of the line box containing them, their horizontal distribution within the line box is determined by the 'text-align' property.

finally

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

How to get the total number of rows of a GROUP BY query?

Here is the solution for you

$sql="SELECT count(*) FROM [tablename] WHERE key == ? ";
$sth = $this->db->prepare($sql);
$sth->execute(array($key));
$rows = $sth->fetch(PDO::FETCH_NUM);
echo $rows[0];

How to set <iframe src="..."> without causing `unsafe value` exception?

This one works for me.

import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    selector: 'player',
    templateUrl: './player.component.html',
    styleUrls:['./player.component.scss'],
    
})
export class PlayerComponent implements OnInit{
    @Input()
    id:string; 
    url: SafeResourceUrl;
    constructor (public sanitizer:DomSanitizer) {
    }
    ngOnInit() {
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);      
    }
}

Hosting ASP.NET in IIS7 gives Access is denied?

This is what happened to me:

Get - Post is ok. Working well.

When I try to use Options verb, the server return error like that.

403

Then, beware with urlScan

I add OPTIONS verb to urlscan configuration .ini file, then everything works well.

To check if urlscan is installed or not, open your iis manager, and open ISAPI FILTERS url scan should appear at the list.

How to refresh or show immediately in datagridview after inserting?

Try refreshing the datagrid after each insert

datagridview1.update();
datagridview1.refresh();  

Hope this helps you!

What is the meaning of Bus: error 10 in C

Whenever you are using pointer variables ( the asterix ) such as

char *str = "First string";

you need to asign memory to it

str = malloc(strlen(*str))

Assert a function/method was not called using Mock

This should work for your case;

assert not my_var.called, 'method should not have been called'

Sample;

>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been

What's the best way to detect a 'touch screen' device using JavaScript?

Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}

How to run a shell script on a Unix console or Mac terminal?

If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:

. /path/to/script.sh

or

source /path/to/script.sh

Note that /path/to/script.sh can be relative, for instance . bin/script.sh runs the script.sh in the bin directory under the current directory.

How to re-index all subarray elements of a multidimensional array?

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

Array ( [0] => apple [1] => cherry )

//...
array_multisort($result, SORT_DESC);
//...

Array ( [0] => cherry [1] => apple )

Getting the index of a particular item in array

FindIndex Extension

static class ArrayExtensions
{
    public static int FindIndex<T>(this T[] array, Predicate<T> match)
    {
        return Array.FindIndex(array, match);
    }
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.FindIndex(i => i == 7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.


Bonus: IndexOf Extension

I wrote this first not reading the question properly...

static class ArrayExtensions
{
    public static int IndexOf<T>(this T[] array, T value)
    {
        return Array.IndexOf(array, value);
    }   
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.IndexOf(7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.

How can I suppress all output from a command using Bash?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 )
$ echo $?
0
$ DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
0

nvm is not compatible with the npm config "prefix" option:

Delete and Reset the prefix

$ npm config delete prefix 
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1

Note: Change the version number with the one indicated in the error message.

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.


Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"

When to use malloc for char pointers

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);

How to give a user only select permission on a database

You can use Create USer to create a user

CREATE LOGIN sam
    WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO 

and to Grant (Read-only access) you can use the following

GRANT SELECT TO sam

Hope that helps.

.htaccess rewrite subdomain to directory

I'm not a mod_rewrite expert, I often struggle with it, but I have done this on one of my sites, it might need other flags etc depending on your circumstances. I'm using this:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
RewriteCond %{REQUEST_URI} !^/subdomains/subdomain
RewriteRule ^(.*)$ /subdomains/subdomain/$1 [L] 

Any other rewrite rules for the rest of the site must go afterwards to prevent them from interfering with your subdomain rewrites.

LISTAGG in Oracle to return distinct values

select col1, listaggr(col2,',') within group(Order by col2) from table group by col1 meaning aggregate the strings (col2) into list keeping the order n then afterwards deal with the duplicates as group by col1 meaning merge col1 duplicates in 1 group. perhaps this looks clean and simple as it should be and if in case you want col3 as well just you need to add one more listagg() that is select col1, listaggr(col2,',') within group(Order by col2),listaggr(col3,',') within group(order by col3) from table group by col1

Remove certain characters from a string

You can use Replace function as;

REPLACE ('Your String with cityname here', 'cityname', 'xyz')
--Results
'Your String with xyz here'

If you apply this to a table column where stringColumnName, cityName both are columns of YourTable

SELECT REPLACE(stringColumnName, cityName, '')
FROM YourTable

Or if you want to remove 'cityName' string from out put of a column then

SELECT REPLACE(stringColumnName, 'cityName', '')
FROM yourTable

EDIT: Since you have given more details now, REPLACE function is not the best method to sort your problem. Following is another way of doing it. Also @MartinSmith has given a good answer. Now you have the choice to select again.

SELECT RIGHT (O.Ort, LEN(O.Ort) - LEN(C.CityName)-1) As WithoutCityName
FROM   tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004'

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?

Yes.

Create the .o (as per normal):

g++ -c header.cpp

Create the archive:

ar rvs header.a header.o

Test:

g++ test.cpp header.a -o executable_name

Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:

g++ test.cpp header.cpp -o executable_name

Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.

Hope this helps!

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

Plotting of 1-dimensional Gaussian distribution function

In addition to previous answers, I recommend to first calculate the ratio in the exponent, then taking the square:

def gaussian(x,x0,sigma):
  return np.exp(-np.power((x - x0)/sigma, 2.)/2.)

That way, you can also calculate the gaussian of very small or very large numbers:

In: gaussian(1e-12,5e-12,3e-12)
Out: 0.64118038842995462

Recursively list all files in a directory including files in symlink directories

find -L /var/www/ -type l

# man find
-L     Follow  symbolic links.  When find examines or prints information about files, the information used shall be taken from the

properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.

Link to all Visual Studio $ variables

Anybody working on legacy software using Visual Studio 6.0 will find that $(Configuration) and $(ProjectDir) macro's are not defined. For post-build/pre-build events, give a relative path starting with the location of your .dsw file(workspace) as the starting point. In relative path dot represents the current directory and .. represents the parent directory. Give a relative path to the file that need to be processed. Example: ( copy /y .\..\..\Debug\mylib.dll .\..\MyProject\Debug\ )

Is mathematics necessary for programming?

I guess I am going to be the first person to say you do need math. As others have said math is not all that important for certain aspects of development, but the fundamentals of critical thinking and structured analysis are very important.

More so, math is important in understanding a lot of the fundamentals that go into things like schedulers, optimizations, sorting, protocol management, and a number of other aspects of computers. Though the math involved from a calculation level is not complex (its mostly High school algebra) the theories and applications can be quite complex as a solid understanding of math through calculus will be of great benefit.

Can you get by without it, absolutely, and you shouldnt let a less then thorough knowledge of math hold you back, but if you had the chance, or the inclination I would study as much math as you could, calculus, numeric theory, linear algebra, combinatorics, practical applications, all of it has both practical and theoretical applications in a wide range of computer science.

I have known people who were highly successful on both sides of the fence (those without a strong focus on math, and those who went to school for physics or math), but in both groups they enjoyed numerical problems and learning about algorithms and math theory.

How to have Android Service communicate with Activity

There are three obvious ways to communicate with services:

  1. Using Intents
  2. Using AIDL
  3. Using the service object itself (as singleton)

In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():

void onCreate(Intent i) {
  sInstance = this;
}

Make a static function MyService getInstance(), which returns the static sInstance.

Then in Activity.onCreate() you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread().

The last thing you need to do is to remove the reference to you listener object in Activity.onPause(), otherwise an instance of your activity context will leak, not good.

NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.

Opening A Specific File With A Batch File?

That program would need to have a specific API that you can use from the command line.

For example the following command uses 7Zip to extract a zip file. This only works as 7Zip has an API to do this specific task (using the x switch).

"C:\Program Files\7-Zip\CommandLine\7za.exe" x C:\docs\base-file-structure.zip 

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Detecting EOF in C

while(scanf("%d %d",a,b)!=EOF)
{

//do .....
}

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

A generic solution like so

public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
        Function<Y, Z> function) {
    return input
            .entrySet()
            .stream()
            .collect(
                    Collectors.toMap((entry) -> entry.getKey(),
                            (entry) -> function.apply(entry.getValue())));
}

Example

Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<String, Integer> output = transform(input,
            (val) -> Integer.parseInt(val));

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

sudo service mysqld start

Worked for me, I'm using Centos

Printing with sed or awk a line following a matching pattern

This might work for you (GNU sed):

sed -n ':a;/regexp/{n;h;p;x;ba}' file

Use seds grep-like option -n and if the current line contains the required regexp replace the current line with the next, copy that line to the hold space (HS), print the line, swap the pattern space (PS) for the HS and repeat.

CSS transition shorthand with multiple properties?

By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :

"transition: opacity .5s .5s;"

Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Handling exceptions from Java ExecutorService tasks

I'm using VerboseRunnable class from jcabi-log, which swallows all exceptions and logs them. Very convenient, for example:

import com.jcabi.log.VerboseRunnable;
scheduler.scheduleWithFixedDelay(
  new VerboseRunnable(
    Runnable() {
      public void run() { 
        // the code, which may throw
      }
    },
    true // it means that all exceptions will be swallowed and logged
  ),
  1, 1, TimeUnit.MILLISECONDS
);

How to launch Safari and open URL from iOS app

Try this:

NSString *URL = @"xyz.com";
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:URL]])
{
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL]];
}

How can I create a war file of my project in NetBeans?

Just check in you projects properties >build ->packaging WAR file compress.

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Register DLL file on Windows Server 2008 R2

Counting DISTINCT over multiple columns

This code uses distinct on 2 parameters and provides count of number of rows specific to those distinct values row count. It worked for me in MySQL like a charm.

select DISTINCT DocumentId as i,  DocumentSessionId as s , count(*) 
from DocumentOutputItems   
group by i ,s;

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

Java: How to access methods from another class

You either need to create an object of type Beta in the Alpha class or its method

Like you do here in the Main Beta cBeta = new Beta();

If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like

public class Alpha 
{

    Beta localInstance;

    public Alpha(Beta _beta)
    {
        localInstance = _beta;
    }


     public void DoSomethingAlpha() 
     {
          localInstance.DoSomethingAlpha();     
     }
}

Understanding the order() function

In simple words, order() gives the locations of elements of increasing magnitude.

For example, order(c(10,20,30)) will give 1,2,3 and order(c(30,20,10)) will give 3,2,1.

Does MS SQL Server's "between" include the range boundaries?

if you hit this, and don't really want to try and handle adding a day in code, then let the DB do it..

myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')

If you do include the time portion: make sure it references midnight. Otherwise you can simply omit the time:

myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')

and not worry about it.

How can a Javascript object refer to values in itself?

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

How to reload a page using Angularjs?

You can also try this, after injecting $window service.

$window.location.reload();

Variable declaration in a header file

You can (should) declare it as extern in a header file, and define it in exactly 1 .c file.

Note that that .c file should also use the header and that the standard pattern looks like:

// file.h
extern int x;  // declaration

// file.c
#include "file.h"
int x = 1;    // definition and re-declaration

How to hide a column (GridView) but still access its value?

If I am not mistaken, GridView does not hold the values of BoundColumns that have the attribute visible="false". Two things you may do here, one (as explained in the answer from V4Vendetta) to use Datakeys. Or you can change your BoundColumn to a TemplateField. And in the ItemTemplate, add a control like Label, make its visibility false and give your value to that Label.

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

Create Log File in Powershell

I've been playing with this code for a while now and I have something that works well for me. Log files are numbered with leading '0' but retain their file extension. And I know everyone likes to make functions for everything but I started to remove functions that performed 1 simple task. Why use many word when few do trick? Will likely remove other functions and perhaps create functions out of other blocks. I keep the logger script in a central share and make a local copy if it has changed, or load it from the central location if needed.

First I import the logger:

#Change directory to the script root
cd $PSScriptRoot

#Make a local copy if changed then Import logger
if(test-path "D:\Scripts\logger.ps1"){
    if (Test-Path "\\<server>\share\DCS\Scripts\logger.ps1") {
        if((Get-FileHash "\\<server>\share\DCS\Scripts\logger.ps1").Hash -ne (Get-FileHash "D:\Scripts\logger.ps1").Hash){
            rename-Item -path "..\logger.ps1" -newname "logger$(Get-Date -format 'yyyyMMdd-HH.mm.ss').ps1" -force
            Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force 
        }
    }
}else{
    Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
. "..\logger.ps1"

Define the log file:

$logfile = (get-location).path + "\Log\" + $QProfile.replace(" ","_") + "-$metricEnv-$ScriptName.log"

What I log depends on debug levels that I created:

if ($Debug -ge 1){
    $message = "<$pid>Debug:$Debug`-Adding tag `"MetricClass:temp`" to $host_name`:$metric_name"
    Write-Log $message $logfile "DEBUG"
}

I would probably consider myself a bit of a "hack" when it comes to coding so this might not be the prettiest but here is my version of logger.ps1:

# all logging settins are here on top
param(
    [Parameter(Mandatory=$false)]
        [string]$logFile = "$(gc env:computername).log",
    [Parameter(Mandatory=$false)]
        [string]$logLevel = "DEBUG", # ("DEBUG","INFO","WARN","ERROR","FATAL")
    [Parameter(Mandatory=$false)]
        [int64]$logSize = 10mb,
    [Parameter(Mandatory=$false)]
        [int]$logCount = 25
) 
# end of settings

function Write-Log-Line ($line, $logFile) {
    $logFile | %{ 
           If (Test-Path -Path $_) { Get-Item $_ } 
           Else { New-Item -Path $_ -Force } 
    } | Add-Content -Value $Line -erroraction SilentlyCOntinue
}

function Roll-logFile
{
    #function checks to see if file in question is larger than the paramater specified if it is it will roll a log and delete the oldes log if there are more than x logs.
    param(
        [string]$fileName = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")+".log", 
        [int64]$maxSize = $logSize, 
        [int]$maxCount = $logCount
    )
    $logRollStatus = $true
    if(test-path $filename) {
        $file = Get-ChildItem $filename
        # Start the log-roll if the file is big enough

        #Write-Log-Line "$Stamp INFO Log file size is $($file.length), max size $maxSize" $logFile
        #Write-Host "$Stamp INFO Log file size is $('{0:N0}' -f $file.length), max size $('{0:N0}' -f $maxSize)"
        if($file.length -ge $maxSize) {
            Write-Log-Line "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!" $logFile
            #Write-Host "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!"
            $fileDir = $file.Directory
            $fbase = $file.BaseName
            $fext = $file.Extension
            $fn = $file.name #this gets the name of the file we started with

            function refresh-log-files {
                 Get-ChildItem $filedir | ?{ $_.Extension -match "$fext" -and $_.name -like "$fbase*"} | Sort-Object lastwritetime
            }
            function fileByIndex($index) {
                $fileByIndex = $files | ?{($_.Name).split("-")[-1].trim("$fext") -eq $($index | % tostring 00)}
                #Write-Log-Line "LOGGER: fileByIndex = $fileByIndex" $logFile
                $fileByIndex
            }
            function getNumberOfFile($theFile) {
                $NumberOfFile = $theFile.Name.split("-")[-1].trim("$fext")
                if ($NumberOfFile -match '[a-z]'){
                    $NumberOfFile = "01"
                }
                #Write-Log-Line "LOGGER: GetNumberOfFile = $NumberOfFile" $logFile
                $NumberOfFile
            }

            refresh-log-files | %{
                [int32]$num = getNumberOfFile $_
                Write-Log-Line "LOGGER: checking log file number $num" $logFile
                if ([int32]$($num | % tostring 00) -ge $maxCount) {
                    write-host "Deleting files above log max count $maxCount : $_"
                    Write-Log-Line "LOGGER: Deleting files above log max count $maxCount : $_" $logFile
                    Remove-Item $_.fullName
                }
            }

            $files = @(refresh-log-files)

            # Now there should be at most $maxCount files, and the highest number is one less than count, unless there are badly named files, eg non-numbers
            for ($i = $files.count; $i -gt 0; $i--) {
                $newfilename = "$fbase-$($i | % tostring 00)$fext"
                #$newfilename = getFileNameByNumber ($i | % tostring 00) 
                if($i -gt 1) {
                    $fileToMove = fileByIndex($i-1)
                } else {
                    $fileToMove = $file
                }
                if (Test-Path $fileToMove.PSPath) { # If there are holes in sequence, file by index might not exist. The 'hole' will shift to next number, as files below hole are moved to fill it
                    write-host "moving '$fileToMove' => '$newfilename'"
                    #Write-Log-Line "LOGGER: moving $fileToMove => $newfilename" $logFile
                    # $fileToMove is a System.IO.FileInfo, but $newfilename is a string. Move-Item takes a string, so we need full path
                    Move-Item ($fileToMove.FullName) -Destination $fileDir\$newfilename -Force
                }
            }
        } else {
            $logRollStatus = $false
        }
    } else {
        $logrollStatus = $false
    }
    $LogRollStatus
}


Function Write-Log {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True)]
    [string]
    $Message,

    [Parameter(Mandatory=$False)]
    [String]
    $logFile = "log-$(gc env:computername).log",

    [Parameter(Mandatory=$False)]
    [String]
    $Level = "INFO"
    )
    #Write-Host $logFile
    $levels = ("DEBUG","INFO","WARN","ERROR","FATAL")
    $logLevelPos = [array]::IndexOf($levels, $logLevel)
    $levelPos = [array]::IndexOf($levels, $Level)
    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")

    # First roll the log if needed to null to avoid output
    $Null = @(
        Roll-logFile -fileName $logFile -filesize $logSize -logcount $logCount
    )

    if ($logLevelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong logLevel configuration [$logLevel]" $logFile
    }

    if ($levelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong log level parameter [$Level]" $logFile
    }

    # if level parameter is wrong or configuration is wrong I still want to see the 
    # message in log
    if ($levelPos -lt $logLevelPos -and $levelPos -ge 0 -and $logLevelPos -ge 0){
        return
    }

    $Line = "$Stamp $Level $Message"
    Write-Log-Line $Line $logFile
}

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

Deserialize a json string to an object in python

I thought I lose all my hairs for solving this 'challenge'. I faced following problems:

  1. How to deserialize nested objects, lists etc.
  2. I like constructors with specified fields
  3. I don't like dynamic fields
  4. I don't like hacky solutions

I found a library called jsonpickle which is has proven to be really useful.

Installation:

pip install jsonpickle

Here is a code example with writing nested objects to file:

import jsonpickle


class SubObject:
    def __init__(self, sub_name, sub_age):
        self.sub_name = sub_name
        self.sub_age = sub_age


class TestClass:

    def __init__(self, name, age, sub_object):
        self.name = name
        self.age = age
        self.sub_object = sub_object


john_junior = SubObject("John jr.", 2)

john = TestClass("John", 21, john_junior)

file_name = 'JohnWithSon' + '.json'

john_string = jsonpickle.encode(john)

with open(file_name, 'w') as fp:
    fp.write(john_string)

john_from_file = open(file_name).read()

test_class_2 = jsonpickle.decode(john_from_file)

print(test_class_2.name)
print(test_class_2.age)
print(test_class_2.sub_object.sub_name)

Output:

John
21
John jr.

Website: http://jsonpickle.github.io/

Hope it will save your time (and hairs).

how to use javascript Object.defineProperty

yes no more function extending for setup setter & getter this is my example Object.defineProperty(obj,name,func)

var obj = {};
['data', 'name'].forEach(function(name) {
    Object.defineProperty(obj, name, {
        get : function() {
            return 'setter & getter';
        }
    });
});


console.log(obj.data);
console.log(obj.name);

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

How to cherry-pick multiple commits

Another variant worth mentioning is that if you want the last n commits from a branch, the ~ syntax can be useful:

git cherry-pick some-branch~4..some-branch

In this case, the above command would pick the last 4 commits from a branch called some-branch (though you could also use a commit hash in place of a branch name)

Converting binary to decimal integer output

This is the full thing

binary = input('enter a number: ')
decimal = 0
for digit in binary:
decimal= decimal*2 + int(digit)

print (decimal)

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

Where is the Microsoft.IdentityModel dll

I had this problem, but fixed it by referencing the DLL from "C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll"

Go to reference properties and set Copy Local to True for the DLL. The DLL will now be included in the azure package.

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Change icons of checked and unchecked for Checkbox for Android

This may be achieved by using AppCompatCheckBox. You can use app:buttonCompat="@drawable/selector_drawable" to change the selector.

It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.

When can I use a forward declaration?

As long as you don't need the definition (think pointers and references) you can get away with forward declarations. This is why mostly you'd see them in headers while implementation files typically will pull the header for the appropriate definition(s).

How do I output the results of a HiveQL query to CSV?

I was looking for a similar solution, but the ones mentioned here would not work. My data had all variations of whitespace (space, newline, tab) chars and commas.

To make the column data tsv safe, I replaced all \t chars in the column data with a space, and executed python code on the commandline to generate a csv file, as shown below:

hive -e 'tab_replaced_hql_query' |  python -c 'exec("import sys;import csv;reader = csv.reader(sys.stdin, dialect=csv.excel_tab);writer = csv.writer(sys.stdout, dialect=csv.excel)\nfor row in reader: writer.writerow(row)")'

This created a perfectly valid csv. Hope this helps those who come looking for this solution.

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

Onchange open URL via select - jQuery

You can use this simple code snippet using jQuery to redirect from a drop down menu.

<select id="dynamic-select">
    <option value="" selected>Pick a Website</option>
    <option value="http://www.google.com/">Google</option>
    <option value="http://www.youtube.com/">YouTube</option>
    <option value="http://www.stackoverflow.com/">Stack Overflow</option>
</select>

<script>
    $('#dynamic-select').bind('change', function () { // bind change event to select
        var url = $(this).val(); // get selected value
        if (url != '') { // require a URL
            window.location = url; // redirect
        }
        return false;
    });
</script>

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

How to switch back to 'master' with git?

You need to checkout the branch:

git checkout master

See the Git cheat sheets for more information.

Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.

How can I remove the last character of a string in python?

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

What are database constraints?

  1. UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)

  2. CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)

  3. FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).

How to restart kubernetes nodes?

In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.

  1. (Optional) Swap off

    $ swapoff -a

  2. You have to restart all Docker containers

    $ docker restart $(docker ps -a -q)

  3. Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)

    $ kubectl get nodes

  4. Restart the node

    $ systemctl restart kubelet

  5. Check again the status (now should be in Ready status)

Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready

How to remove a column from an existing table?

If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.

[identity_column] = new int()

How to implement onBackPressed() in Fragments?

Just add addToBackStack while you are transitioning between your fragments like below:

fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();

if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

Ant build failed: "Target "build..xml" does not exist"

in the folder where the build.xml resides run command only -

ant

and not the command - `

ant build.xml

`

. if you are using the ant file as build xml then the below steps helps you Steps : open cmd Prompt >> switch to the project location >>type ant and click enter key

json.net has key method?

JObject.ContainsKey(string propertyName) has been made as public method in 11.0.1 release

Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm

Send private messages to friends

You can use Facebook Chat API to send private messages, here is an example in Ruby using xmpp4r_facebook gem:

sender_chat_id = "-#{sender_uid}@chat.facebook.com"
receiver_chat_id = "-#{receiver_uid}@chat.facebook.com"
message_body = "message body"
message_subject = "message subject"

jabber_message = Jabber::Message.new(receiver_chat_id, message_body)
jabber_message.subject = message_subject

client = Jabber::Client.new(Jabber::JID.new(sender_chat_id))
client.connect
client.auth_sasl(Jabber::SASL::XFacebookPlatform.new(client,
   ENV.fetch('FACEBOOK_APP_ID'), facebook_auth.token,
   ENV.fetch('FACEBOOK_APP_SECRET')), nil)
client.send(jabber_message)
client.close

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

Size of Matrix OpenCV

For 2D matrix:

mat.rows – Number of rows in a 2D array.

mat.cols – Number of columns in a 2D array.

Or: C++: Size Mat::size() const

The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).

For multidimensional matrix, you need to use

int thisSizes[3] = {2, 3, 4};
cv::Mat mat3D(3, thisSizes, CV_32FC1);
// mat3D.size tells the size of the matrix 
// mat3D.size[0] = 2;
// mat3D.size[1] = 3;
// mat3D.size[2] = 4;

Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Using variables inside strings

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Responsive css styles on mobile devices ONLY

What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.

There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.

The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.

To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.

Convert Mercurial project to Git

Another option is to create a free Kiln account -- kiln round trips between git and hg with 100% metadata retention, so you can use it for a one time convert or use it to access a repository using whichever client you prefer.

Sql script to find invalid email addresses

SELECT Email FROM Employee WHERE NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}’, ‘i’);

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

How can I pass a file argument to my bash script using a Terminal command in Linux?

you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:

#!/bin/sh

OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")

if [ $? -ne 0 ]; then
  echo "getopt error"
  exit 1
fi

eval set -- $OPTIONS

while true; do
  case "$1" in
    -h|--help) HELP=1 ;;
    -f|--file) FILE="$2" ; shift ;;
    -g|--foo)  FOO=1 ;;
    -b|--bar)  BAR=1 ;;
    --)        shift ; break ;;
    *)         echo "unknown option: $1" ; exit 1 ;;
  esac
  shift
done

if [ $# -ne 0 ]; then
  echo "unknown option(s): $@"
  exit 1
fi

echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"

see also:

Download large file in python with requests

Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib:

from urllib.request import urlretrieve
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)

Or this way, if you want to save it to a temporary file:

from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)

I watched the process:

watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'

And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?

How can I use MS Visual Studio for Android Development?

That depends on what you actually want to achieve.

You want to keep on making normal Java-based Android application, but use Visual Studio for development? Then it's bad news, as Visual Studio has no built-in java support. Thus, if you use it out-of-the-box, you will lose all Java-specific Eclipse functionality (IntelliSense for Java, Java debugger, wizards, etc) as well as numerous Android plugins (that are Eclipse-specific and won't work with VS).

On the other hand, you can use Mono for Android to develop apps in C# in VS, but they won't look as smooth as the native apps (some functionality might be missing, look-and-feel slightly different, etc.). In that case such app could sell less than a "normal" Java app that looks and feels like all other Java apps.

If you are talking about native Android code (in C/C++), such as games, the news are not as bad. As Visual Studio has no problem with C++, there are numerous ways to make it work:

  1. If you only want to compile your code, you can use the free vs-android toolset. It's essentially a set of build rules telling Visual Studio how to launch Android compiler.

  2. If you want to compile and debug your native code with Visual Studio, you will need something more advanced, such as VisualGDB for Android. It can build/debug your Native code independently, or together with debugging Java code from Eclipse.

How to inject Javascript in WebBrowser control?

this is a solution using mshtml

IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();

IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
    alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

I was just wrestling with a similar problem myself, but didn't want the overhead of a function. I came up with the following query:

SELECT myfield::integer FROM mytable WHERE myfield ~ E'^\\d+$';

Postgres shortcuts its conditionals, so you shouldn't get any non-integers hitting your ::integer cast. It also handles NULL values (they won't match the regexp).

If you want zeros instead of not selecting, then a CASE statement should work:

SELECT CASE WHEN myfield~E'^\\d+$' THEN myfield::integer ELSE 0 END FROM mytable;

Store query result in a variable using in PL/pgSQL

Create Learning Table:

CREATE TABLE "public"."learning" (
    "api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
    "title" varchar(255) COLLATE "default"
);

Insert Data Learning Table:

INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');

Step: 01

CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
        learn_id INT,
        learn_title VARCHAR
) AS $$
BEGIN
    RETURN QUERY SELECT
        api_id,
        title
    FROM
        learning
    WHERE
        title = pattern ;
END ; $$ LANGUAGE 'plpgsql';

Step: 02

SELECT * FROM get_all('Google AI-01');

Step: 03

DROP FUNCTION get_all();

Demo: enter image description here

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

Receive JSON POST with PHP

It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.

This can be simply resolved by first checking if the JSON is valid. i.e.

function isValidJSON($str) {
   json_decode($str);
   return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");

if (strlen($json_params) > 0 && isValidJSON($json_params))
  $decoded_params = json_decode($json_params);

Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

How to override Bootstrap's Panel heading background color?

You can simply add an id attribute to the panel. Like this

<div class="panel-heading" id="mypanelId">Hello world </div>

Then in your custom CSS file:

#mypanelId{
    background-image: none;
    background: rgba(22, 20, 100, 0.8);
    color: white;
     }

.htaccess not working apache

First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.

Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.

Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.

How do you find out the caller function in JavaScript?

As none of previous answers works like what I was looking for(getting just the last function caller not a function as a string or callstack) I post my solution here for those who are like me and hope this will work for them:

_x000D_
_x000D_
function getCallerName(func)_x000D_
{_x000D_
  if (!func) return "anonymous";_x000D_
  let caller = func.caller;_x000D_
  if (!caller) return "anonymous";_x000D_
  caller = caller.toString();_x000D_
  if (!caller.trim().startsWith("function")) return "anonymous";_x000D_
  return caller.substring(0, caller.indexOf("(")).replace("function","");_x000D_
}_x000D_
_x000D_
_x000D_
//  Example of how to use "getCallerName" function_x000D_
_x000D_
function Hello(){_x000D_
console.log("ex1  =>  " + getCallerName(Hello));_x000D_
}_x000D_
_x000D_
function Main(){_x000D_
Hello();_x000D_
_x000D_
// another example_x000D_
console.log("ex3  =>  " + getCallerName(Main));_x000D_
}_x000D_
_x000D_
Main();
_x000D_
_x000D_
_x000D_